protected function sendHookTestAction(Request $request) { $url = InputHelper::url($request->request->get('url')); // validate the URL if ($url == '' || !$url) { // default to an error message $dataArray = array('success' => 1, 'html' => '<div class="has-error"><span class="help-block">' . $this->factory->getTranslator()->trans('mautic.webhook.label.no.url') . '</span></div>'); return $this->sendJsonResponse($dataArray); } // get the selected types $selectedTypes = InputHelper::cleanArray($request->request->get('types')); $payloadPaths = $this->getPayloadPaths($selectedTypes); $payloads = $this->loadPayloads($payloadPaths); $now = new \DateTime(); $payloads['timestamp'] = $now->format('c'); // Set up custom headers $headers = ['Content-Type' => 'application/json']; // instantiate new http class $http = new Http(); // set the response $response = $http->post($url, json_encode($payloads), $headers); // default to an error message $dataArray = array('success' => 1, 'html' => '<div class="has-error"><span class="help-block">' . $this->factory->getTranslator()->trans('mautic.webhook.label.warning') . '</span></div>'); // if we get a 200 response convert to success message if ($response->code == 200) { $dataArray['html'] = '<div class="has-success"><span class="help-block">' . $this->factory->getTranslator()->trans('mautic.webhook.label.success') . '</span></div>'; } return $this->sendJsonResponse($dataArray); }
/** * Fetches a language package from the remote server * * @param string $languageCode * * @return array */ public function fetchPackage($languageCode) { // Check if we have a cache file, generate it if not if (!is_readable($this->cacheFile)) { $this->fetchLanguages(); } $cacheData = json_decode(file_get_contents($this->cacheFile), true); // Make sure the language actually exists if (!isset($cacheData['languages'][$languageCode])) { return array('error' => true, 'message' => 'mautic.core.language.helper.invalid.language'); } // GET the update data try { $data = $this->connector->get('https://updates.mautic.org/index.php?option=com_mauticdownload&task=downloadLanguagePackage&langCode=' . $languageCode); } catch (\Exception $exception) { $logger = $this->factory->getLogger(); $logger->addError('An error occurred while attempting to fetch the package: ' . $exception->getMessage()); return array('error' => true, 'message' => 'mautic.core.language.helper.error.fetching.package'); } if ($data->code != 200) { return array('error' => true, 'message' => 'mautic.core.language.helper.error.fetching.package'); } // Set the filesystem target $target = $this->factory->getSystemPath('cache') . '/' . $languageCode . '.zip'; // Write the response to the filesystem file_put_contents($target, $data->body); // Return an array for the sake of consistency return array('error' => false); }
/** * Constructor. * * @param Registry $options Client options object. * @param Transport $transport The HTTP transport object. * * @since 11.3 */ public function __construct(Registry $options = null, Transport $transport = null) { // Call the JHttp constructor to setup the object. parent::__construct($options, $transport); // Make sure the user agent string is defined. $this->options->def('userAgent', 'JGitHub/2.0'); // Set the default timeout to 120 seconds. $this->options->def('timeout', 120); }
/** * Shorten a URL. * * @param $url * * @return mixed */ public function buildShortUrl($url) { if (!$this->shortnerServiceUrl) { return $url; } try { $response = $this->http->get($this->shortnerServiceUrl . urlencode($url)); if ($response->code === 200) { return rtrim($response->body); } elseif ($this->logger) { $this->logger->addWarning("Url shortner failed with code {$response->code}: {$response->body}"); } } catch (\Exception $exception) { if ($this->logger) { $this->logger->addError($exception->getMessage(), ['exception' => $exception]); } } return $url; }
/** * Retrieves the update data from our home server * * @param bool $overrideCache * * @return array */ public function fetchData($overrideCache = false) { $cacheFile = $this->factory->getSystemPath('cache') . '/lastUpdateCheck.txt'; // Check if we have a cache file and try to return cached data if so if (!$overrideCache && is_readable($cacheFile)) { $update = (array) json_decode(file_get_contents($cacheFile)); // Check if the user has changed the update channel, if so the cache is invalidated if ($update['stability'] == $this->factory->getParameter('update_stability')) { // If we're within the cache time, return the cached data if ($update['checkedTime'] > strtotime('-3 hours')) { return $update; } } } // Before processing the update data, send up our metrics try { // Generate a unique instance ID for the site $instanceId = hash('sha1', $this->factory->getParameter('secret_key') . 'Mautic' . $this->factory->getParameter('db_driver')); $data = array('application' => 'Mautic', 'version' => $this->factory->getVersion(), 'phpVersion' => PHP_VERSION, 'dbDriver' => $this->factory->getParameter('db_driver'), 'serverOs' => php_uname('s') . ' ' . php_uname('r'), 'instanceId' => $instanceId, 'installSource' => $this->factory->getParameter('install_source', 'Mautic')); $this->connector->post('https://updates.mautic.org/stats/send', $data, array(), 10); } catch (\Exception $exception) { // Not so concerned about failures here, move along } // Get the update data try { $appData = array('appVersion' => $this->factory->getVersion(), 'phpVersion' => PHP_VERSION, 'stability' => $this->factory->getParameter('update_stability')); $data = $this->connector->post('https://updates.mautic.org/index.php?option=com_mauticdownload&task=checkUpdates', $appData, array(), 10); $update = json_decode($data->body); } catch (\Exception $exception) { // Log the error $logger = $this->factory->getLogger(); $logger->addError('An error occurred while attempting to fetch updates: ' . $exception->getMessage()); return array('error' => true, 'message' => 'mautic.core.updater.error.fetching.updates'); } if ($data->code != 200) { // Log the error $logger = $this->factory->getLogger(); $logger->addError(sprintf('An unexpected %1$s code was returned while attempting to fetch updates. The message received was: %2$s', $data->code, is_string($data->body) ? $data->body : implode('; ', $data->body))); return array('error' => true, 'message' => 'mautic.core.updater.error.fetching.updates'); } // If the user's up-to-date, go no further if ($update->latest_version) { return array('error' => false, 'message' => 'mautic.core.updater.running.latest.version'); } // Last sanity check, if the $update->version is older than our current version if (version_compare($this->factory->getVersion(), $update->version, 'ge')) { return array('error' => false, 'message' => 'mautic.core.updater.running.latest.version'); } // The user is able to update to the latest version, cache the data first $data = array('error' => false, 'message' => 'mautic.core.updater.update.available', 'version' => $update->version, 'announcement' => $update->announcement, 'package' => $update->package, 'checkedTime' => time(), 'stability' => $this->factory->getParameter('update_stability')); file_put_contents($cacheFile, json_encode($data)); return $data; }
/** * Constructor. * * @param array $options Client options array. * @param TransportInterface $transport The HTTP transport object. * * @since 1.0 */ public function __construct($options = array(), TransportInterface $transport = null) { // Call the JHttp constructor to setup the object. parent::__construct($options, $transport); // Make sure the user agent string is defined. if (!isset($this->options['userAgent'])) { $this->options['userAgent'] = 'JGitHub/2.0'; } // Set the default timeout to 120 seconds. if (!isset($this->options['timeout'])) { $this->options['timeout'] = 120; } }
/** * Constructor. * * @param array $options Client options array. * @param TransportInterface $transport The HTTP transport object. * * @since 1.0 */ public function __construct($options = array(), TransportInterface $transport = null) { // Call the BaseHttp constructor to setup the object. parent::__construct($options, $transport); // Make sure the user agent string is defined. if (!$this->getOption('userAgent')) { $this->setOption('userAgent', 'BDTransifex/2.0'); } // Set the default timeout to 120 seconds. if (!$this->getOption('timeout')) { $this->setOption('timeout', 120); } }
public function processWebhook(Webhook $webhook) { /** @var \Mautic\WebhookBundle\Entity\WebhookQueueRepository $webhookQueueRepo */ $webhookQueueRepo = $this->getQueueRepository(); // instantiate new http class $http = new Http(); // get the webhook payload $payload = $this->getWebhookPayload($webhook); // if there wasn't a payload we can stop here if (!count($payload)) { return; } // Set up custom headers $headers = ['Content-Type' => 'application/json']; /* @var \Mautic\WebhookBundle\Entity\Webhook $webhook */ try { /** @var \Joomla\Http\Http $http */ $response = $http->post($webhook->getWebhookUrl(), json_encode($payload), $headers); $this->addLog($webhook, $response); // throw an error exception if we don't get a 200 back if ($response->code != 200) { throw new \ErrorException($webhook->getWebhookUrl() . ' returned ' . $response->code); } } catch (\Exception $e) { // log any errors but allow the script to keep running $this->logger->addError($e->getMessage()); } // delete all the queued items we just processed $webhookQueueRepo->deleteQueuesById($this->webhookQueueIdList); $queueCount = $webhookQueueRepo->getQueueCountByWebhookId($webhook->getId()); // reset the array to blank so none of the IDs are repeated $this->webhookQueueIdList = []; // if there are still items in the queue after processing we re-process // WARNING: this is recursive if ($queueCount > 0) { $this->processWebhook($webhook); } }
/** * Request an oAuth token from GitHub. * * @param string $code The code obtained form GitHub on the previous step. * * @return string The OAuth token * * @since 1.0 * @throws \RuntimeException * @throws \DomainException */ public function requestToken($code) { // GitHub API works best with cURL $options = new Registry(); $transport = HttpFactory::getAvailableDriver($options, array('curl')); if (false == $transport) { throw new \DomainException('No transports available (please install php-curl)'); } $http = new Http($options, $transport); $data = array('client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'code' => $code); $response = $http->post('https://github.com/login/oauth/access_token', $data, array('Accept' => 'application/json')); if (200 != $response->code) { if (JDEBUG) { var_dump($response); } throw new \DomainException('Invalid response from GitHub (2) :('); } $body = json_decode($response->body); if (isset($body->error)) { switch ($body->error) { case 'bad_verification_code': throw new \DomainException('bad verification code'); break; default: throw new \DomainException('Unknown (2) ' . $body->error); break; } } if (!isset($body->access_token)) { throw new \DomainException('Can not retrieve the access token'); } return $body->access_token; }
/** * Upload build Zipfile to GitHub * * @param $version * @param $githubToken * @param $upload_url */ private function uploadToGithub($version, $githubToken, $upload_url) { $zipfile = "pkg-" . $this->getExtensionName() . "-" . $this->getConfig()->version . ".zip"; $zipfilepath = JPATH_BASE . "/dist/pkg-" . $this->getExtensionName() . "-" . $this->getConfig()->version . ".zip"; $filesize = filesize($zipfilepath); $this->say("Uploading the Extension package to the Github release: {$version}"); $uploadUrl = str_replace("{?name,label}", "?access_token={$githubToken}&name=" . $zipfile . "&size=" . $filesize, $upload_url); $this->say(print_r($uploadUrl, true)); $http = new Http(); $data = array("file" => $zipfilepath); $headers = array("Content-Type" => "application/zip"); $http->post($uploadUrl, $data, $headers); }
/** * @param Request $request * @return JoomlaResponse */ protected function patch(Request $request) { return $this->http->patch((string) $request->getUrl(), $request->getContent(), $this->prepareHeaders($request)); }