Example #1
0
 /**
  * Send a request to the server and return a JHttpResponse object with the response.
  *
  * @param   RokUpdater_Uri $uri        The URI to the resource to request.
  * @param   string         $data       Either an associative array or a string to be sent with the request.
  * @param   array          $headers    An array of request headers to send with the request.
  * @param   integer        $timeout    Read timeout in seconds.
  * @param   string         $userAgent  The optional user agent string to send with the request.
  *
  * @throws ProtocolBuffers_Exception
  * @return  string
  */
 protected function transportRequest(RokUpdater_Uri $uri, $data = null, array $headers = array(), $timeout = null, $userAgent = null)
 {
     // Create the stream context options array with the required method offset.
     $options = array('method' => strtoupper('POST'));
     // If data exists let's encode it and make sure our Content-type header is set.
     if (isset($data)) {
         $options['content'] = 'message=' . urlencode($data);
         JLog::add(sprintf('%s sending body %s', get_class($this), $options['content']), JLog::DEBUG, 'rokupdater');
         if (!isset($headers['Content-type'])) {
             $headers['Content-type'] = 'application/x-www-form-urlencoded';
         }
         $headers['Content-length'] = strlen($options['content']);
     }
     // Build the headers string for the request.
     $headerString = null;
     if (isset($headers)) {
         foreach ($headers as $key => $value) {
             $headerString .= $key . ': ' . $value . "\r\n";
         }
         // Add the headers string into the stream context options array.
         $options['header'] = trim($headerString, "\r\n");
     }
     // If an explicit timeout is given user it.
     if (isset($timeout)) {
         $options['timeout'] = (int) $timeout;
     }
     // If an explicit user agent is given use it.
     if (isset($userAgent)) {
         $options['user_agent'] = $userAgent;
     }
     // Ignore HTTP errors so that we can capture them.
     $options['ignore_errors'] = 1;
     // Create the stream context for the request.
     $context = stream_context_create(array('http' => $options));
     if ($uri->getScheme() == self::HTTPS_SCHEME) {
         $cacert_path = dirname(__FILE__) . '/cacert.pem';
         JLog::add(sprintf('%s : setting ssl:cacert option to %s', get_class($this), $cacert_path), JLog::INFO, 'rokupdater');
         stream_context_set_option($context, 'ssl', 'cafile', $cacert_path);
         stream_context_set_option($context, 'ssl', 'verify_peer', true);
     }
     if (array_key_exists('streamsocket.options', $this->options) && is_array($this->options['streamsocket.options'])) {
         foreach ($this->options['streamsocket.options'] as $wrapper => $settings) {
             foreach ($settings as $setting_name => $setting_value) {
                 JLog::add(sprintf('%s : Stream socket override option set %s:%s:%s.', get_class($this), $wrapper, $setting_name, $setting_value), JLog::INFO, 'rokupdater');
                 stream_context_set_option($context, $wrapper, $setting_name, $setting_value);
             }
         }
     }
     // Open the stream for reading.
     $stream = fopen($uri->getAbsoluteUri(), 'r', false, $context);
     // Get the contents from the stream.
     $content = stream_get_contents($stream);
     JLog::add(sprintf('%s : Response is : %s', get_class($this), $content), JLog::DEBUG, 'rokupdater');
     // Close the stream.
     fclose($stream);
     return $content;
 }
Example #2
0
 /**
  * Send a request to the server and return a JHttpResponse object with the response.
  *
  * @param   RokUpdater_Uri $uri        The URI to the resource to request.
  * @param   string         $data       Either an associative array or a string to be sent with the request.
  * @param   array          $headers    An array of request headers to send with the request.
  * @param   integer        $timeout    Read timeout in seconds.
  * @param   string         $userAgent  The optional user agent string to send with the request.
  *
  * @throws ProtocolBuffers_Exception
  * @throws Exception
  * @return  string
  */
 protected function transportRequest(RokUpdater_Uri $uri, $data = null, array $headers = array(), $timeout = null, $userAgent = null)
 {
     // Setup the cURL handle.
     $ch = curl_init();
     // Initialize the certificate store
     $options[CURLOPT_CAINFO] = array_key_exists('curl.certpath', $this->options) ? $this->options['curl.certpath'] : dirname(__FILE__);
     $options[CURLOPT_CAINFO] .= '/cacert.pem';
     // Build the headers string for the request.
     $headerArray = array();
     if (isset($headers)) {
         foreach ($headers as $key => $value) {
             $headerArray[] = $key . ': ' . $value;
         }
         // Add the headers string into the stream context options array.
         $options[CURLOPT_HTTPHEADER] = $headerArray;
     }
     $options[CURLOPT_URL] = $uri->getAbsoluteUri();
     $options[CURLOPT_POST] = true;
     $options[CURLOPT_POSTFIELDS] = 'message=' . urlencode($data);
     JLog::add(sprintf('%s post body is %s', get_class($this), $options[CURLOPT_POSTFIELDS]), JLog::DEBUG, 'rokupdater');
     // If an explicit timeout is given user it.
     if (isset($timeout)) {
         $options[CURLOPT_TIMEOUT] = (int) $timeout;
         $options[CURLOPT_CONNECTTIMEOUT] = (int) $timeout;
     }
     // If an explicit user agent is given use it.
     if (isset($userAgent)) {
         $headers[CURLOPT_USERAGENT] = $userAgent;
     }
     // Return it... echoing it would be tacky.
     $options[CURLOPT_RETURNTRANSFER] = true;
     // Override the Expect header to prevent cURL from confusing itself in its own stupidity.
     // Link: http://the-stickman.com/web-development/php-and-curl-disabling-100-continue-header/
     $options[CURLOPT_HTTPHEADER][] = 'Expect:';
     // Follow redirects.
     $options[CURLOPT_FOLLOWLOCATION] = array_key_exists('follow_location', $this->options) ? (bool) $this->options['follow_location'] : true;
     if (array_key_exists('curl.options', $this->options) && is_array($this->options['curl.options'])) {
         foreach ($this->options['curl.options'] as $key => $value) {
             JLog::add(sprintf('%s setting overriden cURL option %s to  %s', get_class($this), $key, $value, $options[CURLOPT_POSTFIELDS]), JLog::INFO, 'rokupdater');
             $options[$key] = $value;
         }
     }
     // Set the cURL options.
     curl_setopt_array($ch, $options);
     // Execute the request and close the connection.
     $content = curl_exec($ch);
     JLog::add(sprintf('%s : Response is : %s', get_class($this), $content), JLog::DEBUG, 'rokupdater');
     if ($content === false) {
         JLog::add(sprintf('%s : request failed.', get_class($this), $options[CURLOPT_POSTFIELDS]), JLog::INFO, 'rokupdater');
         throw new Exception(curl_error($ch));
     }
     // Close the connection.
     curl_close($ch);
     return $content;
 }
 /**
  * @param $token
  *
  * @throws RokUpdater_Exception
  */
 public function updateAccessToken($site_id, $token = null)
 {
     // get the RT update items
     $db = JFactory::getDbo();
     $query = $db->getQuery(true);
     $query->select('update_site_id, location')->from('#__update_sites');
     $query->where('location like ' . $query->quote($this->container->updaters_server_regex_pattern));
     $db->setQuery($query);
     try {
         $update_items = $db->loadAssocList('update_site_id');
         if ($db->getErrorNum()) {
             throw new RokUpdater_Exception(sprintf('Database error - %s', $db->getErrorMsg(true)));
         }
     } catch (Exception $e) {
         throw new RokUpdater_Exception(sprintf('Database error - %s', $e->getMessage()));
     }
     $jversion = new JVersion();
     // Append the access token to any RT update URL
     foreach ($update_items as $id => $row_info) {
         $uri = new RokUpdater_Uri(trim($row_info['location']));
         $uri->addQueryParam(self::SITE_ID_QUERY_KEY, $site_id);
         if (null !== $token) {
             $uri->addQueryParam(self::ACCESS_TOKEN_QUERY_KEY, $token);
             $uri->removeQueryParam(self::IGNORED_QUERY_KEY);
         } else {
             $uri->removeQueryParam(self::ACCESS_TOKEN_QUERY_KEY);
             $uri->removeQueryParam(self::IGNORED_QUERY_KEY);
         }
         $location = $uri->getAbsoluteUri();
         $location .= !count($uri->getQueryParams()) ? '?' : '&';
         $location .= self::IGNORED_QUERY_KEY . '=update.xml';
         $update_query = $db->getQuery(true);
         $update_query->update('#__update_sites')->set(sprintf('location = %s', $update_query->quote($location)));
         $update_query->where(sprintf('update_site_id = %d', (int) $id));
         $db->setQuery($update_query);
         try {
             if (method_exists($db, 'execute') && !$db->execute() || method_exists($db, 'query') && !$db->query()) {
                 throw new RokUpdater_Exception(sprintf('Database error - %s', $db->getErrorMsg(true)));
             }
         } catch (Exception $e) {
             throw new RokUpdater_Exception(sprintf('Database error - %s', $e->getMessage()));
         }
     }
 }
Example #4
0
 /**
  * wrapper to send a request to the server and return a string with the response body.
  *
  * @param   RokUpdater_Uri $uri        The URI to the resource to request.
  * @param   string         $data       Either an associative array or a string to be sent with the request.
  * @param   array          $headers    An array of request headers to send with the request.
  * @param   integer        $timeout    Read timeout in seconds.
  * @param   string         $userAgent  The optional user agent string to send with the request.
  *
  * @throws ProtocolBuffers_Exception
  * @throws Exception
  * @return string
  */
 public function request(RokUpdater_Uri $uri, $data = null, array $headers = array(), $timeout = null, $userAgent = null)
 {
     JLog::add(sprintf('%s request called for %s', get_class($this), $uri->getAbsoluteUri()), JLog::DEBUG, 'rokupdater');
     JLog::add(sprintf('%s request data passed %s', get_class($this), $data), JLog::DEBUG, 'rokupdater');
     if ($uri->getScheme() == self::HTTPS_SCHEME && !$this->isSSLSupported() && array_key_exists('http_fallback', $this->options)) {
         JLog::add(sprintf('%s : SSL is not supported in cURL and fallback is set', get_class($this)), JLog::DEBUG, 'rokupdater');
         if ($this->options['http_fallback']) {
             $uri->setScheme(self::HTTP_SCHEME);
             if ((int) $uri->getPort() == self::HTTPS_PORT) {
                 $uri->setPort(self::HTTP_PORT);
             }
         } else {
             JLog::add('SSL is not supported in cURL and fallback not set', JLog::INFO, 'rokupdater');
             throw new ProtocolBuffers_Exception(sprintf('%s Transport implmentation does not support SSL', get_class($this)), ProtocolBuffers_TransportFactory::PROTOCOL_BUFFERS_ERROR_SSL_STREAM_NOT_REGISTERED);
         }
     }
     JLog::add(sprintf('%s sending request to %s', get_class($this), $uri->getAbsoluteUri()), JLog::INFO, 'rokupdater');
     return $this->transportRequest($uri, $data, $headers, $timeout, $userAgent);
 }
Example #5
0
 /**
  * @param     $path
  * @param int $type
  *
  * @return mixed|string
  */
 public function getUrlForPath($path, $type = self::RELATIVE_URL)
 {
     if (is_string($path)) {
         $uri = new RokUpdater_Uri($path);
     } else {
         if ($path instanceof RokUpdater_Uri) {
             $uri = $path;
         } else {
             return false;
         }
     }
     // if its external  just return the external url
     if ($this->isExternal($uri)) {
         return $path;
     }
     $clean_uri_path = preg_match('/^WIN/', PHP_OS) && preg_match('/^[a-zA-Z]:/', $uri->getPath()) ? '' : '/';
     $clean_uri_path .= self::cleanFilesystemPath($uri->getPath());
     $clean_site_uri_path = preg_match('/^WIN/', PHP_OS) && preg_match('/^[a-zA-Z]:/', $this->site_uri->getPath()) ? '' : '/';
     $clean_site_uri_path .= self::cleanFilesystemPath($this->site_uri->getPath());
     if (!@file_exists($clean_uri_path)) {
         return $clean_uri_path;
     }
     $return_uri = clone $this->site_uri;
     // check if the path seems to be in the instances  or  server path
     // leave it as is if not one of the two
     if (strpos($clean_uri_path, $this->site_root_path) === 0) {
         // its an instance path
         $return_uri->appendPath(str_replace($this->site_root_path, '', $clean_uri_path));
     } elseif (!is_null($this->server_root_path) && strpos($clean_uri_path, $this->server_root_path) === 0) {
         // its a server path
         $return_uri->setPath(str_replace($this->server_root_path, '', $clean_uri_path));
     } else {
         if (is_null($this->server_root_path) && !isset($_SERVER['DOCUMENT_ROOT'])) {
             trigger_error('No $_SERVER[\'DOCUMENT_ROOT\'] value is set.  Unable to find path to map to URL. Assuming root.', E_USER_NOTICE);
             $return_uri = $uri;
         } else {
             $return_uri = $uri;
         }
     }
     return $return_uri->getComponents($type);
 }
Example #6
0
 /**
  * @param  RokUpdater_Uri   $uri
  * @param  array $components
  * @param  bool  $esc
  *
  * @return string
  */
 private static function getRelativeComponents(RokUpdater_Uri $uri, $components, $esc)
 {
     $result = '';
     if ($components & RokUpdater_Uri_Components::PATH) {
         $cmp = $uri->getPath();
         $result .= '/';
         if ($esc) {
             foreach (explode('/', $cmp) as $key => $value) {
                 $result .= ($key === 0 ? '' : '/') . rawurlencode($value);
             }
         } else {
             $result .= $cmp;
         }
     }
     if ($components & RokUpdater_Uri_Components::QUERY) {
         $cmp = $uri->getQuery();
         if (!empty($cmp)) {
             if ($esc) {
                 parse_str($cmp, $cmp);
                 $result .= '?' . str_replace('+', '%20', http_build_query($cmp, null, '&'));
             } else {
                 $result .= "?{$cmp}";
             }
         }
     }
     //FRAGMENT:
     if ($components & RokUpdater_Uri_Components::FRAGMENT) {
         $cmp = $uri->getFragment();
         if (!empty($cmp)) {
             if ($esc) {
                 $result .= '#' . rawurlencode($cmp);
             } else {
                 $result .= "#{$cmp}";
             }
         }
     }
     //		RESULT:
     return $result;
 }