/** * Downloads a package * * @param string $url URL of file to download * @param string $target Download target filename [optional] * * @return mixed Path to downloaded package or boolean false on failure * * @since 11.1 */ public static function downloadPackage($url, $target = false) { $config = JFactory::getConfig(); // Capture PHP errors $track_errors = ini_get('track_errors'); ini_set('track_errors', true); // Set user agent $version = new JVersion(); ini_set('user_agent', $version->getUserAgent('Installer')); $http = JHttpFactory::getHttp(); $response = $http->get($url); if (200 != $response->code) { JLog::add(JText::_('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT'), JLog::WARNING, 'jerror'); return false; } if ($response->headers['wrapper_data']['Content-Disposition']) { $contentfilename = explode("\"", $response->headers['wrapper_data']['Content-Disposition']); $target = $contentfilename[1]; } // Set the target path if not given if (!$target) { $target = $config->get('tmp_path') . '/' . self::getFilenameFromURL($url); } else { $target = $config->get('tmp_path') . '/' . basename($target); } // Write buffer to file JFile::write($target, $response->body); // Restore error tracking to what it was before ini_set('track_errors', $track_errors); // Bump the max execution time because not using built in php zip libs are slow @set_time_limit(ini_get('max_execution_time')); // Return the name of the downloaded package return basename($target); }
/** * Request a page and return it as string. * * @param string $url A url to request. * @param string $method Request method, GET or POST. * @param string $query Query string. eg: 'option=com_content&id=11&Itemid=125'. <br /> Only use for POST. * @param array $option An option array to override CURL OPT. * * @throws \Exception * @return mixed If success, return string, or return false. */ public static function get($url, $method = 'get', $query = '', $option = array()) { if ((!function_exists('curl_init') || !is_callable('curl_init')) && ini_get('allow_url_fopen')) { $return = new Object(); $return->body = file_get_contents($url); return $return; } $options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1", CURLOPT_FOLLOWLOCATION => !ini_get('open_basedir') ? true : false, CURLOPT_SSL_VERIFYPEER => false); // Merge option $options = $option + $options; $http = \JHttpFactory::getHttp(new \JRegistry($options), 'curl'); try { switch ($method) { case 'post': case 'put': case 'patch': $result = $http->{$method}(UriHelper::safe($url), $query); break; default: $result = $http->{$method}(UriHelper::safe($url)); break; } } catch (\Exception $e) { return new NullObject(); } return $result; }
private function getBalance() { $cache = JFactory::getCache('paypal', 'output'); $cache->setCaching(1); $cache->setLifeTime($this->params->get('cache', 60) * 60); $key = md5($this->params->toString()); if (!($result = $cache->get($key))) { try { $http = JHttpFactory::getHttp(); $data = array('USER' => $this->params->get('apiuser'), 'PWD' => $this->params->get('apipw'), 'SIGNATURE' => $this->params->get('apisig'), 'VERSION' => '112', 'METHOD' => 'GetBalance'); $result = $http->post($this->url, $data); } catch (Exception $e) { JFactory::getApplication()->enqueueMessage($e->getMessage()); return $this->output = JText::_('ERROR'); } $cache->store($result, $key); } if ($result->code != 200) { $msg = __CLASS__ . ' HTTP-Status ' . JHtml::_('link', 'http://wikipedia.org/wiki/List_of_HTTP_status_codes#' . $result->code, $result->code, array('target' => '_blank')); JFactory::getApplication()->enqueueMessage($msg, 'error'); return $this->output = JText::_('ERROR'); } parse_str($result->body, $result->body); if (!isset($result->body['ACK']) || $result->body['ACK'] != 'Success') { return $this->output = $result->body['L_SHORTMESSAGE0']; } $this->success = true; $this->output = $result->body['L_AMT0'] . ' ' . $result->body['L_CURRENCYCODE0']; }
/** * Method to load a URI into the feed reader for parsing. * * @param string $uri The URI of the feed to load. Idn uris must be passed already converted to punycode. * * @return JFeedReader * * @since 12.3 * @throws InvalidArgumentException * @throws RuntimeException */ public function getFeed($uri) { // Create the XMLReader object. $reader = new XMLReader(); // Open the URI within the stream reader. if (!@$reader->open($uri, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) { // Retry with JHttpFactory that allow using CURL and Sockets as alternative method when available // Adding a valid user agent string, otherwise some feed-servers returning an error $options = new \joomla\Registry\Registry(); $options->set('userAgent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0'); $connector = JHttpFactory::getHttp($options); $feed = $connector->get($uri); if ($feed->code != 200) { throw new RuntimeException('Unable to open the feed.'); } // Set the value to the XMLReader parser if (!$reader->xml($feed->body, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) { throw new RuntimeException('Unable to parse the feed.'); } } try { // Skip ahead to the root node. while ($reader->read()) { if ($reader->nodeType == XMLReader::ELEMENT) { break; } } } catch (Exception $e) { throw new RuntimeException('Error reading feed.', $e->getCode(), $e); } // Setup the appopriate feed parser for the feed. $parser = $this->_fetchFeedParser($reader->name, $reader); return $parser->parse(); }
/** * Looks for an update to the extension * * @return string */ public function send() { JSession::checkToken('get') or jexit(JText::_('JINVALID_TOKEN')); $statsModel = $this->getModel(); $data = $statsModel->getData(); // Set up our JRegistry object for the BDHttp connector $options = new JRegistry(); // Use a 30 second timeout $options->set('timeout', 30); try { $transport = JHttpFactory::getHttp($options); } catch (Exception $e) { echo '###Something went wrong! We could not even get a transporter!###'; JFactory::getApplication()->close(); } // We have to provide the user-agent here, because Joomla! 2.5 won't understand it // If we add it in the $options... $request = $transport->post('https://stats.compojoom.com', $data, array('user-agent' => 'LibCompojoom/4.0')); // There is a bug in curl, that we don't have an work-around in j2.5 That's why we // will asume here that 100 == 200... if ($request->code == 200 || JVERSION < 3 && $request->code == 100) { // Let's update the date $statsModel->dataGathered(); echo '###All Good!###'; } else { echo '###Something went wrong!###'; } // Cut the execution short JFactory::getApplication()->close(); }
/** * Method to load a URI into the feed reader for parsing. * * @param string $uri The URI of the feed to load. Idn uris must be passed already converted to punycode. * * @return JFeedReader * * @since 12.3 * @throws InvalidArgumentException * @throws RuntimeException */ public function getFeed($uri) { // Create the XMLReader object. $reader = new XMLReader(); // Open the URI within the stream reader. if (!@$reader->open($uri, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) { // If allow_url_fopen is enabled if (ini_get('allow_url_fopen')) { // This is an error throw new RuntimeException('Unable to open the feed.'); } else { // Retry with JHttpFactory that allow using CURL and Sockets as alternative method when available $connector = JHttpFactory::getHttp(); $feed = $connector->get($uri); // Set the value to the XMLReader parser if (!$reader->xml($feed->body, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) { throw new RuntimeException('Unable to parse the feed.'); } } } try { // Skip ahead to the root node. while ($reader->read()) { if ($reader->nodeType == XMLReader::ELEMENT) { break; } } } catch (Exception $e) { throw new RuntimeException('Error reading feed.'); } // Setup the appopriate feed parser for the feed. $parser = $this->_fetchFeedParser($reader->name, $reader); return $parser->parse(); }
/** * Constructor. * * @param JRegistry $options OAuth1Client options object. * @param JHttp $client The HTTP client object. * @param JInput $input The input object * @param JApplicationWeb $application The application object * @param string $version Specify the OAuth version. By default we are using 1.0a. * * @since 13.1 */ public function __construct(JRegistry $options = null, JHttp $client = null, JInput $input = null, JApplicationWeb $application = null, $version = null) { $this->options = isset($options) ? $options : new JRegistry(); $this->client = isset($client) ? $client : JHttpFactory::getHttp($this->options); $this->input = isset($input) ? $input : JFactory::getApplication()->input; $this->application = isset($application) ? $application : new JApplicationWeb(); $this->version = isset($version) ? $version : '1.0a'; }
public function getContents($url, $fopen = 0) { $hash = md5('getByUrl_' . $url . '_' . $fopen); if (NNCache::has($hash)) { return NNCache::get($hash); } return NNCache::set($hash, JHttpFactory::getHttp()->get($url)->body); }
/** * */ public function __construct() { jimport('joomla.http.factory'); if (!class_exists('JHttpFactory')) { throw new BadFunctionCallException(JchPlatformUtility::translate('JHttpFactory not present. Please upgrade your version of Joomla. Exiting plugin...')); } $aOptions = array('follow_location' => true); $oOptions = new JRegistry($aOptions); $this->oHttpAdapter = JHttpFactory::getAvailableDriver($oOptions); }
/** * Downloads a package * * @param string $url URL of file to download * @param string $target Download target filename [optional] * * @return mixed Path to downloaded package or boolean false on failure * * @since 11.1 */ public static function downloadPackage($url, $target = false) { $config = JFactory::getConfig(); // Capture PHP errors $php_errormsg = 'Error Unknown'; $track_errors = ini_get('track_errors'); ini_set('track_errors', true); // Set user agent $version = new JVersion(); ini_set('user_agent', $version->getUserAgent('Installer')); $http = JHttpFactory::getHttp(); // load installer plugins, and allow url and headers modification $headers = array(); JPluginHelper::importPlugin('installer'); $dispatcher = JDispatcher::getInstance(); $results = $dispatcher->trigger('onInstallerBeforePackageDownload', array(&$url, &$headers)); try { $response = $http->get($url, $headers); } catch (Exception $exc) { $response = null; } if (is_null($response)) { JError::raiseWarning(42, JText::_('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT')); return false; } if (302 == $response->code && isset($response->headers['Location'])) { return self::downloadPackage($response->headers['Location']); } elseif (200 != $response->code) { if ($response->body === '') { $response->body = $php_errormsg; } JError::raiseWarning(42, JText::sprintf('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT', $response->body)); return false; } // Parse the Content-Disposition header to get the file name if (isset($response->headers['Content-Disposition']) && preg_match("/\\s*filename\\s?=\\s?(.*)/", $response->headers['Content-Disposition'], $parts)) { $target = trim(rtrim($parts[1], ";"), '"'); } // Set the target path if not given if (!$target) { $target = $config->get('tmp_path') . '/' . self::getFilenameFromURL($url); } else { $target = $config->get('tmp_path') . '/' . basename($target); } // Write buffer to file JFile::write($target, $response->body); // Restore error tracking to what it was before ini_set('track_errors', $track_errors); // bump the max execution time because not using built in php zip libs are slow @set_time_limit(ini_get('max_execution_time')); // Return the name of the downloaded package return basename($target); }
public function getContents($url, $timeout = 20) { $hash = md5('getContents_' . $url); if (NNCache::has($hash)) { return NNCache::get($hash); } try { $content = JHttpFactory::getHttp()->get($url, null, $timeout)->body; } catch (RuntimeException $e) { return ''; } return NNCache::set($hash, $content); }
/** * Get a single row * * @return step object */ public function requestRest($task = 'total', $table = false) { $http = JHttpFactory::getHttp(); $data = $this->getRestData(); // Getting the total $data['task'] = $task; $data['table'] = $table != false ? $table : ''; $request = $http->get($this->params->rest_hostname . '/index.php', $data); $code = $request->code; if ($code == 500) { throw new Exception('COM_REDMIGRATOR_REDMIGRATOR_ERROR_REST_REQUEST'); } else { return $code == 200 || $code == 301 ? $request->body : $code; } }
/** * @param $code * @return string * @throws Exception */ private function _closureCompiler($code) { if (JString::strlen($code) > 200000) { return $code; } if (!class_exists('JHttpFactory')) { return $code; } $response = JHttpFactory::getHttp()->post($this->_url, array('js_code' => $code, 'output_info' => 'compiled_code', 'output_format' => 'text', 'compilation_level' => 'WHITESPACE_ONLY'), array('Content-type' => 'application/x-www-form-urlencoded', 'Connection' => 'close'), 15); $result = $response->body; if (preg_match('/^Error\\(\\d\\d?\\):/', $result)) { throw new Exception('Google JS Minify: ' . $result); } return $result; }
/** * Method to test get(). * * @return void * * @covers Windwalker\Helper\CurlHelper::get */ public function testGet() { $url = 'http://example.com/'; $http = \JHttpFactory::getHttp(new \JRegistry($this->options), 'curl'); // Test with Restful Api 'GET' $helperOutput = CurlHelper::get($url); $jHttpOutput = $http->get($url); $this->assertEquals($helperOutput->code, $jHttpOutput->code); $this->assertEquals($helperOutput->body, $jHttpOutput->body); // Test with Restful Api 'POST' $helperOutput = CurlHelper::get($url, 'post', array('key' => 'value'), array('testHeader')); $jHttpOutput = $http->post($url, array('key' => 'value'), array('testHeader')); $this->assertEquals($helperOutput->code, $jHttpOutput->code); $this->assertEquals($helperOutput->body, $jHttpOutput->body); }
/** * Downloads a package * * @param string $url URL of file to download * @param string $target Download target filename [optional] * * @return mixed Path to downloaded package or boolean false on failure * * @since 11.1 */ public static function downloadPackage($url, $target = false) { $config = JFactory::getConfig(); // Capture PHP errors $php_errormsg = 'Error Unknown'; $track_errors = ini_get('track_errors'); ini_set('track_errors', true); // Set user agent $version = new JVersion(); ini_set('user_agent', $version->getUserAgent('Installer')); $http = JHttpFactory::getHttp(); try { $response = $http->get($url); } catch (Exception $exc) { $response = null; } if (is_null($response)) { JError::raiseWarning(42, JText::_('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT')); return false; } if (302 == $response->code && isset($response->headers['Location'])) { return self::downloadPackage($response->headers['Location']); } elseif (200 != $response->code) { if ($response->body === '') { $response->body = $php_errormsg; } JError::raiseWarning(42, JText::sprintf('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT', $response->body)); return false; } if (isset($response->headers['Content-Disposition'])) { $contentfilename = explode("\"", $response->headers['Content-Disposition']); $target = $contentfilename[1]; } // Set the target path if not given if (!$target) { $target = $config->get('tmp_path') . '/' . self::getFilenameFromURL($url); } else { $target = $config->get('tmp_path') . '/' . basename($target); } // Write buffer to file JFile::write($target, $response->body); // Restore error tracking to what it was before ini_set('track_errors', $track_errors); // bump the max execution time because not using built in php zip libs are slow @set_time_limit(ini_get('max_execution_time')); // Return the name of the downloaded package return basename($target); }
/** * Get the events from the google calendar api * * @param array $options The query parameter options * * @return mixed * * @throws UnexpectedValueException */ protected function getEvents($options) { $defaultOptions = array('orderBy' => 'startTime', 'singleEvents' => 'true'); $options = array_merge($defaultOptions, $options); // Create an instance of a default Http object. $http = JHttpFactory::getHttp(); $url = 'https://www.googleapis.com/calendar/v3/calendars/' . urlencode($this->calendarId) . '/events?key=' . urlencode($this->apiKey) . '&' . http_build_query($options); $response = $http->get($url); $data = json_decode($response->body); if ($data && isset($data->items)) { return $data->items; } elseif ($data) { return array(); } throw new UnexpectedValueException("Unexpected data received from Google: `{$response->body}`."); }
/** * Downloads a package * * @param string $url URL of file to download * @param mixed $target Download target filename or false to get the filename from the URL * * @return string|boolean Path to downloaded package or boolean false on failure * * @since 3.1 */ public static function downloadPackage($url, $target = false) { // Capture PHP errors $track_errors = ini_get('track_errors'); ini_set('track_errors', true); // Set user agent $version = new JVersion(); ini_set('user_agent', $version->getUserAgent('Installer')); // Load installer plugins, and allow url and headers modification $headers = array(); JPluginHelper::importPlugin('installer'); $dispatcher = JEventDispatcher::getInstance(); $results = $dispatcher->trigger('onInstallerBeforePackageDownload', array(&$url, &$headers)); try { $response = JHttpFactory::getHttp()->get($url, $headers); } catch (RuntimeException $exception) { JLog::add(JText::sprintf('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT', $exception->getMessage()), JLog::WARNING, 'jerror'); return false; } if (302 == $response->code && isset($response->headers['Location'])) { return self::downloadPackage($response->headers['Location']); } elseif (200 != $response->code) { JLog::add(JText::sprintf('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT', $response->code), JLog::WARNING, 'jerror'); return false; } // Parse the Content-Disposition header to get the file name if (isset($response->headers['Content-Disposition']) && preg_match("/\\s*filename\\s?=\\s?(.*)/", $response->headers['Content-Disposition'], $parts)) { $flds = explode(';', $parts[1]); $target = trim($flds[0], '"'); } $tmpPath = JFactory::getConfig()->get('tmp_path'); // Set the target path if not given if (!$target) { $target = $tmpPath . '/' . self::getFilenameFromUrl($url); } else { $target = $tmpPath . '/' . basename($target); } // Write buffer to file JFile::write($target, $response->body); // Restore error tracking to what it was before ini_set('track_errors', $track_errors); // Bump the max execution time because not using built in php zip libs are slow @set_time_limit(ini_get('max_execution_time')); // Return the name of the downloaded package return basename($target); }
protected function sendStats() { $http = JHttpFactory::getHttp(); $data = array('unique_id' => $this->params->get('unique_id'), 'php_version' => PHP_VERSION, 'db_type' => $this->db->name, 'db_version' => $this->db->getVersion(), 'cms_version' => JVERSION, 'server_os' => php_uname('s') . ' ' . php_uname('r')); $uri = new JUri('http://jstats.dongilbert.net/submit'); try { // Don't let the request take longer than 2 seconds to avoid page timeout issues $status = $http->post($uri, $data, null, 2); if ($status->code === 200) { $this->writeCacheFile(); } } catch (UnexpectedValueException $e) { // There was an error sending stats. Should we do anything? } catch (RuntimeException $e) { // There was an error connecting to the server or in the post request } }
private function sendSms($entry) { $params = $this->params; $user = $params->get("user"); $password = $params->get("password"); $from = $params->get("from"); $to = $params->get("to"); $message = $this->parseMessageBody($params->get("message"), $entry); $queryparams = http_build_query(array("action" => "sendsms", "user" => $user, "password" => $password, "from" => $from, "to" => $to, "text" => $message)); $response = JHttpFactory::getHttp()->get("http://www.smsglobal.com/http-api.php?" . $queryparams); if ($response->code == "200" && stripos($response->body, "OK: 0") !== -1) { return true; } else { error_log("failed -- don't save to database"); return false; } }
/** * Method to display a view. * * @param boolean $cachable If true, the view output will be cached * @param array $urlparams An array of safe url parameters and their variable types, for valid values see {@link JFilterInput::clean()}. * * @return $this */ public function display($cachable = false, $urlparams = []) { JFactory::getApplication()->mimeType = 'application/json'; $label = (object) ['label' => JText::_('COM_TRACKERSTATS_WIKI_LABEL_EDITS')]; try { $response = JHttpFactory::getHttp()->get('https://docs.joomla.org/api.php?action=query&list=allusers&format=json&auexcludegroup=bot&aulimit=100&auprop=editcount&auactiveusers=', ['Content-type: application/json']); } catch (Exception $e) { // Error handling? echo json_encode([[[]], [], [$label], JText::_('COM_TRACKERSTATS_WIKI_LABEL_EDITS_BY_CONTRIBUTOR_IN_PAST_30_DAYS')]); return $this; } // Getting results $users = json_decode($response->body); // Convert to array for processing $workArray = []; $totalEditsArray = []; foreach ($users->query->allusers as $user) { if ($user->name == 'MediaWiki default') { continue; } $workArray[$user->name] = $user->recenteditcount; $totalEditsArray[$user->name] = $user->editcount; } asort($workArray, SORT_NUMERIC); // Slice the last 25 entries $maxCount = 25; $arrayCount = count($workArray); if ($arrayCount > $maxCount) { $sliceStart = $arrayCount - $maxCount; $workArray = array_slice($workArray, $sliceStart, $maxCount); } $people = []; $edits = []; $i = 0; foreach ($workArray as $k => $v) { if ($v > 0 && $i++ < $maxCount) { $edits[] = $v; $people[] = JText::sprintf('COM_TRACKERSTATS_WIKI_CHART_PERSON_LABEL', $k, $totalEditsArray[$k]); } } // Send the response. echo json_encode([[$edits], $people, [$label], JText::_('COM_TRACKERSTATS_WIKI_LABEL_EDITS_BY_CONTRIBUTOR_IN_PAST_30_DAYS')]); return $this; }
/** * @param string $url * @param bool $persistent * * @return mixed JHttpResponse|string */ protected function getRemote($url, $persistent = false) { $cache = JFactory::getCache('wow', 'output'); $cache->setCaching(1); $cache->setLifeTime($this->params->get('cache_timeout', 30) * ($persistent ? 172800 : 60) + rand(0, 60)); // randomize cache time a little bit for each url $key = md5($url); if (!($result = $cache->get($key))) { try { $http = JHttpFactory::getHttp(); $http->setOption('userAgent', 'Joomla/' . JVERSION . '; WoW Library/@REVISION@; php/' . phpversion()); $result = $http->get($url, null, $this->params->get('socket_timeout', 10)); } catch (Exception $e) { return $e->getMessage(); } $cache->store($result, $key); } return $result; }
/** * Gets the status of the entered donation code from the donation code script * * @param string $host * @param string $donation_code * * @return int */ private static function getDonationCodeStatus($host, $donation_code) { if (!empty($host) and !empty($donation_code)) { // cURL has always priority - use allow_url_fopen only if selected or as fallback $jhttp_factory = JHttpFactory::getHttp(); $content = $jhttp_factory->get('http://joomla-extensions.kubik-rubik.de/scripts/je_kr_donation_code_check/je_kr_check_code.php?key=' . rawurlencode($donation_code) . '&host=' . rawurlencode($host)); // Code 200? Everything okay, go on! if ($content->code == 200) { if (preg_match('@(error|access denied)@i', $content->body)) { return -1; } return $content->body; } else { return -2; } } else { return 0; } }
public function getContents($url, $timeout = 20) { $hash = md5('getContents_' . $url); if (NNCache::has($hash)) { return NNCache::get($hash); } if (JFactory::getApplication()->input->getInt('cache', 0) && ($content = NNCache::read($hash))) { return $content; } try { $content = JHttpFactory::getHttp()->get($url, null, $timeout)->body; } catch (RuntimeException $e) { return ''; } if ($ttl = JFactory::getApplication()->input->getInt('cache', 0)) { return NNCache::write($hash, $content, $ttl > 1 ? $ttl : 0); } return NNCache::set($hash, $content); }
public function testsettings() { // Test the user settings $plugin = JPluginHelper::getPlugin("simplelogger", "sendlogs"); if (!$plugin) { echo json_encode(array("status" => "failed", "data" => JText::_("COM_SIMPLELOGGER_ERROR_NO_PLUGIN"))); die; } $params = json_decode($plugin->params, true); $queryparams = http_build_query(array("action" => "sendsms", "user" => $params["user"], "password" => $params["password"], "from" => $params["from"], "to" => $params["to"], "text" => $params["message"])); $response = JHttpFactory::getHttp()->get("http://www.smsglobal.com/http-api.php?" . $queryparams); if ($response->code == "200" && stripos($response->body, "OK: 0") !== -1) { echo json_encode(array("status" => "success")); return; } else { echo json_encode(array("status" => "failed", "data" => $response->body)); return; } return; }
/** * Api Request * * @param string $task * @param object $data */ public function apiRequest($task, $data = false) { // build request $request = (object) ['app' => $this->config->data_source_app_id, 'log' => microtime(true) * 100, 'task' => $task, 'data' => $data ? $data : (object) []]; $request->sign = hash('sha256', $this->config->data_source_app_secret . md5(json_encode($request))); // api request $api_request = ['request' => json_encode($request)]; try { $api_results = JHttpFactory::getHttp()->post($this->config->data_source_api_host, $api_request, [], $this->config->data_source_api_timeout); //CHLib::ajaxExit($api_results, 200, true); } catch (Exception $e) { throw new Exception(CHClient::string('error_api_unavailable'), 503); } // check result $result = json_decode($api_results->body); if (is_object($result)) { return $result; } //CHLib::ajaxExit($api_results->body, 200, true); throw new Exception(CHClient::string('error_api_unavailable'), 503); }
private function remote($url) { if (!filter_var($url, FILTER_VALIDATE_URL)) { return 'not a valid url: ' . $url; } $cache = JFactory::getCache('remote', 'output'); $cache->setCaching(1); $cache->setLifeTime($this->params->get('cache_time', 60) * 60); $key = md5($url); if (!($result = $cache->get($key))) { try { $http = JHttpFactory::getHttp(); $result = $http->get($url, null, $this->params->get('timeout', 10)); } catch (Exception $e) { return $e->getMessage(); } $cache->store($result, $key); } if ($result->code != 200) { return __CLASS__ . ' HTTP-Status ' . JHtml::_('link', 'http://wikipedia.org/wiki/List_of_HTTP_status_codes#' . $result->code, $result->code, array('target' => '_blank')); } return $result->body; }
protected function sendStats() { if (version_compare(JVERSION, '3.0', '<')) { JLoader::register('JHttp', dirname(__FILE__) . '/src/joomla/http/http.php'); JLoader::register('JHttpFactory', dirname(__FILE__) . '/src/joomla/http/factory.php'); JLoader::register('JHttpResponse', dirname(__FILE__) . '/src/joomla/http/response.php'); JLoader::register('JHttpTransport', dirname(__FILE__) . '/src/joomla/http/transport.php'); JLoader::register('JHttpTransportCurl', dirname(__FILE__) . '/src/joomla/http/transport/curl.php'); JLoader::register('JHttpTransportSocket', dirname(__FILE__) . '/src/joomla/http/transport/socket.php'); JLoader::register('JHttpTransportStream', dirname(__FILE__) . '/src/joomla/http/transport/stream.php'); } $http = JHttpFactory::getHttp(); $data = array('unique_id' => $this->params->get('unique_id'), 'php_version' => PHP_VERSION, 'db_type' => $this->db->name, 'db_version' => $this->db->getVersion(), 'cms_version' => JVERSION, 'server_os' => php_uname('s') . ' ' . php_uname('r')); $uri = new JUri('http://jstats.dongilbert.net/submit'); try { $status = $http->post($uri, $data); if ($status->code === 200) { $this->writeCacheFile(); } } catch (UnexpectedValueException $e) { // There was an error sending stats. Should we do anything?g } }
/** * {@inheritdoc} */ protected function _request($url, $args, Data $options) { $method = $options->get('method'); $headers = $options->get('headers'); $timeout = $options->get('timeout'); $sslVerify = $options->get('ssl_verify'); if (empty($headers)) { $headers = null; } if ($sslVerify) { // "curl" driver doesn't have such option $httpClient = \JHttpFactory::getHttp(); // try to find curl driver } else { $httpClient = \JHttpFactory::getHttp(null, 'stream'); } $httpClient->setOption('userAgent', $options->get('user_agent')); if (self::METHOD_GET === $method) { $apiResponse = $httpClient->get($url, $headers, $timeout); } elseif (self::METHOD_POST === $method) { $apiResponse = $httpClient->post($url, $args, $headers, $timeout); } elseif (self::METHOD_HEAD === $method) { $apiResponse = $httpClient->head($url, $headers, $timeout); } elseif (self::METHOD_PUT === $method) { $apiResponse = $httpClient->put($url, $args, $headers, $timeout); } elseif (self::METHOD_DELETE === $method) { $apiResponse = $httpClient->delete($url, $headers, $timeout); } elseif (self::METHOD_OPTIONS === $method) { $apiResponse = $httpClient->options($url, $headers, $timeout); } elseif (self::METHOD_PATCH === $method) { $apiResponse = $httpClient->patch($url, $args, $headers, $timeout); } else { $apiResponse = $httpClient->get($url, $headers, $timeout); } return $apiResponse; }
public function onJHarvestIngest($harvest) { $params = new JRegistry($harvest->params); $this->harvestId = $harvest->id; $items = $this->getCache(0); $i = count($items); $temp = 0; while (count($items) > 0) { foreach ($items as $item) { $data = json_decode($item->data); $metadata = $data->metadata; $assets = $data->assets; if (!isset($metadata->{"dc.type"})) { $metadata->{"dc.type"} = array("-"); } if (!isset($metadata->{"dc.description"})) { $metadata->{"dc.description"} = array("-"); } $collection = $params->get('ingest.dspace.collection'); $path = $this->buildPackage($item->id, $collection, $metadata, $assets); $http = JHttpFactory::getHttp(null, 'curl'); $headers = array('user' => $this->params->get('username'), 'pass' => $this->params->get('password'), 'Content-Type' => 'multipart/form-data'); $post = array('upload' => curl_file_create($path, 'application/zip', JFile::getName($path))); $url = new JUri($this->params->get('rest_url') . '/items.stream'); $response = $http->post($url, $post, $headers); if ($response->code == '201') { fwrite(STDOUT, "item created: " . (string) $response->body . "\n"); } else { fwrite(STDOUT, print_r($response, true) . "\n"); } JFile::delete($path); } $items = $this->getCache($i); $i += count($items); } }
/** * Instanciate http client using Singleton approach * * @return void */ protected static function getHttp() { if (self::$httpClient === null) { self::$httpClient = JHttpFactory::getHttp(); } }