/**
  * Make the request
  *
  * This method will create a new client and get a response from a Guzzle request
  *                                   
  * @param string|null      $handle     The handle of the request record
  *
  * @return array   the req
  */
 public function request($handle = null, array $config = array())
 {
     $this->config = array_merge(array('method' => 'GET', 'cache' => $this->placid_settings['cache'], 'duration' => 3600), $config);
     // Handle any changes to api gracefully
     $this->_swapDeprecatedConfig('path', 'segments');
     $this->_swapDeprecatedConfig('query', 'params');
     // Create a new guzzle client
     $client = new Client();
     if (!array_key_exists('url', $this->config)) {
         $record = $this->findRequestByHandle($handle);
     } else {
         $record = null;
     }
     $request = $this->_createRequest($client, $record);
     // Get a cached request
     $cachedRequest = craft()->placid_cache->get(base64_encode(urlencode($request->getUrl())));
     // Import the onBeforeRequest event
     Craft::import('plugins.placid.events.PlacidBeforeRequestEvent');
     $event = new PlacidBeforeRequestEvent($this, array('request' => $request));
     craft()->placid_requests->onBeforeRequest($event);
     // Check to make sure no other plugins have change anything
     if ($event->makeRequest) {
         if ((!$this->config['cache'] || !$cachedRequest) && !$event->bypassCache) {
             $response = $this->_getResponse($client, $request);
         } else {
             $response = $cachedRequest;
         }
     } else {
         return false;
     }
     Craft::import('plugins.placid.events.PlacidAfterRequestEvent');
     $event = new PlacidAfterRequestEvent($this, array('response' => $response));
     craft()->placid_requests->onAfterRequest($event);
     return $response;
 }
 /**
  * Initializes this component, Guzzle client, and plugin settings
  */
 public function init()
 {
     $this->httpClient = new Client();
     $this->pluginSettings = craft()->plugins->getPlugin('spamguard')->getSettings();
     Craft::import('plugins.spamguard.common.SpamGuardInvalidKeyException');
     parent::init();
 }
 public function optimizeImage($imageToOptimize)
 {
     if ($this->_settings && $this->_settings->useServerImageOptim) {
         $this->setToolAvailability();
         Craft::import('plugins.amtools.libraries.PHPImageOptim.PHPImageOptim', true);
         Craft::import('plugins.amtools.libraries.PHPImageOptim.Tools.Common', true);
         Craft::import('plugins.amtools.libraries.PHPImageOptim.Tools.ToolsInterface', true);
         $imageOptim = new \PHPImageOptim\PHPImageOptim();
         $imageOptim->setImage($imageToOptimize);
         switch (strtolower(pathinfo($imageToOptimize, PATHINFO_EXTENSION))) {
             case 'gif':
                 return $this->optimizeGif($imageOptim);
                 break;
             case 'png':
                 return $this->optimizePng($imageOptim);
                 break;
             case 'jpg':
             case 'jpeg':
                 return $this->optimizeJpeg($imageOptim);
                 break;
         }
     } elseif ($this->_settings && $this->_settings->useImagickImageOptim) {
         return $this->_optimizeAsset($imageToOptimize);
     }
     return true;
 }
 /**
  * Returns the requested elements as JSON
  *
  * @param callable|null $configFactory A function for generating the config
  * @param array|null    $config        The API endpoint configuration
  *
  * @throws Exception
  * @throws HttpException
  */
 public function actionGetElements($configFactory = null, array $config = null)
 {
     if ($configFactory !== null) {
         $params = craft()->urlManager->getRouteParams();
         $variables = isset($params['variables']) ? $params['variables'] : null;
         $config = $this->_callWithParams($configFactory, $variables);
     }
     // Merge in default config options
     $config = array_merge(['paginate' => true, 'pageParam' => 'page', 'elementsPerPage' => 100, 'first' => false, 'transformer' => 'Craft\\ElementApi_ElementTransformer'], craft()->config->get('defaults', 'elementapi'), $config);
     if ($config['pageParam'] == 'p') {
         throw new Exception('The pageParam setting cannot be set to "p" because that’s the parameter Craft uses to check the requested path.');
     }
     if (!isset($config['elementType'])) {
         throw new Exception('Element API configs must specify the elementType.');
     }
     /** @var ElementCriteriaModel $criteria */
     $criteria = craft()->elements->getCriteria($config['elementType'], ['limit' => null]);
     if (!empty($config['criteria'])) {
         $criteria->setAttributes($config['criteria']);
     }
     // Load Fractal
     $pluginPath = craft()->path->getPluginsPath() . 'elementapi/';
     require $pluginPath . 'vendor/autoload.php';
     $fractal = new Manager();
     $fractal->setSerializer(new ArraySerializer());
     // Define the transformer
     if (is_callable($config['transformer']) || $config['transformer'] instanceof TransformerAbstract) {
         $transformer = $config['transformer'];
     } else {
         Craft::import('plugins.elementapi.ElementApi_ElementTransformer');
         $transformer = Craft::createComponent($config['transformer']);
     }
     if ($config['first']) {
         $element = $criteria->first();
         if (!$element) {
             throw new HttpException(404);
         }
         $resource = new Item($element, $transformer);
     } else {
         if ($config['paginate']) {
             // Create the paginator
             require $pluginPath . 'ElementApi_PaginatorAdapter.php';
             $paginator = new ElementApi_PaginatorAdapter($config['elementsPerPage'], $criteria->total(), $config['pageParam']);
             // Fetch this page's elements
             $criteria->offset = $config['elementsPerPage'] * ($paginator->getCurrentPage() - 1);
             $criteria->limit = $config['elementsPerPage'];
             $elements = $criteria->find();
             $paginator->setCount(count($elements));
             $resource = new Collection($elements, $transformer);
             $resource->setPaginator($paginator);
         } else {
             $resource = new Collection($criteria, $transformer);
         }
     }
     JsonHelper::sendJsonHeaders();
     echo $fractal->createData($resource)->toJson();
     // End the request
     craft()->end();
 }
Exemplo n.º 5
0
 /**
  * Autoload Files
  *
  * @return void
  */
 public function autoload_files()
 {
     $autoload = craft()->config->get('autoload', 'restfulApi');
     if ($autoload['transformers']) {
         Craft::import('plugins.*.transformers.*', true);
     } else {
         Craft::import('plugins.restfulapi.transformers.*', true);
     }
     if ($autoload['validators']) {
         Craft::import('plugins.*.validators.*', true);
     } else {
         Craft::import('plugins.restfulapi.validators.*', true);
     }
     Craft::import('plugins.restfulapi.vendor.autoload', true);
 }
 public function init()
 {
     require CRAFT_PLUGINS_PATH . 'guestentriesstripe/vendor/autoload.php';
     $settings = $this->getSettings();
     craft()->on('guestEntries.beforeSave', function (GuestEntriesEvent $event) use($settings) {
         $entryModel = $event->params['entry'];
         $postData = $event->params['post'];
         // Test cards
         // https://stripe.com/docs/testing
         // https://github.com/stripe/jquery.payment
         // https://stripe.com/docs/tutorials/charges
         // https://stripe.com/docs/api#pagination
         // http://www.larryullman.com/2012/12/05/writing-the-javascript-code-for-handling-stripe-payments/
         if ($settings->enabled) {
             $mode = ucfirst($settings->stripeAccountMode);
             $key = 'stripe' . $mode . 'CredentialsSK';
             Stripe::setApiKey($settings->{$key});
             $token = isset($postData['stripeToken']) ? $postData['stripeToken'] : null;
             // If we have a token in the post data
             if ($token) {
                 // Try to charge token
                 try {
                     $charge = \Stripe\Charge::create(array("amount" => 10000, "currency" => $settings->stripeDefaultCurrency, "source" => $token, "description" => "Example charge"));
                     Craft::import('plugins.guestentriesstripe.events.GuestEntriesStripeEvent');
                     $event = new GuestEntriesStripeEvent($this, array('entry' => $entryModel, 'post' => craft()->request->getPost()));
                     craft()->guestEntriesStripe->onBeforeSave($event);
                 } catch (\Stripe\Error\Card $e) {
                     // The card has been declined
                     $entryModel->addError('stripePayment', sprintf('Stripe payment error (%s): %s', $e->getCode(), $e->getMessage()));
                     $event->isValid = false;
                 } catch (\Stripe\Error\ApiConnection $e) {
                     // Network communication with Stripe failed
                 } catch (\Stripe\Error\Base $e) {
                     // Display a very generic error to the user, and maybe send
                     // yourself an email
                 } catch (Exception $e) {
                     // Something else happened, completely unrelated to Stripe
                 }
             }
         }
     });
 }
Exemplo n.º 7
0
 /**
  * Initializes the console app by creating the command runner.
  */
 public function init()
 {
     // Set default timezone to UTC
     date_default_timezone_set('UTC');
     // Import all the built-in components
     foreach ($this->componentAliases as $alias) {
         Craft::import($alias);
     }
     // Attach our Craft app behavior.
     $this->attachBehavior('SchematicBehavior', new Schematic());
     // Attach our own custom Logger
     Craft::setLogger(new Logger());
     // Initialize Cache and LogRouter right away (order is important)
     $this->getComponent('cache');
     $this->getComponent('log');
     // So we can try to translate Yii framework strings
     $this->coreMessages->attachEventHandler('onMissingTranslation', ['Craft\\LocalizationHelper', 'findMissingTranslation']);
     // Set our own custom runtime path.
     $this->setRuntimePath(Craft::app()->path->getRuntimePath());
     // No need for these.
     Craft::app()->log->removeRoute('WebLogRoute');
     Craft::app()->log->removeRoute('ProfileLogRoute');
     // Set the edition components
     $this->_setEditionComponents();
     // Install Craft if needed
     if (!$this->isInstalled()) {
         $this->_installCraft();
     }
     // Set the schematic components
     $this->_setSchematicComponents();
     // Call parent::init() before the plugin console command logic so the command runner gets initialized
     parent::init();
     // Load the plugins
     Craft::app()->plugins->loadPlugins();
     // Validate some basics on the database configuration file.
     Craft::app()->validateDbConfigFile();
     // Add commands
     Craft::app()->commandRunner->commands = [];
     Craft::app()->commandRunner->addCommands(__DIR__ . '/../ConsoleCommands/');
 }
Exemplo n.º 8
0
 /**
  * Make the request
  *
  * This method will create a new client and get a response from a Guzzle request
  *
  * @param string|null      $handle     The handle of the request record
  *
  * @return array   the req
  */
 public function request($handle = null, array $config = array())
 {
     // Get our request from the database...or not
     if (!array_key_exists('url', $config)) {
         $model = $this->findRequestByHandle($handle);
     } else {
         $model = null;
     }
     $this->config = array_merge(array('method' => 'GET', 'cache' => $model ? $model->cache : true, 'duration' => 3600), $config);
     // if(isset($config['segments']))
     if (isset($this->config['segments'])) {
         $model->url = $this->parseSegments($model->url, $this->config['segments']);
     }
     $this->_swapDeprecatedConfig('query', 'params');
     // Create a new guzzle client
     $client = new Client();
     if ($model) {
         $request = $this->_createRequest($client, $model);
     } else {
         $request = $client->createRequest($this->config['method'], $this->config['url']);
     }
     // Get a cached request
     $cachedRequest = craft()->placid_cache->get($this->_getCacheId());
     // Import the onBeforeRequest event
     Craft::import('plugins.placid.events.PlacidBeforeRequestEvent');
     $event = new PlacidBeforeRequestEvent($this, array('request' => $request));
     craft()->placid_requests->onBeforeRequest($event);
     // Check to make sure no other plugins have change anything
     if ($event->makeRequest) {
         if ((!$this->config['cache'] || !$cachedRequest) && !$event->bypassCache) {
             $response = $this->_getResponse($client, $request);
         } else {
             $response = $cachedRequest;
         }
     } else {
         return false;
     }
     Craft::import('plugins.placid.events.PlacidAfterRequestEvent');
     $event = new PlacidAfterRequestEvent($this, array('response' => $response));
     $this->onAfterRequest($event);
     return $response;
 }
Exemplo n.º 9
0
 /**
  * Require any enums used across Minimee
  *
  * @return Void
  */
 protected function _autoload()
 {
     require_once craft()->path->getPluginsPath() . 'minimee/library/vendor/autoload.php';
     Craft::import('plugins.minimee.components.Minimee_Exception');
     Craft::import('plugins.minimee.components.Minimee_InfoException');
     Craft::import('plugins.minimee.components.Minimee_WarningException');
     Craft::import('plugins.minimee.components.Minimee_ErrorException');
     Craft::import('plugins.minimee.enums.MinimeeType');
     Craft::import('plugins.minimee.models.Minimee_ISettingsModel');
     Craft::import('plugins.minimee.models.Minimee_SettingsModel');
 }