/** * Get the location based on freegeoip * * @return bool|string * * @since 5.1.0 */ protected static function getGeolocation() { $ip = self::getUserIp(); $url = 'http://freegeoip.net/json/' . $ip; $options = new JRegistry(); $transport = new JHttpTransportCurl($options); // Create a 'curl' transport. $http = new JHttp($options, $transport); $http->setOption('timeout', 5); try { $get = $http->get($url); } catch (Exception $e) { return false; } if ($get->code === 200) { $body = json_decode($get->body); $text = 'Unknown'; // Small to large areas if (!empty($body->city)) { $text = $body->city; } elseif (!empty($body->zip_code)) { $text = $body->zip_code; } elseif (!empty($body->region_name)) { $text = $body->region_name; } elseif (!empty($body->country_name)) { $text = $body->country_name; } return array('lat' => $body->latitude, 'lng' => $body->longitude, 'text' => $text); } return false; }
public static function api($posts) { if (class_exists('JHttp')) { $posts_default = array('platform' => N2Platform::getPlatform()); $client = new JHttp(); $response = $client->post(self::$api, $posts + $posts_default, array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8')); if ($response->code != '200') { N2Message::error(n2_('Unable to contact with the licensing server, please try again later!')); return array('status' => 'ERROR_HANDLED'); } if (isset($response->headers['Content-Type'])) { $contentType = $response->headers['Content-Type']; } $data = $response->body; } if (!isset($data)) { if (function_exists('curl_init')) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, self::$api); $posts_default = array('platform' => N2Platform::getPlatform()); curl_setopt($ch, CURLOPT_POSTFIELDS, $posts + $posts_default); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($ch); $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); $error = curl_error($ch); $curlErrorNumber = curl_errno($ch); curl_close($ch); if ($curlErrorNumber) { N2Message::error($curlErrorNumber . $error); return array('status' => 'ERROR_HANDLED'); } } else { $posts_default = array('platform' => N2Platform::getPlatform()); $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($posts + $posts_default))); $context = stream_context_create($opts); $data = file_get_contents(self::$api, false, $context); if ($data === false) { N2Message::error(n2_('CURL disabled in your php.ini configuration. Please enable it!')); return array('status' => 'ERROR_HANDLED'); } $headers = self::parseHeaders($http_response_header); if ($headers['status'] != '200') { N2Message::error(n2_('Unable to contact with the licensing server, please try again later!')); return array('status' => 'ERROR_HANDLED'); } if (isset($headers['content-type'])) { $contentType = $headers['content-type']; } } } switch ($contentType) { case 'application/json': return json_decode($data, true); } return $data; }
/** * Initialize the video */ private function _init() { StreamFactory::load('libraries.slideshare'); jimport('joomla.http.http'); $feedURL = 'http://www.slideshare.net/api/oembed/2?url=' . $this->source . '&format=json'; $options = new JRegistry(); $transport = new JHttpTransportCurl($options); $http = new JHttp($options, $transport); $response = $http->get($feedURL); $this->response = $response->body; return true; }
public function init($url) { jimport('joomla.http.http'); $this->url = $url; $this->videoId = $this->getId(); $feedURL = 'http://gdata.youtube.com/feeds/api/videos/' . $this->videoId; $options = new JRegistry(); $transport = new JHttpTransportCurl($options); $http = new JHttp($options, $transport); $response = $http->get($feedURL); $this->xmlContent = $response->body; return true; }
/** * Fetch google map data refere to * http://code.google.com/apis/maps/documentation/geocoding/#Geocoding */ public static function getAddressData($address) { $url = JMap::GEOCODE_URL . 'address=' . urlencode($address) . '&sensor=false'; $options = new JRegistry(); $transport = new JHttpTransportCurl($options); $http = new JHttp($options, $transport); $response = $http->get($url); $content = $response->body; $status = null; if (!empty($content)) { $status = json_decode($content); } return $status; }
public function init($url) { jimport('joomla.http.http'); $this->url = $url; $this->videoId = $this->getId(); $feedURL = 'http://vimeo.com/api/v2/video/' . $this->videoId . '.json'; $options = new JRegistry(); $transport = new JHttpTransportCurl($options); $http = new JHttp($options, $transport); $response = $http->get($feedURL); $this->responseObj = json_decode($response->body); $this->responseObj = $this->responseObj[0]; // only take the first response return true; }
/** * Constructor. * * @param Registry $options Client options object. * @param JHttpTransport $transport The HTTP transport object. * * @since 11.3 */ public function __construct(Registry $options = null, JHttpTransport $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); }
/** * Get a single row * * @return step object */ public function requestRest($task = 'total', $table = false, $chunk = false) { // JHttp instance jimport('joomla.http.http'); $http = new JHttp(); $data = $this->getRestData(); // Getting the total $data['task'] = $task; $data['table'] = $table !== false ? $table : ''; $data['chunk'] = $chunk !== false ? $chunk : ''; $data['keepid'] = $this->params->keep_ids ? $this->params->keep_ids : 0; $request = $http->get($this->params->rest_hostname . '/index.php', $data); $code = $request->code; if ($code == 500) { throw new Exception('COM_JUPGRADEPRO_ERROR_REST_REQUEST'); } else { return $code == 200 || $code == 301 ? $request->body : $code; } }
/** * Check repository server * * @return bool|False */ public function check() { if (empty($this->location)) { return false; } $key = $this->_tbl_key; if (!$this->{$key}) { $site_uri = JUri::getInstance()->base(); $http = new JHttp(); $callback_function = 'mp'; $repository = JUri::getInstance($this->location); $repository->setVar('callback', $callback_function); $response = $http->get($repository, array('referer' => $site_uri)); if (200 != $response->code) { return $this->error($this->location, JText::sprintf('COM_MARKETPLACE_REPOSITORY_OPEN_URL', $url)); } if (strpos($response->body, $callback_function . '(') === false) { return $this->error($this->location, JText::_('COM_MARKETPLACE_REPOSITORY_RESPONSE_DONT_SUPPORT_JSONP')); } $response->body = substr($response->body, 3, -1); $data = json_decode($response->body, true); if (is_null($data)) { return $this->error($this->location, JText::_('COM_MARKETPLACE_REPOSITORY_INVALID_RESPONSE')); } $this->name = $data['repository']['name']; } if ($this->location) { $key = $this->_tbl_key; $query = $this->_db->getQuery(true); $query->select($this->_tbl_key); $query->from($this->_tbl); $query->where('location=' . $this->_db->quote($this->location)); $this->_db->setQuery($query); $this->{$key} = $this->_db->loadResult(); } if ($this->{$key} == 0) { $this->published = 1; } return true; }
private function remoteContent($url) { $cache = JFactory::getCache('wow', 'output'); $cache->setCaching(1); $cache->setLifeTime($this->params->get('cache_time', 24) * 60 + rand(0, 60)); // randomize cache time a little bit for each url $key = md5($url); if (!($result = $cache->get($key))) { try { $http = new JHttp(new JRegistry(), new JHttpTransportCurl(new JRegistry())); $http->setOption('userAgent', 'Joomla! ' . JVERSION . '; WoW Raid Progress - WotLK; php/' . phpversion()); $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 json_decode($result->body); }
/** * Send data to PayPal servers and handling the PayPal method "doVoid". * * <code> * $url = "https://api-3t.paypal.com/nvp"; * * $options = new Registry(); * $options->set("credentials.username", "itprism"); * .... * * $paypal = new Prism\PayPal\Express($url, $options); * $paypal->doVoid(); * </code> * * @return string * * @throws \RuntimeException */ public function doVoid() { $data = array("METHOD" => "DoVoid", "USER" => $this->options->get("credentials.username"), "PWD" => $this->options->get("credentials.password"), "SIGNATURE" => $this->options->get("credentials.signature"), "VERSION" => $this->options->get("api.version")); $data["AUTHORIZATIONID"] = $this->options->get("payment.authorization_id"); $response = $this->transport->post($this->url, $data); $body = $this->parseResponse($response); if (strcmp("Success", $body["ACK"]) != 0) { $this->error = ArrayHelper::getValue($body, "L_SHORTMESSAGE0") . ":" . ArrayHelper::getValue($body, "L_LONGMESSAGE0"); $this->errorCode = ArrayHelper::getValue($body, "L_ERRORCODE0"); throw new \RuntimeException($this->error, $this->errorCode); } return $body; }
/** * Method to send the request which does not require authentication. * * @param string $path The path of the request to make * @param string $method The request method. * @param array $headers The headers passed in the request. * @param mixed $data Either an associative array or a string to be sent with the post request. * * @return SimpleXMLElement The XML response * * @since 13.1 * @throws DomainException */ public function sendRequest($path, $method = 'GET', $headers = array(), $data = '') { // Send the request. switch ($method) { case 'GET': $response = $this->client->get($path, $headers); break; case 'POST': $response = $this->client->post($path, $data, $headers); break; } // Validate the response code. if ($response->code != 200) { $error = htmlspecialchars($response->body); throw new DomainException($error, $response->code); } $xml_string = simplexml_load_string($response->body); return $xml_string; }
/** * Send data to PayPal servers and handling the PayPal method "CancelPreapproval". * * <code> * $url = "https://svcs.sandbox.paypal.com/AdaptivePayments"; * * $options = new Registry(); * $options->set("credentials.username", "itprism"); * .... * * $paypal = new PrismPayPalAdaptive($url, $options); * $paypal->doVoid(); * </code> * * @return Response * * @throws \RuntimeException */ public function doVoid() { $url = $this->url . "CancelPreapproval"; $data = array("preapprovalKey" => $this->options->get("payment.preapproval_key"), "requestEnvelope" => $this->options->get("request.envelope")); // Encode data to JSON. $jsonData = json_encode($data); // Prepare headers. $headers = $this->getHeaders($jsonData); // Make a request. $response = $this->transport->post($url, $jsonData, $headers); $response = $this->parseResponse($response, "json"); $response = new Response($response); if ($response->isFailure()) { // Failure $this->error = $response->getErrorMessage(); $this->errorCode = $response->getErrorCode(); throw new \RuntimeException($this->error, $this->errorCode); } return $response; }
function getAvatarUrl($providerUserId, $nullForDefault = false, $params = null) { if (!$params) { $params = new JRegistry(); } $width = $params->get('width', 300); $nullString = $nullForDefault ? 'null' : 'notnull'; $avatarUrl = JFBCFactory::cache()->get('google.avatar.' . $nullString . '.' . $providerUserId . '.' . $width); if ($avatarUrl === false) { $profile = $this->fetchProfile($providerUserId, 'image'); $avatarUrl = $profile->get('image.url', null); // Check for default image if ($avatarUrl) { if ($nullForDefault) { $http = new JHttp(); $avatar = $http->get($avatarUrl); if ($avatar->code == 200 && $avatar->headers['Content-Length'] == 946) { $avatarUrl = null; } } if ($avatarUrl) { $avatarUrl = str_replace("?sz=50", "?sz=" . $width, $avatarUrl); } // get a suitably large image to be resized JFBCFactory::cache()->store($avatarUrl, 'google.avatar.' . $nullString . '.' . $providerUserId . '.' . $width); } } return $avatarUrl; }
/** * Renders the notification item that is loaded for the user. * * This trigger is useful when you want to manipulate the notification item that appears * in the notification drop down. * * @since 1.0 * @access public * @param string * @return */ public function onNotificationBeforeCreate($item_dt) { //checking table is exists in database then only execute patch. $db = FD::db(); $stbl = $db->getTableColumns('#__social_gcm_users'); $reg_ids = array(); $targetUsers = array(); // Create a new query object. $query = $db->getQuery(true); // Select records from the user social_gcm_users table". $query->select($db->quoteName(array('device_id', 'sender_id', 'server_key', 'user_id'))); $query->from($db->quoteName('#__social_gcm_users')); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results as a list of stdClass objects (see later for more options on retrieving data). $urows = $db->loadObjectList(); $rule = $item_dt->rule; //Generate element from rule. $segments = explode('.', $rule); $element = array_shift($segments); $participants = $item_dt->participant; $emailOptions = $item_dt->email_options; $systemOptions = $item_dt->sys_options; $msg_data = $this->createMessageData($element, $emailOptions, $systemOptions, $participants); $targetUsers = $msg_data['tusers']; $count = rand(1, 100); $user = FD::user(); $actor_name = $user->username; $tit = JText::_($msg_data['title']); $tit = str_replace('{actor}', $actor_name, $tit); foreach ($urows as $notfn) { if (in_array($notfn->user_id, $targetUsers)) { $reg_ids[] = $notfn->device_id; $server_k = $notfn->server_key; } } //build message for GCM if (!empty($reg_ids)) { //increment counter $registatoin_ids = $reg_ids; // Message to be sent $message = $tit; //Google cloud messaging GCM-API url $url = 'https://gcm-http.googleapis.com/gcm/send'; //Setting headers for gcm service. $headers = array('Authorization' => 'key=' . $server_k, 'Content-Type' => 'application/json'); //Setting fields for gcm service. //fields contents what data to be sent. $fields = array('registration_ids' => $registatoin_ids, 'data' => array("title" => $message, "message" => $msg_data['mssge'], "notId" => $count, "url" => $msg_data['ul'], "body" => $msg_data['mssge'])); //Making call to GCM API using POST. jimport('joomla.client.http'); //Using JHttp for API call $http = new JHttp(); $options = new JRegistry(); //$transport = new JHttpTransportStream($options); $http = new JHttp($options); $gcmres = $http->post($url, json_encode($fields), $headers); } }
public function getExtensions() { // Get catid, search filter, order column, order direction $cache = JFactory::getCache(); $cache->setCaching(1); $http = new JHttp(); $http->setOption('timeout', 60); $componentParams = JComponentHelper::getParams('com_apps'); $api_url = new JUri(); $default_limit = $componentParams->get('default_limit', 8); $input = new JInput(); $catid = $input->get('id', null, 'int'); $order = $input->get('ordering', $this->getOrderBy()); $orderCol = $this->state->get('list.ordering', $order); $orderDirn = $orderCol == 'core_title' ? 'ASC' : 'DESC'; $release = preg_replace('/[^\\d]/', '', base64_decode($input->get('release', '', 'base64'))); $limitstart = $input->get('limitstart', 0, 'int'); $limit = $input->get('limit', $default_limit, 'int'); $dashboard_limit = $componentParams->get('extensions_perrow') * 6; // 6 rows of extensions $search = str_replace('_', ' ', urldecode(trim($input->get('filter_search', null)))); $release = intval($release / 5) * 5; $api_url->setScheme('http'); $api_url->setHost('extensions.joomla.org/index.php'); $api_url->setvar('option', 'com_jed'); $api_url->setvar('controller', 'filter'); $api_url->setvar('view', 'extension'); $api_url->setvar('format', 'json'); $api_url->setvar('limit', $limit); $api_url->setvar('limitstart', $limitstart); $api_url->setvar('filter[approved]', '1'); $api_url->setvar('filter[published]', '1'); $api_url->setvar('extend', '0'); $api_url->setvar('order', $orderCol); $api_url->setvar('dir', $orderDirn); if ($search) { $api_url->setvar('searchall', urlencode($search)); } $extensions_json = $cache->call(array($http, 'get'), $api_url); $items = json_decode($extensions_json->body); $items = $items->data; // Populate array $extensions = array(0 => array(), 1 => array()); foreach ($items as $item) { $item->image = $this->getBaseModel()->getMainImageUrl($item); if ($search) { $extensions[1 - $item->foundintitle][] = $item; } else { $extensions[0][] = $item; } } return array_merge($extensions[0], $extensions[1]); }
/** * Method to connect to a server and get the resource. * * @param JUri $uri The URI to connect with. * * @return mixed Connection resource on success or boolean false on failure. * * @since 11.3 */ public function connect(JUri $uri) { return parent::connect($uri); }
/** * Gets a list of the merged pull numbers. * * @param integer The pull/issue number. * * @return array * * @since 11.3 */ protected function getMergedPulls() { $cutoff = 10; $page = 1; $merged = array(); while ($cutoff--) { $http = new JHttp(); $r = $http->get('https://api.github.com/repos/joomla/joomla-platform/pulls?state=closed&page=' . $page++ . '&per_page=100'); $pulls = json_decode($r->body); // Check if we've gone past the last page. if (empty($pulls)) { break; } // Loop through each of the pull requests. foreach ($pulls as $pull) { // If merged, add to the white list. if ($pull->merged_at) { $merged[] = $pull->number; } } } return $merged; }
public function verify() { // if Recaptcha is not enabled, return true if (!$this->enabled) { return true; } // get the Recaptcha response from the form data $response = JFactory::getApplication()->input->get('g-recaptcha-response'); if (!$response) { return false; } // send it to verification server for confirmation $http = new JHttp(); $result = $http->post($this->verifyUrl, array('secret' => $this->privateKey, 'remoteip' => $this->ip, 'response' => $response)); $result = json_decode($result->body); return $result->success === true ? true : false; }
/** * Query from eBay API the JSON stream of item id given to render * * @param int $ItemID The eBay ID of object to query * * @return string */ public static function getEbayItem($ItemID) { $config = KunenaFactory::getConfig(); if (is_numeric($ItemID) && $config->ebay_api_key) { $options = new JRegistry(); $transport = new JHttpTransportStream($options); // Create a 'stream' transport. $http = new JHttp($options, $transport); $response = $http->get('http://open.api.ebay.com/shopping?callname=GetSingleItem&appid=' . $config->ebay_api_key . '&siteid=' . $config->ebay_language . '&responseencoding=JSON&ItemID=' . $ItemID . '&version=889&trackingid=' . $config->ebay_affiliate_id . '&trackingpartnercode=9'); if ($response->code == '200') { $resp = json_decode($response->body); return $resp; } } return ''; }
public function getExtension() { // Get extension id $cache = JFactory::getCache(); $cache->setCaching(1); $http = new JHttp(); $http->setOption('timeout', 60); $api_url = new JUri(); $input = new JInput(); $id = $input->get('id', null, 'int'); $release = preg_replace('/[^\\d]/', '', base64_decode($input->get('release', '', 'base64'))); $release = intval($release / 5) * 5; $api_url->setScheme('http'); $api_url->setHost('extensions.joomla.org/index.php'); $api_url->setvar('option', 'com_jed'); $api_url->setvar('controller', 'filter'); $api_url->setvar('view', 'extension'); $api_url->setvar('format', 'json'); $api_url->setvar('filter[approved]', '1'); $api_url->setvar('filter[published]', '1'); $api_url->setvar('extend', '0'); $api_url->setvar('filter[id]', $id); $extension_json = $cache->call(array($http, 'get'), $api_url); // Create item $items = json_decode($extension_json->body); $item = $items->data[0]; $this->_catid = $item->core_catid->value; $item->image = $this->getBaseModel()->getMainImageUrl($item); $item->downloadurl = $item->download_integration_url->value; if (preg_match('/\\.xml\\s*$/', $item->downloadurl)) { $app = JFactory::getApplication(); $product = addslashes(base64_decode($app->input->get('product', '', 'base64'))); $release = preg_replace('/[^\\d\\.]/', '', base64_decode($app->input->get('release', '', 'base64'))); $dev_level = (int) base64_decode($app->input->get('dev_level', '', 'base64')); $updatefile = JPATH_ROOT . '/libraries/joomla/updater/update.php'; $fh = fopen($updatefile, 'r'); $theData = fread($fh, filesize($updatefile)); fclose($fh); $theData = str_replace('<?php', '', $theData); $theData = str_replace('$ver->PRODUCT', "'" . $product . "'", $theData); $theData = str_replace('$ver->RELEASE', "'" . $release . "'", $theData); $theData = str_replace('$ver->DEV_LEVEL', "'" . $dev_level . "'", $theData); eval($theData); $update = new JUpdate(); $update->loadFromXML($item->downloadurl); $package_url_node = $update->get('downloadurl', false); if (isset($package_url_node->_data)) { $item->downloadurl = $package_url_node->_data; } } $item->download_type = $this->getTypeEnum($item->download_integration_type->value); return array($item); }
function onAjaxHelix3() { $input = JFactory::getApplication()->input; $action = $input->post->get('action', '', 'STRING'); if ($action == 'upload_image') { $this->upload_image(); return; } else { if ($action == 'remove_image') { $this->remove_image(); return; } } if ($_POST['data']) { $data = json_decode(json_encode($_POST['data']), true); $action = $data['action']; $layoutName = ''; if (isset($data['layoutName'])) { $layoutName = $data['layoutName']; } $template = self::getTemplate()->template; $layoutPath = JPATH_SITE . '/templates/' . $template . '/layout/'; $filepath = $layoutPath . $layoutName; $report = array(); $report['action'] = 'none'; $report['status'] = 'false'; switch ($action) { case 'remove': if (file_exists($filepath)) { unlink($filepath); $report['action'] = 'remove'; $report['status'] = 'true'; } $report['layout'] = JFolder::files($layoutPath, '.json'); break; case 'save': if ($layoutName) { $layoutName = strtolower(str_replace(' ', '-', $layoutName)); } $content = $data['content']; if ($content && $layoutName) { $file = fopen($layoutPath . $layoutName . '.json', 'wb'); fwrite($file, $content); fclose($file); } $report['layout'] = JFolder::files($layoutPath, '.json'); break; case 'load': if (file_exists($filepath)) { $content = file_get_contents($filepath); } if (isset($content) && $content) { echo $layoutHtml = self::loadNewLayout(json_decode($content)); } die; break; case 'resetLayout': if ($layoutName) { echo self::resetMenuLayout($layoutName); } die; break; // Upload Image // Upload Image case 'upload_image': echo "Joomla"; die; break; default: break; case 'voting': if (JSession::checkToken()) { return json_encode($report); } $rate = -1; $pk = 0; if (isset($data['user_rating'])) { $rate = (int) $data['user_rating']; } if (isset($data['id'])) { $id = str_replace('post_vote_', '', $data['id']); $pk = (int) $id; } if ($rate >= 1 && $rate <= 5 && $id > 0) { $userIP = $_SERVER['REMOTE_ADDR']; $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('*')->from($db->quoteName('#__content_rating'))->where($db->quoteName('content_id') . ' = ' . (int) $pk); $db->setQuery($query); try { $rating = $db->loadObject(); } catch (RuntimeException $e) { return json_encode($report); } if (!$rating) { $query = $db->getQuery(true); $query->insert($db->quoteName('#__content_rating'))->columns(array($db->quoteName('content_id'), $db->quoteName('lastip'), $db->quoteName('rating_sum'), $db->quoteName('rating_count')))->values((int) $pk . ', ' . $db->quote($userIP) . ',' . (int) $rate . ', 1'); $db->setQuery($query); try { $db->execute(); $data = self::getItemRating($pk); $rating = $data->rating; $report['action'] = $rating; $report['status'] = 'true'; return json_encode($report); } catch (RuntimeException $e) { return json_encode($report); } } else { if ($userIP != $rating->lastip) { $query = $db->getQuery(true); $query->update($db->quoteName('#__content_rating'))->set($db->quoteName('rating_count') . ' = rating_count + 1')->set($db->quoteName('rating_sum') . ' = rating_sum + ' . (int) $rate)->set($db->quoteName('lastip') . ' = ' . $db->quote($userIP))->where($db->quoteName('content_id') . ' = ' . (int) $pk); $db->setQuery($query); try { $db->execute(); $data = self::getItemRating($pk); $rating = $data->rating; $report['action'] = $rating; $report['status'] = 'true'; return json_encode($report); } catch (RuntimeException $e) { return json_encode($report); } } else { $report['status'] = 'invalid'; return json_encode($report); } } } $report['action'] = 'failed'; $report['status'] = 'false'; return json_encode($report); break; //Font variant //Font variant case 'fontVariants': $template_path = JPATH_SITE . '/templates/' . self::getTemplate()->template . '/webfonts/webfonts.json'; $plugin_path = JPATH_PLUGINS . '/system/helix3/assets/webfonts/webfonts.json'; if (JFile::exists($template_path)) { $json = JFile::read($template_path); } else { $json = JFile::read($plugin_path); } $webfonts = json_decode($json); $items = $webfonts->items; $output = array(); $fontVariants = ''; $fontSubsets = ''; foreach ($items as $item) { if ($item->family == $layoutName) { //Variants foreach ($item->variants as $variant) { $fontVariants .= '<option value="' . $variant . '">' . $variant . '</option>'; } //Subsets foreach ($item->subsets as $subset) { $fontSubsets .= '<option value="' . $subset . '">' . $subset . '</option>'; } } } $output['variants'] = $fontVariants; $output['subsets'] = $fontSubsets; return json_encode($output); break; //Font variant //Font variant case 'updateFonts': jimport('joomla.filesystem.folder'); jimport('joomla.http.http'); $template_path = JPATH_SITE . '/templates/' . self::getTemplate()->template . '/webfonts'; if (!JFolder::exists($template_path)) { JFolder::create($template_path, 0755); } $url = 'https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyBVybAjpiMHzNyEm3ncA_RZ4WETKsLElDg'; $http = new JHttp(); $str = $http->get($url); if (JFile::write($template_path . '/webfonts.json', $str->body)) { echo "<p class='font-update-success'>Google Webfonts list successfully updated! Please refresh your browser.</p>"; } else { echo "<p class='font-update-failed'>Google Webfonts update failed. Please make sure that your template folder is writable.</p>"; } die; break; //Template setting import //Template setting import case 'import': $template_id = filter_var($data['template_id'], FILTER_VALIDATE_INT); if (!$template_id) { die; break; } $settings = $data['settings']; $db = JFactory::getDbo(); $query = $db->getQuery(true); $fields = array($db->quoteName('params') . ' = ' . $db->quote($settings)); $conditions = array($db->quoteName('id') . ' = ' . $db->quote($template_id), $db->quoteName('client_id') . ' = 0'); $query->update($db->quoteName('#__template_styles'))->set($fields)->where($conditions); $db->setQuery($query); $db->execute(); die; break; } return json_encode($report); } }
/** * Get the rate limit for the authenticated user. * * @return \JHttpResponse * * @since 3.0.0 */ public function getRateLimit() { $prepared = $this->prepareRequest('/rate_limit'); return $this->processResponse($this->client->get($prepared['url'], $prepared['headers'])); }
public function getCategories($catid) { if (empty($this->_categories)) { $cache = JFactory::getCache(); $http = new JHttp(); $http->setOption('timeout', 60); $cache->setCaching(1); $categories_json = $cache->call(array($http, 'get'), 'http://extensions.joomla.org/index.php?option=com_jed&view=category&layout=list&format=json&order=order&limit=-1'); $items = json_decode($categories_json->body); $this->_total = count($items); // Properties to be populated $properties = array('id', 'title', 'alias', 'parent'); // Array to collect children categories $children = array(); // Array to collect active categories $active = array($catid); $breadcrumbRefs = array(); // Array to be returned $this->_categories = array(); $this->_children = array(); foreach ($items as $item) { // Skip root category if (trim(strtolower($item->title->value)) === 'root') { continue; } $id = (int) $item->id->value; $parentId = (int) $item->parent_id->value; if ((int) $item->level->value > 1) { // Ignore subitems without a parent. if (is_null($item->parent_id->value)) { continue; } // It is a child, so let's store as a child of it's parent if (!array_key_exists($parentId, $this->_categories)) { $this->_categories[$parentId] = new stdClass(); } $parent =& $this->_categories[$parentId]; if (!isset($parent->children)) { $parent->children = array(); } if (!isset($parent->children[$id])) { $parent->children[$id] = new stdClass(); } $category =& $parent->children[$id]; // Populate category with values $category->id = $id; $category->active = $catid == $category->id; $category->selected = $category->active; $category->name = $item->title->value; $category->alias = $item->alias->value; $category->parent = (int) $parentId; $category->description = ''; $category->children = array(); $this->_children[] = $category; if ($category->active) { $this->_categories[$parentId]->active = true; if (!array_key_exists($parentId, $breadcrumbRefs)) { $breadcrumbRefs[$parentId] =& $this->_categories[$parentId]; } $breadcrumbRefs[$id] =& $category; } } else { // It is parent, so let's add it to the parent array if (!array_key_exists($id, $this->_categories)) { $this->_categories[$id] = new stdClass(); $this->_categories[$id]->children = array(); } $category =& $this->_categories[$id]; $category->id = $id; if (!isset($category->active)) { $category->active = $catid == $category->id; } $category->selected = $category->active; $category->name = $item->title->value; $category->alias = $item->alias->value; $category->parent = (int) $parentId; $category->description = ''; if ($category->active) { $breadcrumbRefs[$id] =& $category; } } } if (!empty($catid)) { $this->_breadcrumbs = $breadcrumbRefs; } } // Add the Home item $input = new JInput(); $view = $input->get('view', null); $home = new stdClass(); $home->active = $view == 'dashboard' ? true : false; $home->id = 0; $home->name = JText::_('COM_APPS_HOME'); $home->alias = 'home'; $home->description = JText::_('COM_APPS_EXTENSIONS_DASHBOARD'); $home->parent = 0; $home->selected = $view == 'dashboard' ? true : false; $home->children = array(); array_unshift($this->_categories, $home); return $this->_categories; }
/** * Query from eBay API the JSON stream of item id given to render * * @param int $ItemID The eBay ID of object to query * * @return string */ public static function getEbayItem($ItemID) { $config = KunenaFactory::getConfig(); if (is_numeric($ItemID) && $config->ebay_api_key) { $options = new JRegistry(); $transport = new JHttpTransportStream($options); // Create a 'stream' transport. $http = new JHttp($options, $transport); $response = $http->get('http://open.api.ebay.com/shopping?callname=GetSingleItem&appid=' . $config->ebay_api_key . '&siteid=' . $config->ebay_language . '&responseencoding=JSON&ItemID=' . $ItemID . '&version=889&trackingid=' . $config->ebay_affiliate_id . '&trackingpartnercode=9'); if ($response->code == '200') { $resp = json_decode($response->body); if ($resp->Ack == 'Success') { $ebay_object = '<div style="border: 1px solid #e5e5e5;margin:10px;padding:10px;border-radius:5px">'; $ebay_object .= '<img src="https://securepics.ebaystatic.com/api/ebay_market_108x45.gif" />'; $ebay_object .= '<div style="margin:10px 0" /></div>'; $ebay_object .= '<div style="text-align: center;"><a href="' . $resp->Item->ViewItemURLForNaturalSearch . '"> <img src="' . $resp->Item->PictureURL[0] . '" /></a></div>'; $ebay_object .= '<div style="margin:10px 0" /></div>'; $ebay_object .= '<a href="' . $resp->Item->ViewItemURLForNaturalSearch . '">' . $resp->Item->Title . '</a>'; $ebay_object .= '<div style="margin:10px 0" /></div>'; $ebay_object .= $resp->Item->ConvertedCurrentPrice->CurrencyID . ' ' . $resp->Item->ConvertedCurrentPrice->Value; $ebay_object .= '<div style="margin:10px 0" /></div>'; if ($resp->Item->ListingStatus == "Active") { $ebay_object .= '<a class="btn" href="' . $resp->Item->ViewItemURLForNaturalSearch . '">' . JText::_('COM_KUNENA_LIB_BBCODE_EBAY_LABEL_BUY_IT_NOW') . '</a>'; } else { $ebay_object .= JText::_('COM_KUNENA_LIB_BBCODE_EBAY_LABEL_COMPLETED'); } $ebay_object .= '</div>'; return $ebay_object; } else { return '<b>' . JText::_('COM_KUNENA_LIB_BBCODE_EBAY_ERROR_WRONG_ITEM_ID') . '</b>'; } } } else { if (KunenaFactory::getUser()->isAdmin()) { return '<b>' . JText::_('COM_KUNENA_LIB_BBCODE_EBAY_INVALID_APPID_KEY') . '</<b>'; } } return ''; }
/** * Get a list of images to migrate * * @return step object */ public function getImage() { // Initialize jupgrade class $jupgrade = new jUpgrade(); // JHttp instance jimport('joomla.http.http'); $http = new JHttp(); $data = $jupgrade->getRestData(); // Getting the total $data['task'] = "image"; $data['files'] = 'images'; $response = $http->get($jupgrade->params->get('rest_hostname'), $data); $id = $this->_getID('files_images'); $id = $id + 1; $name = $this->_getImageName($id); $write = JFile::write(JPATH_ROOT . '/images.new/' . $name, $response->body); $this->_updateID($id, 'files_images'); }
/** * Get the last id from RESTful * * @access public * @return int The last id */ public function getLastIdRest() { jimport('joomla.http.http'); // JHttp instance $http = new JHttp(); $data = $this->getRestData(); // Getting the total $data['task'] = "lastid"; $data['table'] = $this->_step['name']; $lastid = $http->get($this->params->get('rest_hostname'), $data); return (int) $lastid->body; }
/** * Get a single row * * @return step object */ public function requestRest($task = 'total', $table = false) { // Initialize jupgrade class $jupgrade = new jUpgrade(); // JHttp instance jimport('joomla.http.http'); $http = new JHttp(); $data = $jupgrade->getRestData(); // Getting the total $data['task'] = $task; $data['table'] = $table; $request = $http->get($jupgrade->params->get('rest_hostname'), $data); return $request->body; }
public static function isValidUrl($url) { JFactory::getApplication()->enqueueMessage('isValidUrl:' . $url); $http = new JHttp(); $h = $http->head($url); //var_dump($h); return 1; if (function_exists('curl_init')) { JFactory::getApplication()->enqueueMessage('curl_init ok'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'self::curlHeaderCallback'); curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_exec($ch); $intReturnCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); var_dump($intReturnCode); //$intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE); //if ($intReturnCode != 200 && $intReturnCode != 302 && $intReturnCode != 304) { return 0; } else return 1; } else { JFactory::getApplication()->enqueueMessage('curl_init ko'); } return 1; }
/** * Combine files and set compress header for combined file. * * Below is an example of <b>$files</b> parameter to minify some stylesheets: * * <pre>array( * 'screen' => array('screen1.css', 'screen2.css'), * 'print' => array('print1.css', 'print2.css') * )</pre> * * And the return value after execution this method is: * * <pre>array( * 'screen' => 'absolute/path/to/combined/file', * 'print' => 'absolute/path/to/combined/file' * )</pre> * * For combine Javascript files, the <b>$files</b> parameter look like below: * * <pre>array( * 0 => array('script1.js', 'script2.js', 'script3.js', 'script4.js') * )</pre> * * @param string $path Absolute path to the directory for storing minified file. * @param string $type Either 'css' or 'js'. * @param array $list Array of files to combine. * @param boolean $isContent Set to true if $files contains file content instead of file path. * * @return array */ protected static function process($path, $type, $list, $isContent = false) { // Combine file content foreach ($list as $media => $files) { foreach ($files as $file) { isset($minified[$media]) or $minified[$media] = ''; if ($isContent) { $tmp = $file; } else { // Read file content if (substr($file, 0, 1) == '/') { // Get absolute file path $file = str_replace(JURI::root(true), JPATH_ROOT, $file); if (!($tmp = JFile::read($file))) { // Convert to full file URI $file = JURI::root() . $file; } } // If remote file, get its content via HTTP client if (substr($file, 0, 5) == 'http:' or substr($file, 0, 6) == 'https:') { $http = new JHttp(); $tmp = $http->get($file); if (!empty($tmp->body)) { $tmp = $tmp->body; } } } $minified[$media] .= "\n{$tmp}"; } } // Save combined file foreach ($list as $media => $files) { // Generate minification file path $minifiedFile = $path . DS . $type . '_' . md5(json_encode($files)) . '.php'; // Add header to compress asset file $minified[$media] = '<?php // Initialize ob_gzhandler function to send and compress data ob_start("ob_gzhandler"); // Send the requisite header information and character set header("content-type: ' . ($type == 'js' ? 'text/javascript' : 'text/css') . '; charset: UTF-8"); // Check cached credentials and reprocess accordingly header("cache-control: must-revalidate"); // Set variable for duration of cached content $offset = 365 * 60 * 60; // Set variable specifying format of expiration header $expire = "expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT"; // Send cache expiration header to the client broswer header($expire); ?> ' . self::cleanCode($minified[$media], $type); // Write minification file JFile::write($minifiedFile, $minified[$media]); // Store path to minification file $minified[$media] = $minifiedFile; } return $minified; }