/**
  * Generates a signature for a packet request response
  *
  * @param array                  $packet
  * @param int|null               $code
  * @param string|\Exception|null $message
  *
  * @return array
  *
  */
 protected static function signPacket(array $packet, $code = null, $message = null)
 {
     $_ex = false;
     if ($code instanceof \Exception) {
         $_ex = $code;
         $code = null;
     } elseif ($message instanceof \Exception) {
         $_ex = $message;
         $message = null;
     }
     !$code && ($code = Response::HTTP_OK);
     $code = $code ?: ($_ex ? $_ex->getCode() : Response::HTTP_OK);
     $message = $message ?: ($_ex ? $_ex->getMessage() : null);
     $_startTime = \Request::server('REQUEST_TIME_FLOAT', \Request::server('REQUEST_TIME', $_timestamp = microtime(true)));
     $_elapsed = $_timestamp - $_startTime;
     $_id = sha1($_startTime . \Request::server('HTTP_HOST') . \Request::server('REMOTE_ADDR'));
     //  All packets have this
     $_packet = array_merge($packet, ['error' => false, 'status_code' => $code, 'request' => ['id' => $_id, 'version' => static::PACKET_VERSION, 'signature' => base64_encode(hash_hmac(config('dfe.signature-method'), $_id, $_id, true)), 'verb' => \Request::method(), 'request-uri' => \Request::getRequestUri(), 'start' => date('c', $_startTime), 'elapsed' => (double) number_format($_elapsed, 4)]]);
     //  Update the error entry if there was an error
     if (!array_get($packet, 'success', false) && !array_get($packet, 'error', false)) {
         $_packet['error'] = ['code' => $code, 'message' => $message, 'exception' => $_ex ? Json::encode($_ex) : false];
     } else {
         array_forget($_packet, 'error');
     }
     return $_packet;
 }
Exemple #2
0
 /**
  * Specifies the data to be shaped
  *
  * @param array|mixed $data
  *
  * @return $this
  */
 public function with($data = [])
 {
     //  Convert to an array and store
     if (!is_array($data)) {
         if (is_scalar($data)) {
             throw new \InvalidArgumentException('The $data provided is a scalar value.');
         }
         if (false === ($_json = Json::encode($data)) || JSON_ERROR_NONE != json_last_error()) {
             throw new \InvalidArgumentException('The $data provided cannot be converted to an array.');
         }
         $data = Json::decode($_json, true);
     }
     $this->data = $data;
     return $this;
 }
 /**
  * Handle a provisioning request
  *
  * @param ProvisionJob $command
  *
  * @return mixed
  */
 public function handle(ProvisionJob $command)
 {
     $_options = $command->getOptions();
     $_guestLocation = array_get($_options, 'guest-location', config('provisioning.default-guest-location'));
     if (is_string($_guestLocation) && !is_numeric($_guestLocation)) {
         $_options['guest-location'] = GuestLocations::resolve($_guestLocation, true);
         \Log::debug('[Provision] guest location "' . $_options['guest-location'] . '" resolved from "' . $_guestLocation . '".');
         $_guestLocation = $_options['guest-location'];
     }
     \Log::info('[Provision] Request [guest=' . $_guestLocation . ']: ' . Json::encode($_options));
     try {
         //  Create the instance record
         $_instance = InstanceManager::make($command->getInstanceId(), $_options);
         if (!$_instance) {
             throw new ProvisioningException('InstanceManager::make() failed');
         }
     } catch (\Exception $_ex) {
         \Log::error('[Provision] failure, exception creating instance: ' . $_ex->getMessage());
         return false;
     }
     try {
         $_guest = array_get($_options, 'guest-location', config('provisioning.default-guest-location'));
         $_provisioner = Provision::getProvisioner($_guest);
         if (empty($_provisioner)) {
             throw new \RuntimeException('The provisioner of the request is not valid.');
         }
         if (false === ($_response = $_provisioner->provision(new ProvisionServiceRequest($_instance)))) {
             throw new ProvisioningException('provisioning error');
         }
         \Log::info('[Provision] completed in ' . number_format($_response->getElapsedTime(), 4) . 's');
         return $_response;
     } catch (\Exception $_ex) {
         \Log::error('[Provision] failure: ' . $_ex->getMessage());
         //  Delete instance record...
         if (!$_instance->delete()) {
             throw new \LogicException('Unable to remove created instance "' . $_instance->instance_id_text . '".');
         }
     }
     return false;
 }
Exemple #4
0
 /**
  * Handle the command
  *
  * @return int
  */
 public function fire()
 {
     $this->setOutputPrefix(false);
     /** @type UsageService $_service */
     $_service = \App::make(UsageServiceProvider::IOC_NAME);
     $_stats = $_service->gatherStatistics();
     if (!empty($_stats)) {
         if ($this->option('gather')) {
             Models\Metrics::where('sent_ind', 0)->update(['sent_ind' => 2]);
             Models\Metrics::create(['metrics_data_text' => $_stats]);
             return 0;
         }
         $_output = Json::encode($_stats, JSON_UNESCAPED_SLASHES);
         if (null !== ($_file = $this->option('to-file'))) {
             file_put_contents($_file, $_output);
         }
         $this->writeln($_output);
     } else {
         $this->writeln('No metrics were gathered.');
     }
     return 0;
 }
Exemple #5
0
 /**
  * @param Instance $instance
  * @param string   $subject
  * @param array    $data
  *
  * @return int The number of recipients mailed
  */
 protected function notifyInstanceOwner($instance, $subject, array $data)
 {
     try {
         if (!empty($this->subjectPrefix)) {
             $subject = $this->subjectPrefix . ' ' . trim(str_replace($this->subjectPrefix, null, $subject));
         }
         $data['dashboard_url'] = config('dfe.dashboard-url');
         $data['support_email_address'] = config('dfe.support-email-address');
         $_result = \Mail::send('emails.generic', $data, function ($message) use($instance, $subject) {
             $message->to($instance->user->email_addr_text, $instance->user->first_name_text . ' ' . $instance->user->last_name_text)->subject($subject);
         });
         $this instanceof Lumberjack && $this->debug('notification sent to "' . $instance->user->email_addr_text . '"');
         return $_result;
     } catch (\Exception $_ex) {
         \Log::error('Error sending notification: ' . $_ex->getMessage());
         $_mailPath = storage_path('logs/unsent-mail');
         if (!is_dir($_mailPath)) {
             mkdir($_mailPath, 0777, true);
         }
         @file_put_contents(date('YmdHis') . '-' . $instance->user->email_addr_text . '.json', Json::encode(array_merge($data, ['subject' => $subject, 'template' => 'emails.generic', 'instance' => $instance->toArray()])));
         return false;
     }
 }
 /**
  * @param string          $service The service to retrieve
  * @param int             $index   Which index to return if multiple. NULL returns all
  * @param string|int|null $subkey  Subkey under index to use instead of "credentials"
  *
  * @return array|bool
  * @throws \DreamFactory\Managed\Exceptions\ManagedEnvironmentException
  */
 public function getDatabaseConfig($service = self::BM_DB_SERVICE_KEY, $index = self::BM_DB_INDEX, $subkey = self::BM_DB_CREDS_KEY)
 {
     $this->cacheKey = static::CACHE_KEY_PREFIX . app('request')->getHttpHost();
     //  Decode and examine
     try {
         /** @type string $_envData */
         $_envData = getenv(static::BM_ENV_KEY);
         if (!empty($_availableServices = Json::decode($_envData, true))) {
             $_serviceSet = array_get($_availableServices, $service);
             //  Get credentials environment data
             $_config = array_get(isset($_serviceSet[$index]) ? $_serviceSet[$index] : [], $subkey, []);
             if (empty($_config)) {
                 throw new \RuntimeException('DB credentials not found in env: ' . print_r($_serviceSet, true));
             }
             $_db = ['driver' => 'mysql', 'host' => array_get($_config, 'host', array_get($_config, 'hostname', 'localhost')), 'database' => $_config['name'], 'username' => $_config['username'], 'password' => $_config['password'], 'port' => $_config['port'], 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false];
             unset($_envData, $_config, $_serviceSet);
             return $_db;
         }
     } catch (\InvalidArgumentException $_ex) {
         //  Environment not set correctly for this deployment
     }
     //  Database configuration not found for bluemix
     throw new ManagedEnvironmentException('Bluemix platform detected but no database services are available.');
 }
Exemple #7
0
 /**
  * Transforms an array of data into a new shape
  *
  * @param array $source  The source data
  * @param array $options Any options to pass through to the shaping mechanism
  *
  * @return mixed
  */
 public static function transform(array $source, $options = [])
 {
     return Json::encode($source, data_get($options, 'options'), data_get($options, 'depth', 512));
 }
 /**
  * Writes the file
  *
  * @param int       $options    Any JSON encoding options
  * @param int       $depth      The maximum recursion depth
  * @param int       $retries    The number of times to retry the write.
  * @param float|int $retryDelay The number of microseconds (100000 = 1s) to wait between retries
  *
  * @return bool
  */
 protected function doWrite($options = 0, $depth = 512, $retries = self::STORAGE_OPERATION_RETRY_COUNT, $retryDelay = self::STORAGE_OPERATION_RETRY_DELAY)
 {
     $_attempts = $retries;
     //  Let's not get cray-cray
     if ($_attempts < 1) {
         $_attempts = 1;
     }
     if ($_attempts > 5) {
         $_attempts = 5;
     }
     $this->backupExistingFile();
     $_contents = $this->toArray();
     if (empty($_contents) || !is_array($_contents)) {
         //  Always use the current template
         $_contents = $this->template;
     }
     while ($_attempts--) {
         try {
             if ($this->filesystem->put($this->filename, Json::encode($_contents, $options, $depth))) {
                 break;
             }
             throw new FileException('Unable to write data to file "' . $this->filename . '" after ' . $retries . ' attempt(s).');
         } catch (FileException $_ex) {
             if ($_attempts) {
                 usleep($retryDelay);
                 continue;
             }
             throw $_ex;
         }
     }
     return true;
 }
Exemple #9
0
 /**
  * Creates an array of data suitable for writing to a shell script for sourcing
  */
 public function writeInstallerFiles()
 {
     if (empty($this->formData)) {
         throw new \RuntimeException('No form data has been specified. Cannot write blanks.');
     }
     //  Fix up fact data
     $_facts = [];
     foreach ($this->facterData as $_key => $_value) {
         $_facts[] = $_key . '=' . $_value;
     }
     //  Write out source file
     if (false === file_put_contents($this->outputFile, '#!/bin/sh' . PHP_EOL . PHP_EOL . implode(PHP_EOL, $_facts) . PHP_EOL . PHP_EOL)) {
         throw new FileSystemException('Unable to write output file "' . $this->outputFile . '"');
     }
     //  Write out the JSON file
     if (false === file_put_contents($this->jsonFile, Json::encode($this->cleanData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))) {
         throw new FileSystemException('Unable to write JSON output file "' . $this->jsonFile . '"');
     }
 }
 /**
  * Using the --format option (if specified) format an array of data for output in that format
  *
  * @param array       $array
  * @param bool        $pretty
  * @param string|null $rootNode Enclose transformed data inside a $rootNode
  * @param string      $type     Inner node name prefix. Defaults to 'item'. Used only for XML
  *
  * @return string
  */
 protected function formatArray(array $array, $pretty = true, $rootNode = 'root', $type = 'item')
 {
     switch ($this->format) {
         case 'json':
             return Json::encode($array, ($pretty ? JSON_PRETTY_PRINT : 0) | JSON_UNESCAPED_SLASHES);
         case 'xml':
             return XmlShape::transform($array, ['root' => $rootNode, 'item-type' => $type, 'ugly' => !$pretty]);
     }
     //  Default is to use print_r format
     return print_r($array, true);
 }
 /**
  * Makes a shout out to an instance's private back-end. Should be called bootyCall()  ;)
  *
  * @param string $uri     The REST uri (i.e. "/[rest|api][/v[1|2]]/db", "/rest/system/users", etc.) to retrieve
  *                        from the instance
  * @param array  $payload Any payload to send with request
  * @param array  $options Any options to pass to transport layer
  * @param string $method  The HTTP method. Defaults to "POST"
  *
  * @return array|bool|\stdClass
  */
 public function call($uri, $payload = [], $options = [], $method = Request::METHOD_POST)
 {
     $options[CURLOPT_HTTPHEADER] = array_merge(array_get($options, CURLOPT_HTTPHEADER, []), $this->headers ?: []);
     if (!empty($payload) && !is_scalar($payload)) {
         $payload = Json::encode($payload);
         $options[CURLOPT_HTTPHEADER] = array_merge(array_get($options, CURLOPT_HTTPHEADER, []), ['Content-Type: application/json']);
     }
     try {
         $_response = Curl::request($method, $this->resourceUri . ltrim($uri, ' /'), $payload, $options);
     } catch (\Exception $_ex) {
         $this->error('[dfe.instance-api-client] ' . $method . ' failure: ' . $_ex->getMessage());
         return false;
     }
     return $_response;
 }