public function postLogin() { $output = new \Symfony\Component\Console\Output\ConsoleOutput(2); // show the form // validate the info, create rules for the inputs $rules = array('email' => 'required|email', 'password' => 'required|alphaNum|min:3'); // run the validation rules on the inputs from the form $validator = Validator::make(Input::all(), $rules); // if the validator fails, redirect back to the form if ($validator->fails()) { return Redirect::to('auth/login')->withErrors($validator)->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form } else { // create our user data for the authentication $admindata = array('email' => Input::get('email'), 'password' => Input::get('password')); //return Redirect::to(Hash::make((Input::get('password')))); // attempt to do the login $output->writeln('postlogin'); if (Auth::attempt($admindata)) { // validation successful! // redirect them to the secure section or whatever // return Redirect::to('secure'); // for now we'll just echo success (even though echoing in a controller is bad) echo 'SUCCESS!'; //return Redirect::to('SUCCESS'); } else { $admin = Auth::admin(); // validation not successful, send back to form return Redirect::to($admin); } } }
/** * @param \Symfony\Component\Console\Output\OutputInterface $output * * @return bool */ protected function loadRoboFile($output) { // If we have not been provided an output object, make a temporary one. if (!$output) { $output = new \Symfony\Component\Console\Output\ConsoleOutput(); } // If $this->roboClass is a single class that has not already // been loaded, then we will try to obtain it from $this->roboFile. // If $this->roboClass is an array, we presume all classes requested // are available via the autoloader. if (is_array($this->roboClass) || class_exists($this->roboClass)) { return true; } if (!file_exists($this->dir)) { $output->writeln("<error>Path `{$this->dir}` is invalid; please provide a valid absolute path to the Robofile to load.</error>"); return false; } $realDir = realpath($this->dir); $roboFilePath = $realDir . DIRECTORY_SEPARATOR . $this->roboFile; if (!file_exists($roboFilePath)) { $requestedRoboFilePath = $this->dir . DIRECTORY_SEPARATOR . $this->roboFile; $output->writeln("<error>Requested RoboFile `{$requestedRoboFilePath}` is invalid, please provide valid absolute path to load Robofile</error>"); return false; } require_once $roboFilePath; if (!class_exists($this->roboClass)) { $output->writeln("<error>Class " . $this->roboClass . " was not loaded</error>"); return false; } return true; }
public function fire($job, $data) { $output = new Symfony\Component\Console\Output\ConsoleOutput(); // Process the job received from the queue $output->writeln("out of date. do something about this. alert people. send letters to congress."); $output->writeln(print_r($data)); $job->delete(); }
/** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return Response */ public function store(Request $request) { $output = new \Symfony\Component\Console\Output\ConsoleOutput(2); $output->writeln("store"); $rules = array('id' => 'required|integer', 'nama' => 'required|min:5', 'alamat' => 'required|min:5', 'no_telp' => 'required|min:6', 'jenis' => 'required'); $validator = Validator::make(Input::all(), $rules); // process the login if ($validator->fails()) { return $validator->messages()->toJson(); } else { //cek apakah id yang sama sudah ada $pengguna = Pengguna::find(Input::get('id')); if ($pengguna) { $output->writeln("s1"); return "ID harus unik"; } else { //validate phone number if (!preg_match('/^[0-9]+$/', Input::get('no_telp'))) { return "No. Telp tidak valid. Hanya boleh mengandung angka"; } $output->writeln("s2"); $jenis = ""; if (Input::get('jenis') == 1) { $jenis = "Mahasiswa"; } else { if (Input::get('jenis') == 2) { $jenis = "Dosen"; } else { if (Input::get('jenis') == 3) { $jenis = "Karyawan"; } else { return "Jenis tidak valid"; } } } // store $pengguna = new pengguna(); $pengguna->id = Input::get('id'); $pengguna->nama = Input::get('nama'); $pengguna->alamat = Input::get('alamat'); $pengguna->no_telp = Input::get('no_telp'); $pengguna->jenis = $jenis; $pengguna->save(); return 1; } } }
/** * Initialize a container with all of the default Robo services. * IMPORTANT: after calling this method, clients MUST call: * * $dispatcher = $container->get('eventDispatcher'); * $app->setDispatcher($dispatcher); * * Any modification to the container should be done prior to fetching * objects from it. * * It is recommended to use \Robo::createDefaultContainer() * instead, which does all required setup for the caller, but has * the limitation that the container it creates can only be * extended, not modified. * * @param \League\Container\ContainerInterface $container * @param \Symfony\Component\Console\Application $app * @param \Robo\Config $config * @param null|\Symfony\Component\Console\Input\InputInterface $input * @param null|\Symfony\Component\Console\Output\OutputInterface $output */ public static function configureContainer(ContainerInterface $container, SymfonyApplication $app, Config $config, $input = null, $output = null) { // Self-referential container refernce for the inflector $container->add('container', $container); static::setContainer($container); // Create default input and output objects if they were not provided if (!$input) { $input = new StringInput(''); } if (!$output) { $output = new \Symfony\Component\Console\Output\ConsoleOutput(); } $config->setDecorated($output->isDecorated()); $container->share('application', $app); $container->share('config', $config); $container->share('input', $input); $container->share('output', $output); // Register logging and related services. $container->share('logStyler', \Robo\Log\RoboLogStyle::class); $container->share('logger', \Robo\Log\RoboLogger::class)->withArgument('output')->withMethodCall('setLogOutputStyler', ['logStyler']); $container->add('progressBar', \Symfony\Component\Console\Helper\ProgressBar::class)->withArgument('output'); $container->share('progressIndicator', \Robo\Common\ProgressIndicator::class)->withArgument('progressBar')->withArgument('output'); $container->share('resultPrinter', \Robo\Log\ResultPrinter::class); $container->add('simulator', \Robo\Task\Simulator::class); $container->share('globalOptionsEventListener', \Robo\GlobalOptionsEventListener::class); $container->share('collectionProcessHook', \Robo\Collection\CollectionProcessHook::class); $container->share('hookManager', \Consolidation\AnnotatedCommand\Hooks\HookManager::class)->withMethodCall('addResultProcessor', ['collectionProcessHook', '*']); $container->share('alterOptionsCommandEvent', \Consolidation\AnnotatedCommand\Options\AlterOptionsCommandEvent::class)->withArgument('application'); $container->share('eventDispatcher', \Symfony\Component\EventDispatcher\EventDispatcher::class)->withMethodCall('addSubscriber', ['globalOptionsEventListener'])->withMethodCall('addSubscriber', ['alterOptionsCommandEvent'])->withMethodCall('addSubscriber', ['hookManager']); $container->share('formatterManager', \Consolidation\OutputFormatters\FormatterManager::class)->withMethodCall('addDefaultFormatters', [])->withMethodCall('addDefaultSimplifiers', []); $container->share('commandProcessor', \Consolidation\AnnotatedCommand\CommandProcessor::class)->withArgument('hookManager')->withMethodCall('setFormatterManager', ['formatterManager'])->withMethodCall('setDisplayErrorFunction', [function ($output, $message) use($container) { $logger = $container->get('logger'); $logger->error($message); }]); $container->share('commandFactory', \Consolidation\AnnotatedCommand\AnnotatedCommandFactory::class)->withMethodCall('setCommandProcessor', ['commandProcessor']); $container->add('collection', \Robo\Collection\Collection::class); $container->add('collectionBuilder', \Robo\Collection\CollectionBuilder::class); static::addInflectors($container); // Make sure the application is appropriately initialized. $app->setAutoExit(false); }
public function list_nodes($availability_zone_name, $availability_zone_friendly_name) { $output = new Symfony\Component\Console\Output\ConsoleOutput(); $success = false; $integration = Integration::find($this->db_integration_id); $nodes = []; // We need to measure how often this actually matters. I wonder if UK_IDENTITY_ENDPOINT is only // for UK-based companies, or if it's needed to connect to Hong Kong. try { $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array('username' => $integration->authorization_field_1, 'apiKey' => $integration->authorization_field_2)); } catch (Exception $e) { $client = new Rackspace(Rackspace::UK_IDENTITY_ENDPOINT, array('username' => $integration->authorization_field_1, 'apiKey' => $integration->authorization_field_2)); } $computeService = $client->computeService(null, $availability_zone_name, 'publicURL'); $serverList = $computeService->serverList(); foreach ($serverList as $server) { $server_ips = []; $private_dns = ""; $public_dns = ""; $server_status = ""; if (strtolower($server->status) == "active") { foreach ($server->addresses->public as $ip) { array_push($server_ips, $ip->addr); } foreach ($server->addresses->private as $ip) { array_push($server_ips, $ip->addr); } $public_dns = null; foreach ($server->addresses->public as $pubdns) { if (strlen($pubdns->addr) < 16) { $public_dns = $pubdns->addr; } } $private_dns = null; foreach ($server->addresses->private as $pdns) { if (strlen($pubdns->addr) < 16) { $private_dns = $pdns->addr; } } $server_status = 'running'; } else { switch (strtolower($server->status)) { case "active": $server_status = 'running'; break; case "build": $server_status = 'starting'; break; default: continue; } } // Get image info so we can get platform info $imageService = $client->imageService("cloudImages", $availability_zone_name); $imageInfo = $imageService->getImage($server->image->id); $platform = $imageInfo['os_type']; array_push($nodes, array('service_provider_status' => $server_status, 'service_provider_base_image_id' => $server->image->id, 'service_provider_id' => $server->id, 'private_dns_name' => $private_dns, 'public_dns_name' => $public_dns, 'network_interfaces' => [], 'service_provider_cluster_id' => null, 'service_provider_ip_addresses' => $server_ips, 'availability_zone_friendly' => $availability_zone_friendly_name, 'availability_zone_name' => $availability_zone_name, 'platform' => ucfirst($platform))); } // If nodes is empty, make attempt to list them through the legacy api. if (empty($nodes)) { $output->writeln("robby's account"); } return $nodes; }
public function foundAdminWithEmail() { $output = new \Symfony\Component\Console\Output\ConsoleOutput(2); // Getting all post data $email = Input::get('email'); $column = 'email'; // This is the name of the column you wish to search $n = Admin::where($column, '=', $email)->count(); $output->writeln($n); $result = null; if ($n > 0) { $result = 'Email sudah terdaftar'; } else { $output->writeln('else'); } echo json_encode($result); }
require_once APPLICATION_DIR . 'cvsgit/command/RemoveCommand.php'; require_once APPLICATION_DIR . 'cvsgit/command/StatusCommand.php'; require_once APPLICATION_DIR . 'cvsgit/command/DiffCommand.php'; require_once APPLICATION_DIR . 'cvsgit/command/LogCommand.php'; require_once APPLICATION_DIR . 'cvsgit/command/ConfigCommand.php'; require_once APPLICATION_DIR . 'cvsgit/command/HistoryCommand.php'; require_once APPLICATION_DIR . 'cvsgit/command/WhatChangedCommand.php'; require_once APPLICATION_DIR . 'cvsgit/command/AnnotateCommand.php'; require_once APPLICATION_DIR . 'cvsgit/command/DieCommand.php'; require_once APPLICATION_DIR . 'cvsgit/command/CheckoutCommand.php'; require_once APPLICATION_DIR . 'cvsgit/model/CvsGitModel.php'; require_once APPLICATION_DIR . 'cvsgit/model/ArquivoModel.php'; use CVS\CVSApplication as CVS; define('CONFIG_DIR', getenv('HOME') . '/.cvsgit/'); try { /** * Instancia app e define arquivo de configração */ $oCVS = new CVS(); /** * Adiciona programas */ $oCVS->addCommands(array(new \CVS\HistoryCommand(), new \CVS\InitCommand(), new \CVS\PushCommand(), new \CVS\AddCommand(), new \CVS\TagCommand(), new \CVS\RemoveCommand(), new \CVS\StatusCommand(), new \CVS\PullCommand(), new \CVS\DiffCommand(), new \CVS\LogCommand(), new \CVS\ConfigCommand(), new \CVS\WhatChangedCommand(), new \CVS\AnnotateCommand(), new \CVS\DieCommand(), new \CVS\CheckoutCommand())); /** * Executa aplicacao */ $oCVS->run(); } catch (Exception $oErro) { $oOutput = new \Symfony\Component\Console\Output\ConsoleOutput(); $oOutput->writeln("<error>\n [You Tá The Brinqueichon Uite Me, cara?]\n " . $oErro->getMessage() . "\n</error>"); }
case 'yml': case 'yaml': //$driver = new YamlDriver( $mappingPaths ); //$driver->setFileExtension('.yml'); $ymlConfig = Setup::createYAMLMetadataConfiguration($mappingPaths, $env == 'dev'); //$ymlConfig->setMetadataDriverImpl( $driver ); $entityManager = EntityManager::create($dbParams, $ymlConfig); break; case 'annotation': $annotationConfig = Setup::createAnnotationMetadataConfiguration($mappingPaths, $env == 'dev'); $entityManager = EntityManager::create($dbParams, $annotationConfig); break; default: throw new \Exception("Config: Unknown mapping type of '{$mappingType}'."); } if (empty($entityManager)) { throw new \Exception("Config: Unable to instantiate an entity manager. Please check the configuration."); } $helperSet = new HelperSet(array('db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($entityManager->getConnection()), 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($entityManager))); $app = new DoctrineConsole(); $app->setCatchExceptions(false); $app->setDispatcher($dispatcher); $app->setHelperSet($helperSet); ConsoleRunner::addCommands($app); $commands = array(new \Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\LatestCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand()); $app->addCommands($commands); $app->run(); } catch (\Exception $e) { $output = new \Symfony\Component\Console\Output\ConsoleOutput(); $app->renderException($e, $output->getErrorOutput()); }
$classLoader->register(); $dcConfig = new \Doctrine\ORM\Configuration(); $dcConfig->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache()); $dcConfig->setProxyDir(BASE_PATH . '/library/Orm/Proxies'); $dcConfig->setProxyNamespace('Orm\\Proxies'); $dcConfig->setEntityNamespaces(array('Orm\\Entity')); $dcConfig->setMetadataDriverImpl(new \Doctrine\ORM\Mapping\Driver\StaticPHPDriver(realpath(BASE_PATH . '/library/Orm/Entity'))); // create db connection (use Zend_Db like at bootstrap) require_once 'Zend/Db.php'; $dbConfig = $cmsConfig['db']; $dbAdapter = \Zend_Db::factory($dbConfig['adapter'], $dbConfig); $connectionOptions = array('pdo' => $dbAdapter->getConnection(), 'dbname' => $dbConfig['dbname']); // create entity manager $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $dcConfig, new Doctrine\Common\EventManager()); // Create OutputWriter $output = new \Symfony\Component\Console\Output\ConsoleOutput(); $migrationOutputWriter = new \Doctrine\DBAL\Migrations\OutputWriter(function ($message) use($output) { $output->writeln($message); }); // create migration commands $migrationCommands = array(new \Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\LatestCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand()); // set config to migration commands $configuration = new \Doctrine\DBAL\Migrations\Configuration\Configuration($em->getConnection(), $migrationOutputWriter); $configuration->setMigrationsTableName('migrations'); $configuration->setMigrationsNamespace('Orm\\Migrations'); $configuration->setMigrationsDirectory(BASE_PATH . '/library/Orm/Migrations/'); $configuration->registerMigrationsFromDirectory(BASE_PATH . '/library/Orm/Migrations/'); foreach ($migrationCommands as $command) { $command->setMigrationConfiguration($configuration); } // Create and run ConsoleRunner
#!/usr/bin/env php <?php use Symfony\Component\Console\Application; require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../app/bootstrap.php'; $application = new Application(); // Migrations Commands $configure = new \Doctrine\DBAL\Migrations\Configuration\Configuration($c['db.eng']); $configure->setMigrationsNamespace('EngMigration'); $configure->setMigrationsDirectory(DOCROOT . '/database-migration/versions'); $configure->registerMigrationsFromDirectory($configure->getMigrationsDirectory()); $configure->setMigrationsTableName('english_migration_versions'); $symfony_output = new \Symfony\Component\Console\Output\ConsoleOutput(); $symfony_output->setDecorated(true); $configure->setOutputWriter(new \Doctrine\DBAL\Migrations\OutputWriter(function ($msg) use($symfony_output) { $symfony_output->writeln($msg); })); $helperSet = new \Symfony\Component\Console\Helper\HelperSet(array('db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($c['db.eng']), 'dialog' => new \Symfony\Component\Console\Helper\DialogHelper(), 'configuration' => new \Doctrine\DBAL\Migrations\Tools\Console\Helper\ConfigurationHelper($c['db.eng'], $configure))); $application->setHelperSet($helperSet); $application->addCommands(array(new \Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand())); $application->add(new \Doctrine\Bundle\DoctrineBundle\Command\CreateDatabaseDoctrineCommand()); $application->add(new \Doctrine\Bundle\DoctrineBundle\Command\DropDatabaseDoctrineCommand()); $application->add(new \Doctrine\Bundle\DoctrineBundle\Command\GenerateEntitiesDoctrineCommand()); $application->add(new \Doctrine\Bundle\DoctrineBundle\Command\ImportMappingDoctrineCommand()); $application->add(new \Eng\Core\Command\Util\VoiceManager($c)); $application->run();
/** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return Response */ public function update(Request $request, $id) { $output = new \Symfony\Component\Console\Output\ConsoleOutput(2); $output->writeln("update"); $rules = array('nama' => 'required|min:5', 'status' => 'required', 'ketersediaan' => 'required', 'lokasi' => 'required', 'jenis' => 'required'); $validator = Validator::make(Input::all(), $rules); // process the update if ($validator->fails()) { return $validator->messages()->toJson(); } else { // update if (Input::get('ketersediaan') == 1) { $ketersediaan = "Tersedia"; } else { if (Input::get('ketersediaan') == 0) { $ketersediaan = "Sedang Digunakan"; } else { return "Ketersediaan tidak valid"; } } if (Input::get('status') == 0) { $status = "Rusak"; } else { if (Input::get('status') == 1) { $status = "Baik"; } else { if (Input::get('status') == 2) { $status = "Perbaikan"; } else { return "Status tidak valid"; } } } $peralatan = Peralatan::find($id); if (!$peralatan) { return "Not Found"; } $peralatan->nama = Input::get('nama'); $peralatan->status = $status; $peralatan->ketersediaan = $ketersediaan; $peralatan->lokasi = Input::get('lokasi'); $peralatan->jenis = Input::get('jenis'); $peralatan->save(); return 1; } }
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ $rootDir = __DIR__; require_once __DIR__ . '/app/bootstrap.php.cache'; // reset data $fs = new \Symfony\Component\Filesystem\Filesystem(); $output = new \Symfony\Component\Console\Output\ConsoleOutput(); // does the parent directory have a parameters.yml file if (is_file(__DIR__ . '/../parameters.demo.yml')) { $fs->copy(__DIR__ . '/../parameters.demo.yml', __DIR__ . '/app/config/parameters.yml', true); } if (!is_file(__DIR__ . '/app/config/parameters.yml')) { $output->writeln('<error>no default app/config/parameters.yml file</error>'); exit(0); } /** * @param $commands * @param \Symfony\Component\Console\Output\ConsoleOutput $output * @return void */ function execute_commands($commands, $output) { foreach ($commands as $command) {
* This file is part of the Sonata package. * * (c) Thomas Rabaix <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ if (!is_file('composer.json')) { throw new \RuntimeException('Can\'t find a composer.json file. Make sure to start this script from the project root folder'); } $rootDir = __DIR__ . '/..'; require_once __DIR__ . '/../app/bootstrap.php.cache'; use Symfony\Component\Console\Output\OutputInterface; // reset data $fs = new \Symfony\Component\Filesystem\Filesystem(); $output = new \Symfony\Component\Console\Output\ConsoleOutput(); // does the parent directory have a parameters.yml file if (is_file(__DIR__ . '/../../parameters.demo.yml')) { $fs->copy(__DIR__ . '/../../parameters.demo.yml', __DIR__ . '/../app/config/parameters.yml', true); } if (!is_file(__DIR__ . '/../app/config/parameters.yml')) { $output->writeln('<error>no default apps/config/parameters.yml file</error>'); exit(1); } /** * @param $commands * @param \Symfony\Component\Console\Output\ConsoleOutput $output * * @return boolean */ function execute_commands($commands, $output)
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ $rootDir = __DIR__; require_once __DIR__ . '/app/bootstrap.php.cache'; // reset data $fs = new \Symfony\Component\Filesystem\Filesystem(); $output = new \Symfony\Component\Console\Output\ConsoleOutput(); // does the parent directory have a parameters.yml file if (is_file(__DIR__ . '/../parameters.demo.yml')) { $fs->copy(__DIR__ . '/../parameters.demo.yml', __DIR__ . '/app/config/parameters.yml', true); } if (!is_file(__DIR__ . '/app/config/parameters.yml')) { $output->writeln('<error>no default apps/config/parameters.yml file</error>'); exit(1); } /** * @param $commands * @param \Symfony\Component\Console\Output\ConsoleOutput $output * * @return boolean */ function execute_commands($commands, $output) {
public function fire($job, $data) { $output = new Symfony\Component\Console\Output\ConsoleOutput(); $node = Node::find($data['message']['node_id']); $s3 = \Aws\S3\S3Client::factory(array('key' => 'AKIAIUCV4E2L4HDCDOUA', 'secret' => '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', 'region' => 'us-east-1')); $all_keys = Key::where('integration_id', '=', $data['message']['integration_id'])->get(); foreach ($all_keys as $pem_key_reference) { if ($pem_key_reference->remote_url) { $unique_key_name = rand(0, 9999) . $pem_key_reference->remote_url; $key_bucket = App::isLocal() ? 'devkeys.nosprawl.software' : 'keys.nosprawl.software'; $s3->getObject(array('Bucket' => $key_bucket, 'Key' => $pem_key_reference->remote_url, 'SaveAs' => '/tmp/' . $unique_key_name)); // Shouldn't need these two lines at all. exec('chmod 400 /tmp/' . $unique_key_name); $empty = null; $s3_resource_root = App::isLocal() ? 'http://agent.nosprawl.software/dev/' : 'http://agent.nosprawl.software/'; $latest_version = exec("curl -s " . $s3_resource_root . "latest", $empty); $latest_version_url = $s3_resource_root . $latest_version; $ssh = new Net_SSH2($node->public_dns_name); $ssh->enableQuietMode(); $ssh->enablePTY(); $key = new Crypt_RSA(); $key->loadKey(file_get_contents('/tmp/' . $unique_key_name)); exec('rm -rf /tmp/' . $unique_key_name); if (!$ssh->login($pem_key_reference->username, $key)) { continue; } else { $possible_installers = ["yum", "apt-get"]; foreach ($possible_installers as $possible_installer) { $installer_check_result = false; $found = false; $ssh->exec("sudo " . $possible_installer . " -y install ruby"); $install_result = $ssh->read(); $output->writeln($install_result); $install_exit_status = $ssh->getExitStatus(); if ($install_exit_status == 0) { Queue::push('DeployAgentToNode', array('message' => array('node_id' => $node->id, 'integration_id' => $node->integration->id))); return $job->delete(); } } } } else { $output->writeln("This is what we do if all we have is a password."); continue; } } // If we got to this point we were unable to install Curl automatically. $problem = new Problem(); $problem->description = "Couldn't install Curl."; $problem->reason = "Unable to automatically install Curl. Please install it manually."; $problem->node_id = $node->id; $problem->save(); $remediation = new Remediation(); $remediation->name = "Retry Deployment"; $remediation->queue_name = "DeployAgentToNode"; $remediation->problem_id = $problem->id; $remediation->save(); $remediation = new Remediation(); $remediation->name = "Cancel"; $remediation->queue_name = "CancelDeployAgentToNode"; $remediation->problem_id = $problem->id; $remediation->save(); return $job->delete(); }
public function fire($job, $data) { $output = new Symfony\Component\Console\Output\ConsoleOutput(); $node = Node::find($data['message']['node_id']); // Make sure node exists if (!$node) { $output->writeln("node doesn't exist anymore. no need for this job."); return $job->delete(); } // Make sure node isn't terminated /*if($node->service_provider_status == "terminated") { return $job->delete(); }*/ // Make sure node is running if ($node->service_provider_status != "running") { return $job->release(); $output->writeln("node is not running"); } // Keys are always stored on S3. This is the NoS account. $s3 = \Aws\S3\S3Client::factory(array('key' => 'AKIAIUCV4E2L4HDCDOUA', 'secret' => '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', 'region' => 'us-east-1')); $all_keys = Key::where('integration_id', '=', $data['message']['integration_id'])->get(); $unique_key_name = null; $cmdout = null; // Make sure the user has added credentials for this integration if ($all_keys->isEmpty()) { $problem = new Problem(); $problem->description = "Couldn't deploy agent"; $problem->reason = "No credentials added for this integration.<br /><br />You can manage your integration credentials on the <a href='#'>integrations</a> page.<br />Or <a href='#'>deploy manually</a>."; $problem->node_id = $node->id; $problem->long_message = true; $problem->save(); $remediation = new Remediation(); $remediation->name = "Cancel"; $remediation->queue_name = "CancelDeployAgentToNode"; $remediation->problem_id = $problem->id; $remediation->save(); $remediation = new Remediation(); $remediation->name = "Retry"; $remediation->queue_name = "DeployAgentToNode"; $remediation->problem_id = $problem->id; $remediation->save(); return $job->delete(); } $eventually_logged_in = false; foreach ($all_keys as $pem_key_reference) { if ($pem_key_reference->remote_url) { $unique_key_name = rand(0, 9999) . $pem_key_reference->remote_url; $key_bucket = App::isLocal() ? 'devkeys.nosprawl.software' : 'keys.nosprawl.software'; $s3->getObject(array('Bucket' => $key_bucket, 'Key' => $pem_key_reference->remote_url, 'SaveAs' => '/tmp/' . $unique_key_name)); exec('chmod 400 /tmp/' . $unique_key_name); $empty = null; $s3_resource_root = App::isLocal() ? 'http://agent.nosprawl.software/dev/' : 'http://agent.nosprawl.software/'; $latest_version = exec("curl -s " . $s3_resource_root . "latest", $empty); $latest_version_url = $s3_resource_root . $latest_version; $ssh = new Net_SSH2($node->public_dns_name); $ssh->enableQuietMode(); $ssh->enablePTY(); $key = new Crypt_RSA(); $key->loadKey(file_get_contents('/tmp/' . $unique_key_name)); exec('rm -rf /tmp/' . $unique_key_name); if (!$ssh->login($pem_key_reference->username, $key)) { $output->writeln("ssh fail."); continue; } else { $output->writeln("we are in ssh just fine."); // Let's look for any problems running sudo first. $ssh->exec("sudo whoami"); $exit_status = $ssh->getExitStatus(); if (!$exit_status && $exit_status != 0) { // User can't sudo without a password. We can't auto-install. $problem = new Problem(); $problem->description = "Couldn't deploy agent"; $problem->reason = "User '" . $pem_key_reference->username . "' doesn't have passwordless sudo priviliges. Please either enable it or <a class='problem_cta_btn' href='#'>Manually deploy the NoSprawl Agent</a>"; $problem->node_id = $node->id; $problem->long_message = true; $problem->save(); $remediation = new Remediation(); $remediation->name = "Cancel"; $remediation->queue_name = "CancelDeployAgentToNode"; $remediation->problem_id = $problem->id; $remediation->save(); $remediation = new Remediation(); $remediation->name = "Retry"; $remediation->queue_name = "DeployAgentToNode"; $remediation->problem_id = $problem->id; $remediation->save(); return $job->delete(); } $result = $ssh->read(); $output->writeln($result); // Check for problems with curl $ssh->exec("curl --help"); $curl_result = $ssh->read(); $curl_exit_status = $ssh->getExitStatus(); if ($curl_exit_status != 0) { $problem = new Problem(); $problem->description = "Couldn't deploy agent"; $problem->reason = "cURL isn’t installed."; $problem->node_id = $node->id; $problem->save(); $remediation = new Remediation(); $remediation->name = "Install cURL"; $remediation->queue_name = "InstallCurlAndRetryDeployment"; $remediation->problem_id = $problem->id; $remediation->save(); $remediation = new Remediation(); $remediation->name = "Cancel"; $remediation->queue_name = "CancelDeployAgentToNode"; $remediation->problem_id = $problem->id; $remediation->save(); return $job->delete(); } $ssh->exec("(curl " . $latest_version_url . " > nosprawl-installer.rb) && sudo ruby nosprawl-installer.rb && rm -rf nosprawl-installer.rb"); $installer_result = $ssh->read(); $installer_exit_status = $ssh->getExitStatus(); if ($installer_exit_status == 0) { // Everything is good. $node->limbo = false; $node->save(); return $job->delete(); } else { $problem = new Problem(); $problem->description = "Couldn't deploy agent"; $problem->reason = "Ruby isn't installed."; $problem->node_id = $node->id; $problem->save(); $remediation = new Remediation(); $remediation->name = "Install"; $remediation->queue_name = "InstallRubyAndRetryDeployment"; $remediation->problem_id = $problem->id; $remediation->save(); $remediation = new Remediation(); $remediation->name = "Cancel"; $remediation->queue_name = "CancelDeployAgentToNode"; $remediation->problem_id = $problem->id; $remediation->save(); return $job->delete(); } return $job->delete(); } } else { $output->writeln("This is what we do if all we have is a password."); continue; } } if (!$eventually_logged_in) { $problem = new Problem(); $problem->description = "Couldn't deploy agent"; $problem->reason = "None of the credentials provided were sufficient to connect to this node. Manage your credentials on the <a href='#'>integrations</a> page.<br />Or <a href='#'>deploy manually</a>."; $problem->node_id = $node->id; $problem->long_message = true; $problem->save(); $remediation = new Remediation(); $remediation->name = "Cancel"; $remediation->queue_name = "CancelDeployAgentToNode"; $remediation->problem_id = $problem->id; $remediation->save(); $remediation = new Remediation(); $remediation->name = "Retry"; $remediation->queue_name = "DeployAgentToNode"; $remediation->problem_id = $problem->id; $remediation->save(); return $job->delete(); } }
* This file is part of the Sonata package. * * (c) Thomas Rabaix <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ if (!is_file('composer.json')) { throw new \RuntimeException('This script must be started from the project root folder'); } $rootDir = __DIR__ . '/..'; require_once __DIR__ . '/../app/bootstrap.php.cache'; use Symfony\Component\Console\Output\OutputInterface; // reset data $fs = new \Symfony\Component\Filesystem\Filesystem(); $output = new \Symfony\Component\Console\Output\ConsoleOutput(); // does the parent directory have a parameters.yml file if (is_file(__DIR__ . '/../../parameters.demo.yml')) { $fs->copy(__DIR__ . '/../../parameters.demo.yml', __DIR__ . '/../app/config/parameters.yml', true); } if (!is_file(__DIR__ . '/../app/config/parameters.yml')) { $output->writeln('<error>no default apps/config/parameters.yml file</error>'); exit(1); } /** * @param $commands * @param \Symfony\Component\Console\Output\ConsoleOutput $output * * @return boolean */ function execute_commands($commands, $output)
* This file is part of the Sonata package. * * (c) Thomas Rabaix <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ if (!is_file('composer.json')) { throw new \RuntimeException('This script must be started from the project root folder'); } $rootDir = __DIR__ . '/..'; require_once __DIR__ . '/../app/bootstrap.php.cache'; use Symfony\Component\Console\Output\OutputInterface; // reset data $fs = new \Symfony\Component\Filesystem\Filesystem(); $output = new \Symfony\Component\Console\Output\ConsoleOutput(); /** * @param $commands * @param \Symfony\Component\Console\Output\ConsoleOutput $output * * @return boolean */ function execute_commands($commands, $output) { foreach ($commands as $command) { $output->writeln(sprintf('<info>Executing : </info> %s', $command)); $p = new \Symfony\Component\Process\Process($command); $p->setTimeout(null); $p->run(function ($type, $data) use($output) { $output->write($data, false, OutputInterface::OUTPUT_RAW); });
public function fire($job, $data) { try { $output = new Symfony\Component\Console\Output\ConsoleOutput(); $packages = $data['message']['pkginfo']['installed']; $matched_public_ip = false; $node = null; $matches = 0; $ip_node_id_count = array(); $all_matched_ips = IpAddress::whereIn('address', $data['message']['ips'])->get(); if ($all_matched_ips) { foreach ($all_matched_ips as $db_ip) { if (!isset($ip_node_id_count[$db_ip->node_id])) { $ip_node_id_count[$db_ip->node_id] = 1; } else { $ip_node_id_count[$db_ip->node_id]++; } } } else { $output->writeln("Couldn't find any ip addresses in the database from this report."); return $job->delete(); } asort($ip_node_id_count, SORT_NUMERIC); end($ip_node_id_count); $matched_node_id = key($ip_node_id_count); $node = Node::find($matched_node_id); if ($node) { $node->managed = true; $node->limbo = false; $node->hostname = $data['message']['hostname']; $node->virtual = $data['message']['virtual']; $node->last_updated = $data['message']['pkginfo']['last_updated']; $node->package_manager = $data['message']['pkginfo']['package_manager']; if (!$node->platform) { $node->platform = $data['message']['pkginfo']['platform']; } $node->save(); $query_version_vendor_query_pairs = array(); $packages_index = array(); foreach ($packages as $package_version) { // Get rid of debian epochs //https://ask.fedoraproject.org/en/question/6987/whats-the-meaning-of-the-number-which-appears-sometimes-when-i-use-yum-to-install-a-fedora-package-before-a-colon-at-the-beginning-of-the-name-of-the/ $explode_epoch = explode(":", $package_version[1]); if (isset($explode_epoch[1])) { array_shift($explode_epoch); $package_version[1] = implode(":", $explode_epoch); } // Get rid of trailing periods. Note: Explore improving the regex on the agent because this really shouldn't happen but it does. $package_version[1] = rtrim($package_version[1], "."); // Get rid of downstream versioning that comes from dpkg. This should definitely be done on the agent side // because I am 99% sure this is a dpkg thing only. And I'm sure some ying yangs legit put dashes in version // numbers. $last_dash = strrpos($package_version[1], "-"); if ($last_dash) { $package_version[1] = substr($package_version[1], 0, $last_dash); } $package_record = Package::firstOrNew(array('name' => $package_version[0], 'node_id' => $node->id)); $package_record->version = $package_version[1]; try { $package_record->save(); } catch (Exception $e) { $output->writeln("couldn't save record" . print_r($e->getMessage())); } $packages_index[$package_record->name] = $package_record; // Set up query cache. Only one query per agent report. That is crucial. Multiple queries would kill everything. array_push($query_version_vendor_query_pairs, array('$and' => array(array('product' => $package_record->name, 'version' => $package_record->version)))); } // Do one giant query. Not one per record. $mongo_client = new MongoClient('mongodb://*****:*****@capital.3.mongolayer.com:10201,capital.2.mongolayer.com:10201/vulnerabilities?replicaSet=set-5558d1202c6859fcde00176a'); $mongo_database = $mongo_client->selectDB('vulnerabilities'); $mongo_collection = new MongoCollection($mongo_database, 'processed'); $mongo_query = $mongo_collection->find(array('$or' => $query_version_vendor_query_pairs))->timeout(9999999); // This is where we actually do something. // for some reason if i do a sort the query is so slow it times out //$mongo_query->sort(array('last_updated' => 1)); // This won't work right if there are multiple vulnerabilties that match the prod and version. $might_alert_for = array(); foreach ($mongo_query as $document) { $packages_index[$document['product']]->vulnerability_severity = $document['risk_score']; if ($document['risk_score'] > 0) { if ($document['risk_score'] > 1) { $node->vulnerable = true; } else { // See if any alerts need to go out. Severe only for now. /*$alerts = Alert::where("owner_user_id", "=", $node->owner_id)->where("value", "=", 1)->get(); foreach($alerts as $alert) { if(!isset($might_alert_for[$alert->user_id])) { $might_alert_for[$alert->user_id] = array(); } array_push($might_alert_for, $document); }*/ if ($document['risk_score'] > 5) { $node->severe_vulnerable = true; } } } try { $packages_index[$document['product']]->save(); } catch (Exception $e) { } } $node->save(); //$output->writeln(print_r($might_alert_for)); // Check to see if target user has been alerted about these particular issues before. /*foreach($might_alert_for as $user_id, $list) { foreach($list as $k, $list_item) { $query = DB::table('sent_alerts')->where('node_id', '=', $node->id); $query->where('package', '=', $list_item['product']); $query->where('version', '=', $list_item['version']); $count_result = $query->count(); if($count_result > 0) { // If we've alerted before, remove this item from the list. unset($might_alert_for[$user_id][$k]); } } } foreach($might_alert_for as $user_id, $list) { foreach($list as $k, $list_item) { Mail::send('emails.alerts.vulnerable', $data, function($message) use ($list_item) { $message->from("*****@*****.**", "NoSprawl Vulnerability Alerting"); $message->to(User::find($list_item['user_id'])->email, User::find($list_item['user_id'])->name)->subject('NoSprawl New Vulnerability Discovered'); }); } }*/ #$output->writeln("Done"); $job->delete(); } else { $output->writeln("Got an agent report we couldn't match."); $job->delete(); } } catch (Exception $e) { $output->writeln("error" . $e->getMessage()); } }
/** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function end(Request $request, $id) { $output = new \Symfony\Component\Console\Output\ConsoleOutput(2); $output->writeln("end"); $rules = array('id_barang' => 'required', 'waktu_selesai' => 'required'); $validator = Validator::make(Input::all(), $rules); $output->writeln(Input::get('waktu_mulai')); // process the store if ($validator->fails()) { return $validator->messages()->toJson(); } else { $perbaikan = Perbaikan::find($id); if (!$perbaikan) { return "Not Found"; } if (strtotime($perbaikan->waktu_selesai) != null) { return "Perbaikan sudah diakhiri"; } $waktu_mulai = strtotime($perbaikan->waktu_mulai); if (!checkDateTime(Input::get('waktu_selesai'))) { return "Waktu selesai tidak valid"; } if ($waktu_mulai >= strtotime(Input::get('waktu_selesai'))) { return "Waktu mulai > waktu selesai"; } // store $peralatan = Peralatan::find($id); if (!$peralatan) { return "ID peralatan tidak ditemukan"; } $id_barang = $perbaikan->id_barang; $perbaikan->waktu_selesai = Input::get('waktu_selesai'); //ubah status peralatan $peralatan = Peralatan::find($id_barang); if (!$peralatan) { return "ID peralatan tidak ditemukan"; } if (strcmp($peralatan->status, "Perbaikan") == 0) { $peralatan->status = "Baik"; } $peralatan->save(); $perbaikan->save(); return 1; } }
<?php require_once __DIR__ . '/../vendor/autoload.php'; $out = new \Symfony\Component\Console\Output\ConsoleOutput(); $skips = ['Billing\\Entities\\*', 'SchedulerApi\\Console\\Command\\HelloWorldCommand']; if ($argc < 3) { help(); exit(1); } $cloverFile = $argv[1]; $minCoveragePercentage = $argv[2]; if (!is_readable($cloverFile)) { $out->writeln(sprintf('<error>"%s" is not readable</error>', $cloverFile)); exit(1); } if (!is_numeric($minCoveragePercentage) || ($minCoveragePercentage < 0 || $minCoveragePercentage > 100)) { $out->writeln('<error>Provided min coverage is not a valid int</error>'); exit(1); } libxml_use_internal_errors(true); libxml_clear_errors(); $xml = simplexml_load_file($cloverFile); if (!empty(libxml_get_last_error())) { $out->writeln(sprintf('<error>XML Errors found while parsing: %s</error>', implode(',', libxml_get_errors()))); exit(1); } $files = $xml->xpath('//file[class]'); $failedCoverageChecks = []; foreach ($files as $file) { $fileName = (string) $file['name']; $class = (string) $file->class['namespace'] . '\\' . (string) $file->class['name'];