public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $ids = $args->getArg('id');
     if (!$ids) {
         throw new PhutilArgumentUsageException(pht("Use the '%s' flag to specify one or more SMS messages to show.", '--id'));
     }
     $messages = id(new PhabricatorSMS())->loadAllWhere('id IN (%Ld)', $ids);
     if ($ids) {
         $ids = array_fuse($ids);
         $missing = array_diff_key($ids, $messages);
         if ($missing) {
             throw new PhutilArgumentUsageException(pht('Some specified SMS messages do not exist: %s', implode(', ', array_keys($missing))));
         }
     }
     $last_key = last_key($messages);
     foreach ($messages as $message_key => $message) {
         $info = array();
         $info[] = pht('PROPERTIES');
         $info[] = pht('ID: %d', $message->getID());
         $info[] = pht('Status: %s', $message->getSendStatus());
         $info[] = pht('To: %s', $message->getToNumber());
         $info[] = pht('From: %s', $message->getFromNumber());
         $info[] = null;
         $info[] = pht('BODY');
         $info[] = $message->getBody();
         $info[] = null;
         $console->writeOut('%s', implode("\n", $info));
         if ($message_key != $last_key) {
             $console->writeOut("\n%s\n\n", str_repeat('-', 80));
         }
     }
 }
 protected function loadTasks(PhutilArgumentParser $args)
 {
     $ids = $args->getArg('id');
     $class = $args->getArg('class');
     $min_failures = $args->getArg('min-failure-count');
     if (!$ids && !$class && !$min_failures) {
         throw new PhutilArgumentUsageException(pht('Use --id, --class, or --min-failure-count to select tasks.'));
     }
     $active_query = new PhabricatorWorkerActiveTaskQuery();
     $archive_query = new PhabricatorWorkerArchiveTaskQuery();
     if ($ids) {
         $active_query = $active_query->withIDs($ids);
         $archive_query = $archive_query->withIDs($ids);
     }
     if ($class) {
         $class_array = array($class);
         $active_query = $active_query->withClassNames($class_array);
         $archive_query = $archive_query->withClassNames($class_array);
     }
     if ($min_failures) {
         $active_query = $active_query->withFailureCountBetween($min_failures, null);
         $archive_query = $archive_query->withFailureCountBetween($min_failures, null);
     }
     $active_tasks = $active_query->execute();
     $archive_tasks = $archive_query->execute();
     $tasks = mpull($active_tasks, null, 'getID') + mpull($archive_tasks, null, 'getID');
     if ($ids) {
         foreach ($ids as $id) {
             if (empty($tasks[$id])) {
                 throw new PhutilArgumentUsageException(pht('No task exists with id "%s"!', $id));
             }
         }
     }
     if ($class && $min_failures) {
         if (!$tasks) {
             throw new PhutilArgumentUsageException(pht('No task exists with class "%s" and at least %d failures!', $class, $min_failures));
         }
     } else {
         if ($class) {
             if (!$tasks) {
                 throw new PhutilArgumentUsageException(pht('No task exists with class "%s"!', $class));
             }
         } else {
             if ($min_failures) {
                 if (!$tasks) {
                     throw new PhutilArgumentUsageException(pht('No tasks exist with at least %d failures!', $min_failures));
                 }
             }
         }
     }
     // When we lock tasks properly, this gets populated as a side effect. Just
     // fake it when doing manual CLI stuff. This makes sure CLI yields have
     // their expires times set properly.
     foreach ($tasks as $task) {
         if ($task instanceof PhabricatorWorkerActiveTask) {
             $task->setServerTime(PhabricatorTime::getNow());
         }
     }
     return $tasks;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $paths = $args->getArg('paths');
     if (!$paths) {
         $paths = array(getcwd());
     }
     $targets = array();
     foreach ($paths as $path) {
         $root = Filesystem::resolvePath($path);
         if (!Filesystem::pathExists($root) || !is_dir($root)) {
             throw new PhutilArgumentUsageException(pht('Path "%s" does not exist, or is not a directory.', $path));
         }
         $libraries = id(new FileFinder($path))->withPath('*/__phutil_library_init__.php')->find();
         if (!$libraries) {
             throw new PhutilArgumentUsageException(pht('Path "%s" contains no libphutil libraries.', $path));
         }
         foreach ($libraries as $library) {
             $targets[] = Filesystem::resolvePath(dirname($library)) . '/';
         }
     }
     $targets = array_unique($targets);
     foreach ($targets as $library) {
         echo tsprintf("**<bg:blue> %s </bg>** %s\n", pht('EXTRACT'), pht('Extracting "%s"...', Filesystem::readablePath($library)));
         $this->extractLibrary($library);
     }
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $is_dry = $args->getArg('dryrun');
     $is_force = $args->getArg('force');
     if (!$is_dry && !$is_force) {
         echo phutil_console_wrap("Are you completely sure you really want to permanently destroy all " . "storage for Phabricator data? This operation can not be undone and " . "your data will not be recoverable if you proceed.");
         if (!phutil_console_confirm('Permanently destroy all data?')) {
             echo "Cancelled.\n";
             exit(1);
         }
         if (!phutil_console_confirm('Really destroy all data forever?')) {
             echo "Cancelled.\n";
             exit(1);
         }
     }
     $api = $this->getAPI();
     $patches = $this->getPatches();
     $databases = $api->getDatabaseList($patches);
     $databases[] = $api->getDatabaseName('meta_data');
     foreach ($databases as $database) {
         if ($is_dry) {
             echo "DRYRUN: Would drop database '{$database}'.\n";
         } else {
             echo "Dropping database '{$database}'...\n";
             queryfx($api->getConn('meta_data', $select_database = false), 'DROP DATABASE IF EXISTS %T', $database);
         }
     }
     if (!$is_dry) {
         echo "Storage was destroyed.\n";
     }
     return 0;
 }
 public function didExecute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $patches = $this->getPatches();
     if (!$this->isDryRun() && !$this->isForce()) {
         $console->writeOut(phutil_console_wrap(pht('Before running storage upgrades, you should take down the ' . 'Phabricator web interface and stop any running Phabricator ' . 'daemons (you can disable this warning with %s).', '--force')));
         if (!phutil_console_confirm(pht('Are you ready to continue?'))) {
             $console->writeOut("%s\n", pht('Cancelled.'));
             return 1;
         }
     }
     $apply_only = $args->getArg('apply');
     if ($apply_only) {
         if (empty($patches[$apply_only])) {
             throw new PhutilArgumentUsageException(pht("%s argument '%s' is not a valid patch. " . "Use '%s' to show patch status.", '--apply', $apply_only, './bin/storage status'));
         }
     }
     $no_quickstart = $args->getArg('no-quickstart');
     $init_only = $args->getArg('init-only');
     $no_adjust = $args->getArg('no-adjust');
     $this->upgradeSchemata($apply_only, $no_quickstart, $init_only);
     if ($no_adjust || $init_only || $apply_only) {
         $console->writeOut("%s\n", pht('Declining to apply storage adjustments.'));
         return 0;
     } else {
         return $this->adjustSchemata(false);
     }
 }
 protected function loadITem(PhutilArgumentParser $argv, $key)
 {
     $item = $argv->getArg($key);
     if (!strlen($item)) {
         throw new PhutilArgumentUsageException(pht('Specify a item with %s.', '--' . $key));
     }
     $query = id(new NuanceItemQuery())->setViewer($this->getViewer())->setRaisePolicyExceptions(true);
     $type_unknown = PhabricatorPHIDConstants::PHID_TYPE_UNKNOWN;
     if (ctype_digit($item)) {
         $kind = 'id';
         $query->withIDs(array($item));
     } else {
         if (phid_get_type($item) !== $type_unknown) {
             $kind = 'phid';
             $query->withPHIDs($item);
         } else {
             throw new PhutilArgumentUsageException(pht('Specify the ID or PHID of an item to update. Parameter "%s" ' . 'is not an ID or PHID.', $item));
         }
     }
     $items = $query->execute();
     if (!$items) {
         switch ($kind) {
             case 'id':
                 $message = pht('No item exists with ID "%s".', $item);
                 break;
             case 'phid':
                 $message = pht('No item exists with PHID "%s".', $item);
                 break;
         }
         throw new PhutilArgumentUsageException($message);
     }
     return head($items);
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $reset = $args->getArg('reset');
     if ($reset) {
         foreach ($reset as $name) {
             $cursor = id(new PhabricatorFactCursor())->loadOneWhere('name = %s', $name);
             if ($cursor) {
                 $console->writeOut("%s\n", pht("Resetting cursor %s...", $name));
                 $cursor->delete();
             } else {
                 $console->writeErr("%s\n", pht("Cursor %s does not exist or is already reset.", $name));
             }
         }
         return 0;
     }
     $iterator_map = PhabricatorFactDaemon::getAllApplicationIterators();
     if (!$iterator_map) {
         $console->writeErr("%s\n", pht("No cursors."));
         return 0;
     }
     $cursors = id(new PhabricatorFactCursor())->loadAllWhere('name IN (%Ls)', array_keys($iterator_map));
     $cursors = mpull($cursors, 'getPosition', 'getName');
     foreach ($iterator_map as $iterator_name => $iterator) {
         $console->writeOut("%s (%s)\n", $iterator_name, idx($cursors, $iterator_name, 'start'));
     }
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $supported_types = id(new PhutilSymbolLoader())->setAncestorClass('PhabricatorTestDataGenerator')->loadObjects();
     echo "These are the types of data you can generate:\n";
     foreach (array_keys($supported_types) as $typetmp) {
         echo "\t" . $typetmp . "\n";
     }
     echo "\n";
     $prompt = 'Are you sure you want to generate lots of test data?';
     if (!phutil_console_confirm($prompt, $default_no = true)) {
         return;
     }
     $argv = $args->getArg('args');
     if (count($argv) == 0 || count($argv) == 1 && $argv[0] == 'all') {
         $this->infinitelyGenerate($supported_types);
     } else {
         $new_supported_types = array();
         for ($i = 0; $i < count($argv); $i++) {
             $arg = $argv[$i];
             if (array_key_exists($arg, $supported_types)) {
                 $new_supported_types[$arg] = $supported_types[$arg];
             } else {
                 echo "The type " . $arg . " is not supported by the lipsum generator.\n";
             }
         }
         $this->infinitelyGenerate($new_supported_types);
     }
     echo "None of the input types were supported.\n";
     echo "The supported types are:\n";
     echo implode("\n", array_keys($supported_types));
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $purge_all = $args->getArg('purge-all');
     $purge = array('remarkup' => $purge_all || $args->getArg('purge-remarkup'), 'changeset' => $purge_all || $args->getArg('purge-changeset'), 'general' => $purge_all || $args->getArg('purge-general'));
     if (!array_filter($purge)) {
         $list = array();
         foreach ($purge as $key => $ignored) {
             $list[] = "'--purge-" . $key . "'";
         }
         throw new PhutilArgumentUsageException("Specify which cache or caches to purge, or use '--purge-all'. " . "Available caches are: " . implode(', ', $list) . ". Use '--help' " . "for more information.");
     }
     if ($purge['remarkup']) {
         $console->writeOut('Purging remarkup cache...');
         $this->purgeRemarkupCache();
         $console->writeOut("done.\n");
     }
     if ($purge['changeset']) {
         $console->writeOut('Purging changeset cache...');
         $this->purgeChangesetCache();
         $console->writeOut("done.\n");
     }
     if ($purge['general']) {
         $console->writeOut('Purging general cache...');
         $this->purgeGeneralCache();
         $console->writeOut("done.\n");
     }
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $id = $args->getArg('id');
     if (!$id) {
         throw new PhutilArgumentUsageException(pht('Specify a public key to trust with --id.'));
     }
     $key = id(new PhabricatorAuthSSHKeyQuery())->setViewer($this->getViewer())->withIDs(array($id))->executeOne();
     if (!$key) {
         throw new PhutilArgumentUsageException(pht('No public key exists with ID "%s".', $id));
     }
     if ($key->getIsTrusted()) {
         throw new PhutilArgumentUsageException(pht('Public key with ID %s is already trusted.', $id));
     }
     if (!$key->getObject() instanceof AlmanacDevice) {
         throw new PhutilArgumentUsageException(pht('You can only trust keys associated with Almanac devices.'));
     }
     $handle = id(new PhabricatorHandleQuery())->setViewer($this->getViewer())->withPHIDs(array($key->getObject()->getPHID()))->executeOne();
     $console->writeOut("**<bg:red> %s </bg>**\n\n%s\n\n%s\n\n%s", pht('IMPORTANT!'), phutil_console_wrap(pht('Trusting a public key gives anyone holding the corresponding ' . 'private key complete, unrestricted access to all data in ' . 'Phabricator. The private key will be able to sign requests that ' . 'skip policy and security checks.')), phutil_console_wrap(pht('This is an advanced feature which should normally be used only ' . 'when building a Phabricator cluster. This feature is very ' . 'dangerous if misused.')), pht('This key is associated with device "%s".', $handle->getName()));
     $prompt = pht('Really trust this key?');
     if (!phutil_console_confirm($prompt)) {
         throw new PhutilArgumentUsageException(pht('User aborted workflow.'));
     }
     $key->setIsTrusted(1);
     $key->save();
     $console->writeOut("**<bg:green> %s </bg>** %s\n", pht('TRUSTED'), pht('Key %s has been marked as trusted.', $id));
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $ids = $args->getArg('ids');
     if (!$ids) {
         throw new PhutilArgumentUsageException('Specify one or more lease IDs to release.');
     }
     $viewer = $this->getViewer();
     $leases = id(new DrydockLeaseQuery())->setViewer($viewer)->withIDs($ids)->execute();
     foreach ($ids as $id) {
         $lease = idx($leases, $id);
         if (!$lease) {
             $console->writeErr("Lease %d does not exist!\n", $id);
         } else {
             if ($lease->getStatus() != DrydockLeaseStatus::STATUS_ACTIVE) {
                 $console->writeErr("Lease %d is not 'active'!\n", $id);
             } else {
                 $resource = $lease->getResource();
                 $blueprint = $resource->getBlueprint();
                 $blueprint->releaseLease($resource, $lease);
                 $console->writeErr("Released lease %d.\n", $id);
             }
         }
     }
 }
 public function execute(PhutilArgumentParser $args)
 {
     $ids = $args->getArg('id');
     if (!$ids) {
         throw new PhutilArgumentUsageException(pht('Specify one or more lease IDs to release with "%s".', '--id'));
     }
     $viewer = $this->getViewer();
     $drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
     $leases = id(new DrydockLeaseQuery())->setViewer($viewer)->withIDs($ids)->execute();
     PhabricatorWorker::setRunAllTasksInProcess(true);
     foreach ($ids as $id) {
         $lease = idx($leases, $id);
         if (!$lease) {
             echo tsprintf("%s\n", pht('Lease "%s" does not exist.', $id));
             continue;
         }
         if (!$lease->canRelease()) {
             echo tsprintf("%s\n", pht('Lease "%s" is not releasable.', $id));
             continue;
         }
         $command = DrydockCommand::initializeNewCommand($viewer)->setTargetPHID($lease->getPHID())->setAuthorPHID($drydock_phid)->setCommand(DrydockCommand::COMMAND_RELEASE)->save();
         $lease->scheduleUpdate();
         echo tsprintf("%s\n", pht('Scheduled release of lease "%s".', $id));
     }
 }
 public function execute(PhutilArgumentParser $args)
 {
     $can_recover = id(new PhabricatorPeopleQuery())->setViewer($this->getViewer())->withIsAdmin(true)->execute();
     if (!$can_recover) {
         throw new PhutilArgumentUsageException(pht('This Phabricator installation has no recoverable administrator ' . 'accounts. You can use `bin/accountadmin` to create a new ' . 'administrator account or make an existing user an administrator.'));
     }
     $can_recover = mpull($can_recover, 'getUsername');
     sort($can_recover);
     $can_recover = implode(', ', $can_recover);
     $usernames = $args->getArg('username');
     if (!$usernames) {
         throw new PhutilArgumentUsageException(pht('You must specify the username of the account to recover.'));
     } else {
         if (count($usernames) > 1) {
             throw new PhutilArgumentUsageException(pht('You can only recover the username for one account.'));
         }
     }
     $username = head($usernames);
     $user = id(new PhabricatorPeopleQuery())->setViewer($this->getViewer())->withUsernames(array($username))->executeOne();
     if (!$user) {
         throw new PhutilArgumentUsageException(pht('No such user "%s". Recoverable administrator accounts are: %s.', $username, $can_recover));
     }
     if (!$user->getIsAdmin()) {
         throw new PhutilArgumentUsageException(pht('You can only recover administrator accounts, but %s is not an ' . 'administrator. Recoverable administrator accounts are: %s.', $username, $can_recover));
     }
     $engine = new PhabricatorAuthSessionEngine();
     $onetime_uri = $engine->getOneTimeLoginURI($user, null, PhabricatorAuthSessionEngine::ONETIME_RECOVER);
     $console = PhutilConsole::getConsole();
     $console->writeOut(pht('Use this link to recover access to the "%s" account from the web ' . 'interface:', $username));
     $console->writeOut("\n\n");
     $console->writeOut('    %s', $onetime_uri);
     $console->writeOut("\n\n");
     $console->writeOut(pht('After logging in, you can use the "Auth" application to add or ' . 'restore authentication providers and allow normal logins to ' . 'succeed.') . "\n");
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $pids = $args->getArg('pids');
     $graceful = $args->getArg('graceful');
     $force = $args->getArg('force');
     return $this->executeStopCommand($pids, $graceful, $force);
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $public_keyfile = $args->getArg('public');
     if (!strlen($public_keyfile)) {
         throw new PhutilArgumentUsageException(pht('You must specify the path to a public keyfile with %s.', '--public'));
     }
     if (!Filesystem::pathExists($public_keyfile)) {
         throw new PhutilArgumentUsageException(pht('Specified public keyfile "%s" does not exist!', $public_keyfile));
     }
     $public_key = Filesystem::readFile($public_keyfile);
     $pkcs8_keyfile = $args->getArg('pkcs8');
     if (!strlen($pkcs8_keyfile)) {
         throw new PhutilArgumentUsageException(pht('You must specify the path to a pkcs8 keyfile with %s.', '--pkc8s'));
     }
     if (!Filesystem::pathExists($pkcs8_keyfile)) {
         throw new PhutilArgumentUsageException(pht('Specified pkcs8 keyfile "%s" does not exist!', $pkcs8_keyfile));
     }
     $pkcs8_key = Filesystem::readFile($pkcs8_keyfile);
     $warning = pht('Adding a PKCS8 keyfile to the cache can be very dangerous. If the ' . 'PKCS8 file really encodes a different public key than the one ' . 'specified, an attacker could use it to gain unauthorized access.' . "\n\n" . 'Generally, you should use this option only in a development ' . 'environment where ssh-keygen is broken and it is inconvenient to ' . 'fix it, and only if you are certain you understand the risks. You ' . 'should never cache a PKCS8 file you did not generate yourself.');
     $console->writeOut("%s\n", phutil_console_wrap($warning));
     $prompt = pht('Really trust this PKCS8 keyfile?');
     if (!phutil_console_confirm($prompt)) {
         throw new PhutilArgumentUsageException(pht('Aborted workflow.'));
     }
     $key = PhabricatorAuthSSHPublicKey::newFromRawKey($public_key);
     $key->forcePopulatePKCS8Cache($pkcs8_key);
     $console->writeOut("%s\n", pht('Cached PKCS8 key for public key.'));
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $resource_type = $args->getArg('type');
     if (!$resource_type) {
         throw new PhutilArgumentUsageException(pht('Specify a resource type with `%s`.', '--type'));
     }
     $until = $args->getArg('until');
     if (strlen($until)) {
         $until = strtotime($until);
         if ($until <= 0) {
             throw new PhutilArgumentUsageException(pht('Unable to parse argument to "%s".', '--until'));
         }
     }
     $attributes = $args->getArg('attributes');
     if ($attributes) {
         $options = new PhutilSimpleOptions();
         $options->setCaseSensitive(true);
         $attributes = $options->parse($attributes);
     }
     $lease = id(new DrydockLease())->setResourceType($resource_type);
     if ($attributes) {
         $lease->setAttributes($attributes);
     }
     if ($until) {
         $lease->setUntil($until);
     }
     $lease->queueForActivation();
     echo tsprintf("%s\n", pht('Waiting for daemons to activate lease...'));
     $lease->waitUntilActive();
     echo tsprintf("%s\n", pht('Activated lease "%s".', $lease->getID()));
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $daemon = new PhabricatorFactDaemon(array());
     $daemon->setVerbose(true);
     $daemon->setEngines(PhabricatorFactEngine::loadAllEngines());
     $iterators = PhabricatorFactDaemon::getAllApplicationIterators();
     $selected = $args->getArg('iterator');
     if ($selected) {
         $use = array();
         foreach ($selected as $iterator_name) {
             if (isset($iterators[$iterator_name])) {
                 $use[$iterator_name] = $iterators[$iterator_name];
             } else {
                 $console->writeErr("%s\n", pht("Iterator '%s' does not exist.", $iterator_name));
             }
         }
         $iterators = $use;
     }
     foreach ($iterators as $iterator_name => $iterator) {
         if ($args->getArg('all')) {
             $daemon->processIterator($iterator);
         } else {
             $daemon->processIteratorWithCursor($iterator_name, $iterator);
         }
     }
     if (!$args->getArg('skip-aggregates')) {
         $daemon->processAggregates();
     }
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $supported_types = id(new PhutilClassMapQuery())->setAncestorClass('PhabricatorTestDataGenerator')->execute();
     $console->writeOut("%s:\n\t%s\n", pht('These are the types of data you can generate'), implode("\n\t", array_keys($supported_types)));
     $prompt = pht('Are you sure you want to generate lots of test data?');
     if (!phutil_console_confirm($prompt, true)) {
         return;
     }
     $argv = $args->getArg('args');
     if (count($argv) == 0 || count($argv) == 1 && $argv[0] == 'all') {
         $this->infinitelyGenerate($supported_types);
     } else {
         $new_supported_types = array();
         for ($i = 0; $i < count($argv); $i++) {
             $arg = $argv[$i];
             if (array_key_exists($arg, $supported_types)) {
                 $new_supported_types[$arg] = $supported_types[$arg];
             } else {
                 $console->writeErr("%s\n", pht('The type %s is not supported by the lipsum generator.', $arg));
             }
         }
         $this->infinitelyGenerate($new_supported_types);
     }
     $console->writeOut("%s\n%s:\n%s\n", pht('None of the input types were supported.'), pht('The supported types are'), implode("\n", array_keys($supported_types)));
 }
 public function execute(PhutilArgumentParser $args)
 {
     $emails = $args->getArg('email');
     if (!$emails) {
         throw new PhutilArgumentUsageException(pht('You must specify the email to verify.'));
     } else {
         if (count($emails) > 1) {
             throw new PhutilArgumentUsageException(pht('You can only verify one address at a time.'));
         }
     }
     $address = head($emails);
     $email = id(new PhabricatorUserEmail())->loadOneWhere('address = %s', $address);
     if (!$email) {
         throw new PhutilArgumentUsageException(pht('No email exists with address "%s"!', $address));
     }
     $viewer = $this->getViewer();
     $user = id(new PhabricatorPeopleQuery())->setViewer($viewer)->withPHIDs(array($email->getUserPHID()))->executeOne();
     if (!$user) {
         throw new Exception(pht('Email record has invalid user PHID!'));
     }
     $editor = id(new PhabricatorUserEditor())->setActor($viewer)->verifyEmail($user, $email);
     $console = PhutilConsole::getConsole();
     $console->writeOut("%s\n", pht('Done.'));
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $viewer = $this->getViewer();
     $names = $args->getArg('buildable');
     if (count($names) != 1) {
         throw new PhutilArgumentUsageException(pht('Specify exactly one buildable object, by object name.'));
     }
     $name = head($names);
     $buildable = id(new PhabricatorObjectQuery())->setViewer($viewer)->withNames($names)->executeOne();
     if (!$buildable) {
         throw new PhutilArgumentUsageException(pht('No such buildable "%s"!', $name));
     }
     if (!$buildable instanceof HarbormasterBuildableInterface) {
         throw new PhutilArgumentUsageException(pht('Object "%s" is not a buildable!', $name));
     }
     $plan_id = $args->getArg('plan');
     if (!$plan_id) {
         throw new PhutilArgumentUsageException(pht('Use --plan to specify a build plan to run.'));
     }
     $plan = id(new HarbormasterBuildPlanQuery())->setViewer($viewer)->withIDs(array($plan_id))->executeOne();
     if (!$plan) {
         throw new PhutilArgumentUsageException(pht('Build plan "%s" does not exist.', $plan_id));
     }
     $console = PhutilConsole::getConsole();
     $buildable = HarbormasterBuildable::initializeNewBuildable($viewer)->setIsManualBuildable(true)->setBuildablePHID($buildable->getHarbormasterBuildablePHID())->setContainerPHID($buildable->getHarbormasterContainerPHID())->save();
     $console->writeOut("%s\n", pht('Applying plan %s to new buildable %s...', $plan->getID(), 'B' . $buildable->getID()));
     $console->writeOut("\n    %s\n\n", PhabricatorEnv::getProductionURI('/B' . $buildable->getID()));
     PhabricatorWorker::setRunAllTasksInProcess(true);
     $buildable->applyPlan($plan);
     $console->writeOut("%s\n", pht('Done.'));
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $argv = $args->getArg('args');
     if (count($argv) == 0) {
         throw new PhutilArgumentUsageException(pht('Specify a configuration key to delete.'));
     }
     $key = $argv[0];
     if (count($argv) > 1) {
         throw new PhutilArgumentUsageException(pht('Too many arguments: expected one key.'));
     }
     $use_database = $args->getArg('database');
     if ($use_database) {
         $config = new PhabricatorConfigDatabaseSource('default');
         $config_type = 'database';
     } else {
         $config = new PhabricatorConfigLocalSource();
         $config_type = 'local';
     }
     $values = $config->getKeys(array($key));
     if (!$values) {
         throw new PhutilArgumentUsageException(pht("Configuration key '%s' is not set in %s configuration!", $key, $config_type));
     }
     if ($use_database) {
         $config_entry = PhabricatorConfigEntry::loadConfigEntry($key);
         $config_entry->setIsDeleted(1);
         $config_entry->save();
     } else {
         $config->deleteKeys(array($key));
     }
     $console->writeOut("%s\n", pht("Deleted '%s' from %s configuration.", $key, $config_type));
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $argv = $args->getArg('args');
     if (count($argv) == 0) {
         throw new PhutilArgumentUsageException('Specify a configuration key to get.');
     }
     $key = $argv[0];
     if (count($argv) > 1) {
         throw new PhutilArgumentUsageException('Too many arguments: expected one key.');
     }
     $options = PhabricatorApplicationConfigOptions::loadAllOptions();
     if (empty($options[$key])) {
         throw new PhutilArgumentUsageException("No such configuration key '{$key}'! Use `config list` to list all " . "keys.");
     }
     $config = new PhabricatorConfigLocalSource();
     $values = $config->getKeys(array($key));
     $result = array();
     foreach ($values as $key => $value) {
         $result[] = array('key' => $key, 'source' => 'local', 'value' => $value);
     }
     $result = array('config' => $result);
     $json = new PhutilJSON();
     $console->writeOut($json->encodeFormatted($result));
 }
 public function execute(PhutilArgumentParser $args)
 {
     $viewer = $this->getViewer();
     $argv = $args->getArg('argv');
     if (count($argv) !== 2) {
         throw new PhutilArgumentUsageException(pht('Specify a commit and a revision to attach it to.'));
     }
     $commit_name = head($argv);
     $revision_name = last($argv);
     $commit = id(new DiffusionCommitQuery())->setViewer($viewer)->withIdentifiers(array($commit_name))->executeOne();
     if (!$commit) {
         throw new PhutilArgumentUsageException(pht('Commit "%s" does not exist.', $commit_name));
     }
     $revision = id(new PhabricatorObjectQuery())->setViewer($viewer)->withNames(array($revision_name))->executeOne();
     if (!$revision) {
         throw new PhutilArgumentUsageException(pht('Revision "%s" does not exist.', $revision_name));
     }
     if (!$revision instanceof DifferentialRevision) {
         throw new PhutilArgumentUsageException(pht('Object "%s" must be a Differential revision.', $revision_name));
     }
     // Reload the revision to get the active diff.
     $revision = id(new DifferentialRevisionQuery())->setViewer($viewer)->withIDs(array($revision->getID()))->needActiveDiffs(true)->executeOne();
     $differential_phid = id(new PhabricatorDifferentialApplication())->getPHID();
     $extraction_engine = id(new DifferentialDiffExtractionEngine())->setViewer($viewer)->setAuthorPHID($differential_phid);
     $content_source = PhabricatorContentSource::newForSource(PhabricatorContentSource::SOURCE_CONSOLE, array());
     $extraction_engine->updateRevisionWithCommit($revision, $commit, array(), $content_source);
     echo tsprintf("%s\n", pht('Attached "%s" to "%s".', $commit->getMonogram(), $revision->getMonogram()));
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $resource_name = $args->getArg('name');
     if (!$resource_name) {
         throw new PhutilArgumentUsageException('Specify a resource name with `--name`.');
     }
     $blueprint_id = $args->getArg('blueprint');
     if (!$blueprint_id) {
         throw new PhutilArgumentUsageException('Specify a blueprint ID with `--blueprint`.');
     }
     $attributes = $args->getArg('attributes');
     if ($attributes) {
         $options = new PhutilSimpleOptions();
         $options->setCaseSensitive(true);
         $attributes = $options->parse($attributes);
     }
     $viewer = $this->getViewer();
     $blueprint = id(new DrydockBlueprintQuery())->setViewer($viewer)->withIDs(array($blueprint_id))->executeOne();
     if (!$blueprint) {
         throw new PhutilArgumentUsageException('Specified blueprint does not exist.');
     }
     $resource = id(new DrydockResource())->setBlueprintPHID($blueprint->getPHID())->setType($blueprint->getImplementation()->getType())->setName($resource_name)->setStatus(DrydockResourceStatus::STATUS_OPEN);
     if ($attributes) {
         $resource->setAttributes($attributes);
     }
     $resource->save();
     $console->writeOut("Created Resource %s\n", $resource->getID());
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $in = $args->getArg('in');
     if (!strlen($in)) {
         throw new PhutilArgumentUsageException(pht('Specify the dumpfile to read with --in.'));
     }
     $from = $args->getArg('from');
     if (!strlen($from)) {
         throw new PhutilArgumentUsageException(pht('Specify namespace to rename from with --from.'));
     }
     $to = $args->getArg('to');
     if (!strlen($to)) {
         throw new PhutilArgumentUsageException(pht('Specify namespace to rename to with --to.'));
     }
     $patterns = array('use' => '@^(USE `)([^_]+)(_.*)$@', 'create' => '@^(CREATE DATABASE /\\*.*?\\*/ `)([^_]+)(_.*)$@');
     $found = array_fill_keys(array_keys($patterns), 0);
     $matches = null;
     foreach (new LinesOfALargeFile($in) as $line) {
         foreach ($patterns as $key => $pattern) {
             if (preg_match($pattern, $line, $matches)) {
                 $namespace = $matches[2];
                 if ($namespace != $from) {
                     throw new Exception(pht('Expected namespace "%s", found "%s": %s.', $from, $namespace, $line));
                 }
                 $line = $matches[1] . $to . $matches[3];
                 $found[$key]++;
             }
         }
         echo $line . "\n";
     }
     // Give the user a chance to catch things if the results are crazy.
     $console->writeErr(pht('Adjusted **%s** create statements and **%s** use statements.', new PhutilNumber($found['create']), new PhutilNumber($found['use'])) . "\n");
     return 0;
 }
 protected function loadCommits(PhutilArgumentParser $args, $param)
 {
     $names = $args->getArg($param);
     if (!$names) {
         return null;
     }
     return $this->loadNamedCommits($names);
 }
 public function execute(PhutilArgumentParser $args)
 {
     $force = $args->getArg('force');
     $unsafe = $args->getArg('unsafe');
     $dry_run = $args->getArg('dryrun');
     $this->requireAllPatchesApplied();
     return $this->adjustSchemata($force, $unsafe, $dry_run);
 }
 public function execute(PhutilArgumentParser $args)
 {
     $err = $this->executeStopCommand(array(), array('graceful' => $args->getArg('graceful'), 'force' => $args->getArg('force'), 'gently' => $args->getArg('gently')));
     if ($err) {
         return $err;
     }
     return $this->executeStartCommand(array('reserve' => (double) $args->getArg('autoscale-reserve', 0.0)));
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $repos = id(new PhabricatorRepositoryQuery())->setViewer($this->getViewer())->execute();
     if (!$repos) {
         $console->writeErr("%s\n", pht('There are no repositories.'));
         return 0;
     }
     $from = $args->getArg('from');
     if (!strlen($from)) {
         throw new Exception(pht('You must specify a path prefix to move from with --from.'));
     }
     $to = $args->getArg('to');
     if (!strlen($to)) {
         throw new Exception(pht('You must specify a path prefix to move to with --to.'));
     }
     $rows = array();
     $any_changes = false;
     foreach ($repos as $repo) {
         $src = $repo->getLocalPath();
         $row = array('repository' => $repo, 'move' => false, 'monogram' => $repo->getMonogram(), 'src' => $src, 'dst' => '');
         if (strncmp($src, $from, strlen($from))) {
             $row['action'] = pht('Ignore');
         } else {
             $dst = $to . substr($src, strlen($from));
             $row['action'] = phutil_console_format('**%s**', pht('Move'));
             $row['dst'] = $dst;
             $row['move'] = true;
             $any_changes = true;
         }
         $rows[] = $row;
     }
     $table = id(new PhutilConsoleTable())->addColumn('action', array('title' => pht('Action')))->addColumn('monogram', array('title' => pht('Repository')))->addColumn('src', array('title' => pht('Src')))->addColumn('dst', array('title' => pht('dst')))->setBorders(true);
     foreach ($rows as $row) {
         $display = array_select_keys($row, array('action', 'monogram', 'src', 'dst'));
         $table->addRow($display);
     }
     $table->draw();
     if (!$any_changes) {
         $console->writeOut(pht('No matching repositories.') . "\n");
         return 0;
     }
     $prompt = pht('Apply these changes?');
     if (!phutil_console_confirm($prompt)) {
         throw new Exception(pht('Declining to apply changes.'));
     }
     foreach ($rows as $row) {
         if (empty($row['move'])) {
             continue;
         }
         $repo = $row['repository'];
         $details = $repo->getDetails();
         $details['local-path'] = $row['dst'];
         queryfx($repo->establishConnection('w'), 'UPDATE %T SET details = %s WHERE id = %d', $repo->getTableName(), phutil_json_encode($details), $repo->getID());
     }
     $console->writeOut(pht('Applied changes.') . "\n");
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $viewer = $this->getViewer();
     $days = (int) $args->getArg('days');
     if ($days < 1) {
         throw new PhutilArgumentUsageException(pht('Period specified with --days must be at least 1.'));
     }
     $duration = phutil_units("{$days} days in seconds");
     $since = PhabricatorTime::getNow() - $duration;
     $until = PhabricatorTime::getNow();
     $mails = id(new PhabricatorMetaMTAMailQuery())->setViewer($viewer)->withDateCreatedBetween($since, $until)->execute();
     $unfiltered = array();
     $delivered = array();
     foreach ($mails as $mail) {
         // Count messages we attempted to deliver. This includes messages which
         // were voided by preferences or other rules.
         $unfiltered_actors = mpull($mail->loadAllActors(), 'getPHID');
         foreach ($unfiltered_actors as $phid) {
             if (empty($unfiltered[$phid])) {
                 $unfiltered[$phid] = 0;
             }
             $unfiltered[$phid]++;
         }
         // Now, count mail we actually delivered.
         $result = $mail->getDeliveredActors();
         if ($result) {
             foreach ($result as $actor_phid => $actor_info) {
                 if (!$actor_info['deliverable']) {
                     continue;
                 }
                 if (empty($delivered[$actor_phid])) {
                     $delivered[$actor_phid] = 0;
                 }
                 $delivered[$actor_phid]++;
             }
         }
     }
     // Sort users by delivered mail, then unfiltered mail.
     arsort($delivered);
     arsort($unfiltered);
     $delivered = $delivered + array_fill_keys(array_keys($unfiltered), 0);
     $table = id(new PhutilConsoleTable())->setBorders(true)->addColumn('user', array('title' => pht('User')))->addColumn('unfiltered', array('title' => pht('Unfiltered')))->addColumn('delivered', array('title' => pht('Delivered')));
     $handles = $viewer->loadHandles(array_keys($unfiltered));
     $names = mpull(iterator_to_array($handles), 'getName', 'getPHID');
     foreach ($delivered as $phid => $delivered_count) {
         $unfiltered_count = idx($unfiltered, $phid, 0);
         $table->addRow(array('user' => idx($names, $phid), 'unfiltered' => $unfiltered_count, 'delivered' => $delivered_count));
     }
     $table->draw();
     echo "\n";
     echo pht('Mail sent in the last %s day(s).', new PhutilNumber($days)) . "\n";
     echo pht('"Unfiltered" is raw volume before rules applied.') . "\n";
     echo pht('"Delivered" shows email actually sent.') . "\n";
     echo "\n";
     return 0;
 }