private function loadUpstreams() { $key = join("-", array($this->type, $this->category, $this->framework)); $response = \TerminusCommand::request("products", "public", false, "GET"); $upstreams = array(); $keys_to_show = array('longname', 'framework', 'type', 'category'); // we'll use this to sort the list later $sort = array(); foreach ((array) $response['data'] as $id => $details) { if (!empty($this->type) and $details->attributes->type != $this->type) { continue; } if (!empty($this->category) and $details->attributes->category != $this->category) { continue; } if (!empty($this->framework) and $details->attributes->framework != $this->framework) { continue; } $sort[] = $details->attributes->shortname; $row = array(); $row['id'] = $id; foreach ($keys_to_show as $key) { $row[$key] = @$details->attributes->{$key}; } array_push($upstreams, $row); } array_multisort($sort, SORT_ASC, SORT_REGULAR, $upstreams); $this->upstreams = $upstreams; return $upstreams; }
/** * Requests API data and populates $this->aliases * * @return [void] */ private function setAliases() { $path = 'drush_aliases'; $method = 'GET'; $response = \TerminusCommand::request('users', $this->id, $path, $method); $this->aliases = $response['data']->drush_aliases; }
public function getSites() { $path = 'memberships/sites'; $method = 'GET'; $response = \TerminusCommand::request('organizations', $this->id, $path, $method); return $response['data']; }
/** * Make a request to the Pantheon API * * @param [string] $realm Permissions realm for data request (e.g. user, * site organization, etc. Can also be "public" to simply pull read-only * data that is not privileged. * @param [string] $uuid The UUID of the item in the realm to access * @param [string] $path API path (URL) * @param [string] $method HTTP method to use * @param [mixed] $options A native PHP data structure (e.g. int, string, * array, or stdClass) to be sent along with the request * @return [array] $data */ public static function request($realm, $uuid, $path = false, $method = 'GET', $options = null) { if (!in_array($realm, array('login', 'user', 'public'))) { Auth::loggedIn(); } try { $cache = Terminus::get_cache(); 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()); 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(); $sanitized_request = TerminusCommand::stripSensitiveData((string) $request, TerminusCommand::$blacklist); \Terminus::error('Request %s had failed: %s', array($sanitized_request, $e->getMessage())); } catch (Exception $e) { \Terminus::error('Unrecognised request failure: %s', $e->getMessage()); } }
public function sites($organization = null) { if ($organization) { $path = sprintf("organizations/%s/memberships/sites", $organization); } else { $path = "sites"; } $method = 'GET'; $response = \TerminusCommand::request('users', $this->id, $path, $method); return $response['data']; }
/** * Execute the login based on an existing session token * * @param [string] $token Session token to initiate login with * @return [boolean] True if login succeeded */ public function logInViaSessionToken($token) { $options = array('headers' => array('Content-type' => 'application/json'), 'cookies' => array('X-Pantheon-Session' => $token)); $this->logger->info('Validating session token'); $response = TerminusCommand::request('user', '', '', 'GET', $options); if (!$response || !isset($response['status_code']) || $response['status_code'] != '200') { throw new TerminusException('The session token {token} is not valid.', array('token' => $token), 1); } $this->logger->info('Logged in as {uuid}.', array('uuid' => $response['data']->id)); $session = array('user_uuid' => $response['data']->id, 'session' => $token, 'session_expire_time' => 0); Session::instance()->setData($session); return true; }
/** * Start a work flow * * @param [Workflow] $workflow String work flow "slot" * @return [array] $response['data'] */ public function workflow($workflow) { $path = sprintf("environments/%s/workflows", $this->get('id')); $data = array('type' => $workflow, 'environment' => $this->get('id')); $options = array('body' => json_encode($data), 'headers' => array('Content-type' => 'application/json')); $response = \TerminusCommand::request('sites', $this->site->get('id'), $path, 'POST', $options); return $response['data']; }
/** * Just the code branches * * @return [stdClass] $data['data'] */ public function tips() { $path = 'code-tips'; $data = \TerminusCommand::request('sites', $this->get('id'), $path, 'GET'); return $data['data']; }
/** * Instantiates object, ensures login * * @return [Instruments_Command] $this */ public function __construct() { Auth::ensureLogin(); parent::__construct(); }
public function __construct() { parent::__construct(); }
/** * Get, load, create, or list backup information * * ## OPTIONS * * <get|load|create|list> * : Function to run - get, load, create, or list * * [--site=<site>] * : Site to load * * [--env=<env>] * : Environment to load * * [--element=<code|files|db|all>] * : Element to download or create. *all* only used for 'create' * * [--to-directory=<directory>] * : Absolute path of directory to download the file * * [--latest] * : If set the latest backup will be selected automatically * * [--keep-for] * : Number of days to keep this backup * * @subcommand backups * */ public function backups($args, $assoc_args) { $action = array_shift($args); $site = $this->sites->get(Input::sitename($assoc_args)); $env = Input::env($assoc_args, 'env'); //Backward compatability supports "database" as a valid element value. if (isset($assoc_args['element']) && $assoc_args['element'] == 'database') { $assoc_args['element'] = 'db'; } switch ($action) { case 'get': if (isset($assoc_args['element'])) { $element = $assoc_args['element']; } else { $element = Terminus::menu(array('code', 'files', 'db'), null, 'Select backup element', true); } if (!in_array($element, array('code', 'files', 'db'))) { Terminus::error('Invalid backup element specified.'); } $latest = Input::optional('latest', $assoc_args, false); $backups = $site->environments->get($env)->backups($element); //Ensure that that backups being presented for retrieval have finished $backups = array_filter($backups, function ($backup) { return isset($backup->finish_time) && $backup->finish_time; }); if ($latest) { $backups = array(array_pop($backups)); } if (empty($backups)) { \Terminus::error('No backups available.'); } $menu = $folders = array(); foreach ($backups as $folder => $backup) { if (!isset($backup->filename)) { continue; } if (!isset($backup->folder)) { $backup->folder = $folder; } $buckets[] = $backup->folder; $menu[] = $backup->filename; } if (empty($menu)) { Terminus::error('No backups available. Create one with ' . '`terminus site backup create --site=%s --env=%s`', array($site->get('name'), $env)); } $index = 0; if (!$latest) { $index = Terminus::menu($menu, null, 'Select backup'); } $bucket = $buckets[$index]; $filename = $menu[$index]; $url = $site->environments->get($env)->backupUrl($bucket, $element); if (isset($assoc_args['to-directory'])) { Terminus::line('Downloading ... please wait ...'); $filename = \Terminus\Utils\get_filename_from_url($url->url); $target = sprintf('%s/%s', $assoc_args['to-directory'], $filename); if (TerminusCommand::download($url->url, $target)) { Terminus::success('Downloaded %s', $target); return $target; } else { Terminus::error('Could not download file'); } } Terminus::success($url->url); return $url->url; break; case 'load': $assoc_args['to-directory'] = '/tmp'; $assoc_args['element'] = 'database'; if (isset($assoc_args['database'])) { $database = $assoc_args['database']; } else { $database = escapeshellarg(Terminus::prompt('Name of database to import to')); } if (isset($assoc_args['username'])) { $username = $assoc_args['username']; } else { $username = escapeshellarg(Terminus::prompt('Username')); } if (isset($assoc_args['password'])) { $password = $assoc_args['password']; } else { $password = escapeshellarg(Terminus::prompt('Password')); } exec('mysql -e "show databases"', $stdout, $exit); if ($exit != 0) { Terminus::error('MySQL does not appear to be installed on your server.'); } $assoc_args['env'] = $env; $target = $this->backup(array('get'), $assoc_args); $target = '/tmp/' . \Terminus\Utils\get_filename_from_url($target); if (!file_exists($target)) { Terminus::error('Cannot read database file %s', array($target)); } Terminus::line('Unziping database'); exec("gunzip {$target}", $stdout, $exit); // trim the gz of the target $target = Terminus\Utils\sql_from_zip($target); $target = escapeshellarg($target); exec("mysql {$database} -u {$username} -p'{$password}' < {$target}", $stdout, $exit); if ($exit != 0) { Terminus::error('Could not import database'); } Terminus::success('%s successfuly imported to %s', array($target, $database)); return true; break; case 'create': if (!array_key_exists('element', $assoc_args)) { $assoc_args['element'] = Input::menu(array('code', 'db', 'files', 'all'), 'all', 'Select element'); } $workflow = $site->environments->get($env)->createBackup($assoc_args); $workflow->wait(); $this->workflowOutput($workflow); break; case 'list': default: $backups = $site->environments->get($env)->backups(); $element_name = false; if (isset($assoc_args['element']) && $assoc_args['element'] != 'all') { $element_name = $assoc_args['element']; } if ($element_name == 'db') { $element_name = 'database'; } $data = array(); foreach ($backups as $id => $backup) { if (!isset($backup->filename) || $element_name && !preg_match(sprintf('/backup_%s/', $element_name), $id)) { continue; } $date = 'Pending'; if (isset($backup->finish_time)) { $date = date('Y-m-d H:i:s', $backup->finish_time); } $size = $backup->size / 1048576; if ($size > 0.1) { $size = sprintf('%.1fMB', $size); } elseif ($size > 0) { $size = '0.1MB'; } else { //0-byte backups should not be recommended for restoration $size = 'Incomplete'; } $data[] = array('file' => $backup->filename, 'size' => $size, 'date' => $date); } if (empty($backups)) { \Terminus::error('No backups found.'); return false; } else { $this->outputter->outputRecordList($data, array('file' => 'File', 'size' => 'Size', 'date' => 'Date')); return $data; } break; } }
/** * Show a list of your sites on Pantheon * @package Terminus * @version 2.0 */ public function __construct() { parent::__construct(); Auth::loggedIn(); $this->sites = new Sites(); }
/** * Load site info * * @param [string] $key Set to retrieve a specific attribute as named * @return [array] $info */ public function info($key = null) { $path = sprintf('environments/%s', $this->get('id')); $result = \TerminusCommand::request('sites', $this->site->get('id'), $path, 'GET'); $connection_mode = null; if (isset($result['data']->on_server_development)) { $connection_mode = 'git'; if ((bool) $result['data']->on_server_development) { $connection_mode = 'sftp'; } } $info = array('id' => $this->get('id'), 'connection_mode' => $connection_mode, 'php_version' => $this->site->info('php_version')); if ($key) { if (isset($info[$key])) { return $info[$key]; } else { throw new TerminusException('There is no such field.', array(), -1); } } else { return $info; } }
/** * Make a request to the Pantheon API * * @param [string] $realm Permissions realm for data request (e.g. user, * site organization, etc. Can also be "public" to simply pull read-only * data that is not privileged. * @param [string] $uuid The UUID of the item in the realm to access * @param [string] $path API path (URL) * @param [string] $method HTTP method to use * @param [mixed] $options A native PHP data structure (e.g. int, string, * array, or stdClass) to be sent along with the request * @return [array] $data */ public static function request($realm, $uuid, $path = false, $method = 'GET', $options = array()) { $logger = Terminus::getLogger(); try { if (!in_array($realm, array('auth/refresh', 'login', 'user'))) { if (!isset($options['headers'])) { $options['headers'] = array(); } $options['headers']['Cookie'] = array('X-Pantheon-Session' => Session::getValue('id_token')); } 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)); $logger->debug('Request URL: ' . $url); Terminus::getLogger()->debug('URL: {url}', compact('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()); return $data; } catch (Guzzle\Http\Exception\BadResponseException $e) { $response = $e->getResponse(); throw new TerminusException($response->getBody(true)); } catch (Guzzle\Http\Exception\HttpException $e) { $request = $e->getRequest(); $sanitized_request = TerminusCommand::stripSensitiveData((string) $request, TerminusCommand::$blacklist); throw new TerminusException('API Request Error. {msg} - Request: {req}', array('req' => $sanitized_request, 'msg' => $e->getMessage())); } catch (Exception $e) { throw new TerminusException('API Request Error: {msg}', array('msg' => $e->getMessage())); } }
/** * Execute the login based on an existing session token * * @param $session_token string (required) * @return array */ private function doLoginFromSessionToken($session_token) { $options = array('headers' => array('Content-type' => 'application/json'), 'cookies' => array('X-Pantheon-Session' => $session_token)); # Temporarily disable the cache for this GET call $response = TerminusCommand::request('user', '', '', 'GET', $options); if (!$response or '200' != @$response['info']['http_code']) { $this->failure('Session token not valid'); } // Prepare credentials for storage. $data = array('user_uuid' => $response['data']->id, 'session' => $session_token, 'session_expire_time' => 0, 'email' => $response['data']->email); // creates a session instance Session::instance()->setData($data); return $data; }
/** * Instantiates object, sets auth property * * @return [Auth_Command] $this */ public function __construct() { parent::__construct(); $this->auth = new \Terminus\Auth(); }
/** * Start a work flow * * @param [Workflow] $workflow String work flow "slot" * @return [array] $response['data'] */ public function workflow($workflow) { $path = sprintf("environments/%s/workflows", $this->get('id')); $body = array('type' => $workflow, 'environment' => $this->get('id')); $options = compact('body'); $response = \TerminusCommand::request('sites', $this->site->get('id'), $path, 'POST', $options); return $response['data']; }
public function __construct() { Auth::ensureLogin(); parent::__construct(); $this->sites = new Sites(); }
/** * Get memberships for a site */ public function memberships($type = 'organizations') { $path = sprintf('memberships/%s', $type); $method = 'GET'; $response = \TerminusCommand::request('sites', $this->getId(), $path, $method); return $response['data']; }
public function __construct() { parent::__construct(); $this->sitesCache = new SitesCache(); }
private function envExists($site_id, $env) { $response = \TerminusCommand::request('sites', $site_id, 'environments', 'GET'); $envs = (array) $response['data']; return array_key_exists($env, $envs); }
/** * Requests API data and populates $this->profile * * @return [void] */ private function setProfile() { $path = 'profile'; $method = 'GET'; $response = \TerminusCommand::request('users', $this->id, $path, $method); $this->profile = $response['data']; }
/** * Make a request to the Pantheon API * * @param [string] $realm Permissions realm for data request (e.g. user, * site organization, etc. Can also be "public" to simply pull read-only * data that is not privileged. * @param [string] $uuid The UUID of the item in the realm to access * @param [string] $path API path (URL) * @param [string] $method HTTP method to use * @param [mixed] $options A native PHP data structure (e.g. int, string, * array, or stdClass) to be sent along with the request * @return [array] $data */ public static function request($realm, $uuid, $path = false, $method = 'GET', $options = array()) { $logger = Terminus::getLogger(); try { $url = Endpoint::get(array('realm' => $realm, 'uuid' => $uuid, 'path' => $path)); $logger->debug('Request URL: ' . $url); $response = Request::send($url, $method, $options); $data = array('data' => json_decode($response->getBody()->getContents()), 'headers' => $response->getHeaders(), 'status_code' => $response->getStatusCode()); return $data; } catch (Guzzle\Http\Exception\BadResponseException $e) { $response = $e->getResponse(); throw new TerminusException($response->getBody(true)); } catch (Guzzle\Http\Exception\HttpException $e) { $request = $e->getRequest(); $sanitized_request = TerminusCommand::stripSensitiveData((string) $request, TerminusCommand::$blacklist); throw new TerminusException('API Request Error. {msg} - Request: {req}', array('req' => $sanitized_request, 'msg' => $e->getMessage())); } catch (Exception $e) { throw new TerminusException('API Request Error: {msg}', array('msg' => $e->getMessage())); } }