/** * Requests API data and returns aliases * * @return string */ private function getAliases() { $request = new Request(); $user = new User(); $path = 'drush_aliases'; $method = 'GET'; $response = $request->request('users', Session::getValue('user_id'), $path, $method); eval(str_replace('<?php', '', $response['data']->drush_aliases)); $formatted_aliases = substr($response['data']->drush_aliases, 0, -1); $sites_object = new Sites(); $sites = $sites_object->all(); foreach ($sites as $site) { $environments = $site->environments->all(); foreach ($environments as $environment) { $key = $site->get('name') . '.' . $environment->get('id'); if (isset($aliases[$key])) { break; } try { $formatted_aliases .= PHP_EOL . " \$aliases['{$key}'] = "; $formatted_aliases .= $this->constructAlias($environment); } catch (TerminusException $e) { continue; } } } $formatted_aliases .= PHP_EOL; return $formatted_aliases; }
/** * Object constructor * * @param array $options Options to set as $this->key */ public function __construct($options = array()) { parent::__construct($options); if (!isset($this->user)) { $this->user = Session::getUser(); } }
/** * Determines if user is logged in * * @return [boolean] True if user is logged in */ public static function loggedIn() { if (Session::instance()->getValue('session', false) === false) { throw new TerminusException('Please login first with `terminus auth login`'); } return true; }
/** * Print and save drush aliases * * ## OPTIONS * * [--print] * : print aliases to screen * * [--location=<location>] * : Specify the the full path, including the filename, to the alias file * you wish to create. Without this option a default of * '~/.drush/pantheon.aliases.drushrc.php' will be used. */ public function aliases($args, $assoc_args) { $user = Session::getUser(); $print = $this->input()->optional(array('key' => 'print', 'choices' => $assoc_args, 'default' => false)); $location = $this->input()->optional(array('key' => 'location', 'choices' => $assoc_args, 'default' => getenv('HOME') . '/.drush/pantheon.aliases.drushrc.php')); if (is_dir($location)) { $message = 'Please provide a full path with filename,'; $message .= ' e.g. {location}/pantheon.aliases.drushrc.php'; $this->failure($message, compact('location')); } $file_exists = file_exists($location); // Create the directory if it doesn't yet exist $dirname = dirname($location); if (!is_dir($dirname)) { mkdir($dirname, 0700, true); } $content = $user->getAliases(); $h = fopen($location, 'w+'); fwrite($h, $content); fclose($h); chmod($location, 0700); $message = 'Pantheon aliases created'; if ($file_exists) { $message = 'Pantheon aliases updated'; } if (strpos($content, 'array') === false) { $message .= ', although you have no sites'; } $this->log()->info($message); if ($print) { $aliases = str_replace(array('<?php', '?>'), '', $content); $this->output()->outputDump($aliases); } }
/** * Delete a machine token from your account * * ## OPTIONS * [--machine-token-id=<id>] * : UUID or name of the site you want to delete * * [--force] * : to skip the confirmations */ public function delete($args, $assoc_args) { $user = Session::getUser(); $id = $assoc_args['machine-token-id']; if (empty($id)) { $this->failure('You must specify a machine token id to delete.'); } // Find the token $machine_token = $user->machine_tokens->get($assoc_args['machine-token-id']); if (empty($machine_token)) { $this->failure('There are no machine tokens with the id {id}.', array('id' => $id)); } $name = $machine_token->get('device_name'); if (!isset($assoc_args['force']) && !Terminus::getConfig('yes')) { //If the force option isn't used, we'll ask you some annoying questions Input::confirm(array('message' => 'Are you sure you want to delete %s?', 'context' => $name)); } $this->log()->info('Deleting {name} ...', array('name' => $name)); $response = $machine_token->delete(); if ($response['status_code'] == 200) { $this->log()->info('Deleted {name}!', array('name' => $name)); } else { $this->failure('There was an problem deleting the machine token.'); } }
/** * Find out what user you are logged in as. */ public function whoami() { if (Session::getValue('user_uuid')) { $this->output()->outputValue(Session::getValue('user_uuid'), 'You are authenticated as'); } else { $this->failure('You are not logged in.'); } }
/** * Object constructor * * @param [stdClass] $attributes Attributes of this model * @param [array] $options Options to set as $this->key * @return [User] $this */ public function __construct($attributes, $options = array()) { if (!isset($options['id'])) { $options['id'] = Session::getValue('user_uuid'); } parent::__construct($attributes, $options); $this->workflows = new Workflows(array('owner' => $this)); $this->instruments = new Instruments(array('user' => $this)); $this->setProfile(); }
/** * Instantiate a console within Terminus * * ## OPTIONS * * [--site=<site>] * : name of site to load * * @subcommand console */ public function console($args, $assoc_args) { $user = Session::getUser(); if (isset($assoc_args['site'])) { $sitename = $assoc_args['site']; $site_id = $this->sitesCache->findId($sitename); $site = new Site($site_id); } eval(\Psy\sh()); }
/** * Object constructor * * @param object $attributes Attributes of this model * @param array $options Options to set as $this->key */ public function __construct($attributes = null, array $options = array()) { parent::__construct($attributes, $options); if (!isset($this->user)) { $this->user = Session::getUser(); } $this->site_memberships = new OrganizationSiteMemberships(array('organization' => $this, 'owner' => $this, 'owner_type' => 'organization')); $this->user_memberships = new OrganizationUserMemberships(array('organization' => $this, 'owner' => $this, 'owner_type' => 'organization')); $this->workflows = new Workflows(array('owner' => $this, 'owner_type' => 'organization')); }
/** * Show a list of your instruments on Pantheon * * @subcommand list */ public function all($args, $assoc_args) { $user = Session::getUser(); $instruments = $user->instruments->all(); $data = array(); foreach ($instruments as $id => $instrument) { $data[] = array('label' => $instrument->get('label'), 'id' => $instrument->get('id')); } $this->output()->outputRecordList($data); }
/** * Say hello */ public function hello($args, $assoc_args) { if (Session::getValue('user_uuid')) { $user = Session::getUser(); $user->fetch(); $data = $user->serialize(); $this->log()->info("Hello, {name}!", array('name' => $data['firstname'])); } else { $this->log()->info("Hello, Anonymous!"); } }
public function __construct($id = null) { if (null === $id) { $this->id = Session::getValue('user_uuid'); } else { $this->id = $id; } $this->getProfile(); self::$instance = $this; return $this; }
public function fetch_user_organizations() { $response = Terminus_Command::paged_request('users/' . Session::getValue('user_uuid') . '/memberships/organizations'); $data = array(); foreach ($response['data'] as $membership) { if ($membership->role != 'unprivileged') { $data[$membership->id] = $membership->organization->profile->name; } } return $data; }
/** * Show a list of your organizations on Pantheon * * @subcommand list */ public function all($args, $assoc_args) { $user = Session::getUser(); $data = array(); $organizations = $user->getOrganizations(); foreach ($organizations as $id => $org) { $org_data = $org->get('organization'); $data[] = array('name' => $org_data->profile->name, 'id' => $org->get('id')); } $this->output()->outputRecordList($data); }
public function __construct($id = null) { if (null === $id) { $this->id = Session::getValue('user_uuid'); } else { $this->id = $id; } $this->workflows = new Workflows(array('owner' => $this, 'owner_type' => 'user')); $this->getProfile(); self::$instance = $this; return $this; }
/** * Instantiates object, sets cache and session */ public function __construct() { //Load commonly used data from cache $this->cache = Terminus::getCache(); $this->logger = Terminus::getLogger(); $this->outputter = Terminus::getOutputter(); $this->session = Session::instance(); $this->request = new Request(); if (!Terminus::isTest()) { Utils\checkForUpdate(); } }
/** * Instantiates object, sets cache and session * * @param array $options Elements as follow: * FileCache cache * Logger Logger * Outputter Outputter * Session Session * @return TerminusCommand */ public function __construct(array $options = []) { $this->cache = new FileCache(); $this->runner = $options['runner']; $this->session = Session::instance(); $this->logger = $this->runner->getLogger(); $this->outputter = $this->runner->getOutputter(); $this->loadHelpers(); if (!Utils\isTest()) { Utils\checkForUpdate($this->log()); } }
/** * Sets up and fills a cookie jar * * @param [array] $params Request data to fill jar with * @return [GuzzleHttp\Cookie\CookieJar] $jar */ static function fillCookieJar($params) { $jar = new CookieJar(); $cookies = array(); if ($session = Session::instance()->get('session', false)) { $cookies['X-Pantheon-Session'] = $session; } if (isset($params['cookies'])) { $cookies = array_merge($cookies, $params['cookies']); } $jar->fromArray($cookies, ''); return $jar; }
/** * Object constructor * * @param object $attributes Attributes of this model * @param array $options Options to set as $this->key */ public function __construct($attributes = null, array $options = array()) { if (!isset($options['id'])) { $options['id'] = Session::getValue('user_uuid'); } parent::__construct($attributes, $options); if (isset($attributes->profile)) { $this->profile = $attributes->profile; } $this->workflows = new Workflows(array('owner' => $this)); $this->instruments = new Instruments(array('user' => $this)); $this->organizations = new UserOrganizationMemberships(array('user' => $this)); }
private function hydrate() { $request = Terminus_Command::request('users', Session::getValue('user_uuid'), 'sites', 'GET', array('hydrated' => true)); $sites = $request['data']; foreach ($sites as $site_id => $site_data) { // we need to skip sites that are in the build process still if (!isset($site_data->information)) { continue; } $site_data->id = $site_id; $this->sites[$site_data->information->name] = $site_data; } return $this; }
/** * Make a request to the Dashbord's internal API. * * @param $realm * Permissions realm for data request: currently "user" or "site" but in the * future this could also be "organization" or another high-level business * object (e.g. "product" for managing your app). Can also be "public" to * simply pull read-only data that is not privileged. * * @param $uuid * The UUID of the item in the realm you want to access. * * @param $method * HTTP method (verb) to use. * * @param $data * A native PHP data structure (int, string, arary or simple object) to be * sent along with the request. Will be encoded as JSON for you. */ public static function request($realm, $uuid, $path = FALSE, $method = 'GET', $options = NULL) { if (!in_array($realm, array('login', 'user', 'public')) and !Terminus::is_test()) { Auth::loggedIn(); } try { $cache = Terminus::get_cache(); // combine session realm uuid and path to get a unique key // @todo need cache "groups" $cachekey = md5(Session::getValue('user_uuid') . $uuid . $realm . $path); $data = $cache->get_data($cachekey); // check the request cache if ("GET" == $method and !Terminus::get_config('nocache') and !getenv('CLI_TEST_MODE') and !empty($data)) { if (Terminus::get_config('debug')) { Logger::debug('CacheKey: ' . $cachekey); } return (array) $data; } // for some methods we'll assume the cache should be invalidated if (in_array($method, array("POST", "PUT", "DELETE"))) { $cache->flush(null, 'session'); } if (!in_array($realm, array('login', 'user'))) { $options['cookies'] = array('X-Pantheon-Session' => Session::getValue('session')); $options['verify'] = false; } $url = Endpoint::get(array('realm' => $realm, 'uuid' => $uuid, 'path' => $path)); if (Terminus::get_config('debug')) { Logger::debug('Request URL: ' . $url); } $resp = Request::send($url, $method, $options); $json = $resp->getBody(TRUE); $data = array('info' => $resp->getInfo(), 'headers' => $resp->getRawHeaders(), 'json' => $json, 'data' => json_decode($json), 'status_code' => $resp->getStatusCode()); $cache->put_data($cachekey, $data); return $data; } catch (Guzzle\Http\Exception\BadResponseException $e) { $response = $e->getResponse(); \Terminus::error("%s", $response->getBody(TRUE)); } catch (Guzzle\Http\Exception\HttpException $e) { $request = $e->getRequest(); //die(Terminus_Command::stripSensitiveData()); $sanitized_request = Terminus_Command::stripSensitiveData((string) $request, Terminus_Command::$_blacklist); \Terminus::error("Request %s had failed: %s", array($sanitized_request, $e->getMessage())); } catch (Exception $e) { \Terminus::error("Unrecognised request failure: %s", $e->getMessage()); } }
/** * Adds site with given site ID to cache * * @param [string] $site_id UUID of site to add to cache * @return [void] */ public function addSiteToCache($site_id) { if (count($this->models) == 0) { $this->rebuildCache(); } else { $site = new Site($this->objectify(array('id' => $site_id)), array('collection' => $this)); $site->fetch(); $cache_membership = $site->info(); if ($org_id) { $org = new Organization(null, array('id' => $org_id)); $cache_membership['membership'] = array('id' => $org_id, 'name' => $org->profile->name, 'type' => 'organization'); } else { $user_id = Session::getValue('user_uuid'); $cache_membership['membership'] = array('id' => $user_id, 'name' => 'Team', 'type' => 'team'); } $this->sites_cache->add($cache_membership); } }
/** * Delete a machine token from your account * * ## OPTIONS * [--machine-token-id=<id>] * : UUID or name of the site you want to delete * * [--force] * : to skip the confirmations */ public function delete($args, $assoc_args) { $user = Session::getUser(); $id = $assoc_args['machine-token-id']; if (empty($id)) { $this->failure('You must specify a machine token id to delete.'); } // Find the token $machine_token = $user->machine_tokens->get($assoc_args['machine-token-id']); if (empty($machine_token)) { $this->failure('There are no machine tokens with the id {id}.', array('id' => $id)); } $name = $machine_token->get('device_name'); $this->input()->confirm(['message' => 'Are you sure you want to delete %s?', 'context' => $name, 'args' => $assoc_args]); $this->log()->info('Deleting {name} ...', array('name' => $name)); $response = $machine_token->delete(); if ($response['status_code'] == 200) { $this->log()->info('Deleted {name}!', array('name' => $name)); } else { $this->failure('There was an problem deleting the machine token.'); } }
/** * Simplified request method for Pantheon API * * @param [string] $path API path (URL) * @param [array] $options Options for the request * [string] method GET is default * [mixed] data Native PHP data structure (e.g. int, string array, or * simple object) to be sent along with the request. Will be encoded as * JSON for you. * @return [array] $data */ public static function simple_request($path, $options = array()) { $req_options = array(); $method = 'get'; if (isset($options['method'])) { $method = $options['method']; } if (isset($options['data'])) { $req_options['body'] = json_encode($options['data']); $req_options['headers'] = array('Content-type' => 'application/json'); } $url = 'https://' . TERMINUS_HOST . '/api/' . $path; if (Session::getValue('session')) { $req_options['cookies'] = array('X-Pantheon-Session' => Session::getValue('session')); $req_options['verify'] = false; } try { $resp = Request::send($url, $method, $req_options); } catch (Guzzle\Http\Exception\BadResponseException $e) { \Terminus::error('Request Failure: %s', $e->getMessage()); return; } $json = $resp->getBody(true); $data = array('info' => $resp->getInfo(), 'headers' => $resp->getRawHeaders(), 'json' => $json, 'data' => json_decode($json), 'status_code' => $resp->getStatusCode()); return $data; }
public static function getData() { $session = Session::instance(); return $session->data; }
/** * Saves the session data to a cookie * * @param \stdClass $data Session data to save * @return bool Always true */ private function setInstanceData(\stdClass $data) { if (!isset($data->machine_token)) { $machine_token = (array) Session::instance()->get('machine_token'); } else { $machine_token = $data->machine_token; } $session = array('user_uuid' => $data->user_id, 'session' => $data->session, 'session_expire_time' => $data->expires_at); if ($machine_token && is_string($machine_token)) { $session['machine_token'] = $machine_token; } Session::instance()->setData($session); return true; }
/** * Checks to ensure user can access the given organization * * @param string $org_id Organization name or UUID * @return bool True if this organization is accessible */ private function isOrgAccessible($org_id) { $user = Session::getUser(); $org = $user->organizations->get($org_id); $is_ok = is_object($org); return $is_ok; }
/** * Fetches organizational memberships for user * * @return [array] $data Properties below: * [string] id UUID of membership join * [string] name Name of organization * [string] type Always "organization" */ private function fetchUserOrganizations() { $response = $this->request->pagedRequest('users/' . Session::getValue('user_uuid') . '/memberships/organizations'); $data = array(); foreach ($response['data'] as $membership) { if ($membership->role == 'unprivileged') { // Users with unprivileged role in organizations can't see organization // sites, but must be added to the team continue; } $data[] = array('id' => $membership->id, 'name' => $membership->organization->profile->name, 'type' => 'organization'); } return $data; }
/** * Returns an array listing organizaitions applicable to user * * @param array $arg_options Elements as follow: * bool allow_none True to allow the "none" option * @return array A list of organizations */ private function orgList(array $arg_options = []) { $default_options = ['allow_none' => true]; $options = array_merge($default_options, $arg_options); $org_list = []; if ($options['allow_none']) { $org_list = ['-' => 'None']; } $user = Session::getUser(); $organizations = $user->organizations->all(); foreach ($organizations as $id => $org) { $org_data = $org->get('organization'); $org_list[$org->get('id')] = $org_data->profile->name; } return $org_list; }
public function teamAddMember($email) { $method = 'POST'; $path = sprintf('team/%s', urlencode($email)); $data = array('invited_by' => Session::getValue('user_uuid')); $options = array('body' => json_encode($data), 'headers' => array('Content-type' => 'application/json')); $response = \Terminus_Command::request('sites', $this->getId(), $path, $method, $options); return $response['data']; }