From c58dc3813bed42f650bd23eb995769db4c77b1cf Mon Sep 17 00:00:00 2001
From: Jaime Perez Crespo <jaime.perez@uninett.no>
Date: Tue, 21 Apr 2015 14:43:46 +0200
Subject: [PATCH] Move SimpleSAML_Utilities::fetch() to
 SimpleSAML\Utils\HTTP::fetch() and deprecate the former.

---
 bin/translation.php                           |  4 +-
 lib/SimpleSAML/Bindings/Shib13/Artifact.php   |  2 +-
 .../Metadata/MetaDataStorageHandlerMDX.php    |  2 +-
 lib/SimpleSAML/Metadata/SAMLParser.php        |  4 +-
 lib/SimpleSAML/Utilities.php                  | 81 +----------------
 lib/SimpleSAML/Utils/HTTP.php                 | 90 +++++++++++++++++++
 .../lib/Auth/Source/LiveID.php                |  6 +-
 modules/cas/lib/Auth/Source/CAS.php           |  4 +-
 modules/casserver/www/serviceValidate.php     |  2 +-
 modules/metarefresh/lib/MetaLoader.php        |  2 +-
 10 files changed, 105 insertions(+), 92 deletions(-)

diff --git a/bin/translation.php b/bin/translation.php
index 479e62737..f5bf452ba 100755
--- a/bin/translation.php
+++ b/bin/translation.php
@@ -40,14 +40,14 @@ echo 'File base: [' . $basefile . ']'. "\n";
 switch($action) {
 	case 'pulldef':
 		
-		$content = SimpleSAML_Utilities::fetch($base . 'export.php?aid=' . $application . '&type=def&file=' . $basefile);
+		$content = \SimpleSAML\Utils\HTTP::fetch($base . 'export.php?aid=' . $application . '&type=def&file=' . $basefile);
 		file_put_contents($fileWithoutExt . '.definition.json' , $content);
 		break;
 		
 	case 'pull':
 
 		try {
-			$content = SimpleSAML_Utilities::fetch($base . 'export.php?aid=' . $application . '&type=translation&file=' . $basefile);
+			$content = \SimpleSAML\Utils\HTTP::fetch($base . 'export.php?aid=' . $application . '&type=translation&file=' . $basefile);
 			file_put_contents($fileWithoutExt . '.translation.json' , $content);
 		}
 		catch (SimpleSAML_Error_Exception $e) {
diff --git a/lib/SimpleSAML/Bindings/Shib13/Artifact.php b/lib/SimpleSAML/Bindings/Shib13/Artifact.php
index 5f5ce01f5..4a8079e29 100644
--- a/lib/SimpleSAML/Bindings/Shib13/Artifact.php
+++ b/lib/SimpleSAML/Bindings/Shib13/Artifact.php
@@ -161,7 +161,7 @@ class SimpleSAML_Bindings_Shib13_Artifact {
 		);
 
 		/* Fetch the artifact. */
-		$response = SimpleSAML_Utilities::fetch($url, $opts);
+		$response = \SimpleSAML\Utils\HTTP::fetch($url, $opts);
 		if ($response === FALSE) {
 			throw new SimpleSAML_Error_Exception('Failed to retrieve assertion from IdP.');
 		}
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerMDX.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerMDX.php
index bf4058475..7f61a62d8 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerMDX.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerMDX.php
@@ -253,7 +253,7 @@ class SimpleSAML_Metadata_MetaDataStorageHandlerMDX extends SimpleSAML_Metadata_
 
 		SimpleSAML_Logger::debug('MetaData - Handler.MDX: Downloading metadata for "'. $index .'" from [' . $mdx_url . ']' );
 		try {
-			$xmldata = SimpleSAML_Utilities::fetch($mdx_url);
+			$xmldata = \SimpleSAML\Utils\HTTP::fetch($mdx_url);
 		} catch(Exception $e) {
 			SimpleSAML_Logger::warning('Fetching metadata for ' . $index . ': ' . $e->getMessage());
 		}
diff --git a/lib/SimpleSAML/Metadata/SAMLParser.php b/lib/SimpleSAML/Metadata/SAMLParser.php
index 3b9be1191..7c36dfddd 100644
--- a/lib/SimpleSAML/Metadata/SAMLParser.php
+++ b/lib/SimpleSAML/Metadata/SAMLParser.php
@@ -178,7 +178,7 @@ class SimpleSAML_Metadata_SAMLParser {
 	public static function parseFile($file) {
 		$doc = new DOMDocument();
 
-		$data = SimpleSAML_Utilities::fetch($file);
+		$data = \SimpleSAML\Utils\HTTP::fetch($file);
 
 		$res = $doc->loadXML($data);
 		if($res !== TRUE) {
@@ -248,7 +248,7 @@ class SimpleSAML_Metadata_SAMLParser {
 
 		if ($file === NULL) throw new Exception('Cannot open file NULL. File name not specified.');
 
-		$data = SimpleSAML_Utilities::fetch($file);
+		$data = \SimpleSAML\Utils\HTTP::fetch($file);
 
 		$doc = new DOMDocument();
 		$res = $doc->loadXML($data);
diff --git a/lib/SimpleSAML/Utilities.php b/lib/SimpleSAML/Utilities.php
index 021a6e7c3..303b5777c 100644
--- a/lib/SimpleSAML/Utilities.php
+++ b/lib/SimpleSAML/Utilities.php
@@ -1078,87 +1078,10 @@ class SimpleSAML_Utilities {
 
 
 	/**
-	 * Helper function to retrieve a file or URL with proxy support.
-	 *
-	 * An exception will be thrown if we are unable to retrieve the data.
-	 *
-	 * @param string $path  The path or URL we should fetch.
-	 * @param array $context  Extra context options. This parameter is optional.
-	 * @param boolean $getHeaders Whether to also return response headers. Optional.
-	 * @return mixed array if $getHeaders is set, string otherwise
+	 * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::fetch() instead.
 	 */
 	public static function fetch($path, $context = array(), $getHeaders = FALSE) {
-		assert('is_string($path)');
-
-		$config = SimpleSAML_Configuration::getInstance();
-
-		$proxy = $config->getString('proxy', NULL);
-		if ($proxy !== NULL) {
-			if (!isset($context['http']['proxy'])) {
-				$context['http']['proxy'] = $proxy;
-			}
-			if (!isset($context['http']['request_fulluri'])) {
-				$context['http']['request_fulluri'] = TRUE;
-			}
-			// If the remote endpoint over HTTPS uses the SNI extension
-			// (Server Name Indication RFC 4366), the proxy could
-			// introduce a mismatch between the names in the
-			// Host: HTTP header and the SNI_server_name in TLS
-			// negotiation (thanks to Cristiano Valli @ GARR-IDEM
-			// to have pointed this problem).
-			// See: https://bugs.php.net/bug.php?id=63519
-			// These controls will force the same value for both fields.
-			// Marco Ferrante (marco@csita.unige.it), Nov 2012
-			if (preg_match('#^https#i', $path)
-				&& defined('OPENSSL_TLSEXT_SERVER_NAME')
-				&& OPENSSL_TLSEXT_SERVER_NAME) {
-				// Extract the hostname
-				$hostname = parse_url($path, PHP_URL_HOST);
-				if (!empty($hostname)) {
-					$context['ssl'] = array(
-						'SNI_server_name' => $hostname,
-						'SNI_enabled' => TRUE,
-						);
-				}
-				else {
-					SimpleSAML_Logger::warning('Invalid URL format or local URL used through a proxy');
-				}
-			}
-		}
-
-		$context = stream_context_create($context);
-
-		$data = file_get_contents($path, FALSE, $context);
-		if ($data === FALSE) {
-			$error = error_get_last();
-			throw new SimpleSAML_Error_Exception('Error fetching ' . var_export($path, TRUE) . ':' . $error['message']);
-		}
-
-		// Data and headers.
-		if ($getHeaders) {
-
-			if (isset($http_response_header)) {
-				$headers = array();
-				foreach($http_response_header as $h) {
-					if(preg_match('@^HTTP/1\.[01]\s+\d{3}\s+@', $h)) {
-						$headers = array(); // reset
-						$headers[0] = $h;
-						continue;
-					}
-					$bits = explode(':', $h, 2);
-					if(count($bits) === 2) {
-						$headers[strtolower($bits[0])] = trim($bits[1]);
-					}
-				}
-			} else {
-				/* No HTTP headers - probably a different protocol, e.g. file. */
-				$headers = NULL;
-			}
-
-			return array($data, $headers);
-		}
-
-		return $data;
+		return \SimpleSAML\Utils\HTTP::fetch($path, $context, $getHeaders);
 	}
 
 
diff --git a/lib/SimpleSAML/Utils/HTTP.php b/lib/SimpleSAML/Utils/HTTP.php
index b2a774645..56e5ebe4f 100644
--- a/lib/SimpleSAML/Utils/HTTP.php
+++ b/lib/SimpleSAML/Utils/HTTP.php
@@ -207,6 +207,96 @@ class HTTP
     }
 
 
+    /**
+     * Helper function to retrieve a file or URL with proxy support.
+     *
+     * An exception will be thrown if we are unable to retrieve the data.
+     *
+     * @param string  $url The path or URL we should fetch.
+     * @param array   $context Extra context options. This parameter is optional.
+     * @param boolean $getHeaders Whether to also return response headers. Optional.
+     *
+     * @return mixed array if $getHeaders is set, string otherwise
+     * @throws \SimpleSAML_Error_Exception If the input parameters are invalid or the file or URL cannot be retrieved.
+     *
+     * @author Andjelko Horvat
+     * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+     * @author Marco Ferrante, University of Genova <marco@csita.unige.it>
+     */
+    public static function fetch($url, $context = array(), $getHeaders = false)
+    {
+        if (!is_string($url)) {
+            throw new \SimpleSAML_Error_Exception('Invalid input parameters.');
+        }
+
+        $config = \SimpleSAML_Configuration::getInstance();
+
+        $proxy = $config->getString('proxy', null);
+        if ($proxy !== null) {
+            if (!isset($context['http']['proxy'])) {
+                $context['http']['proxy'] = $proxy;
+            }
+            if (!isset($context['http']['request_fulluri'])) {
+                $context['http']['request_fulluri'] = true;
+            }
+            /*
+             * If the remote endpoint over HTTPS uses the SNI extension (Server Name Indication RFC 4366), the proxy
+             * could introduce a mismatch between the names in the Host: HTTP header and the SNI_server_name in TLS
+             * negotiation (thanks to Cristiano Valli @ GARR-IDEM to have pointed this problem).
+             * See: https://bugs.php.net/bug.php?id=63519
+             * These controls will force the same value for both fields.
+             * Marco Ferrante (marco@csita.unige.it), Nov 2012
+             */
+            if (preg_match('#^https#i', $url)
+                && defined('OPENSSL_TLSEXT_SERVER_NAME')
+                && OPENSSL_TLSEXT_SERVER_NAME
+            ) {
+                // extract the hostname
+                $hostname = parse_url($url, PHP_URL_HOST);
+                if (!empty($hostname)) {
+                    $context['ssl'] = array(
+                        'SNI_server_name' => $hostname,
+                        'SNI_enabled'     => true,
+                    );
+                } else {
+                    \SimpleSAML_Logger::warning('Invalid URL format or local URL used through a proxy');
+                }
+            }
+        }
+
+        $context = stream_context_create($context);
+        $data = file_get_contents($url, false, $context);
+        if ($data === false) {
+            $error = error_get_last();
+            throw new \SimpleSAML_Error_Exception('Error fetching '.var_export($url, true).':'.$error['message']);
+        }
+
+        // data and headers.
+        if ($getHeaders) {
+            if (isset($http_response_header)) {
+                $headers = array();
+                foreach ($http_response_header as $h) {
+                    if (preg_match('@^HTTP/1\.[01]\s+\d{3}\s+@', $h)) {
+                        $headers = array(); // reset
+                        $headers[0] = $h;
+                        continue;
+                    }
+                    $bits = explode(':', $h, 2);
+                    if (count($bits) === 2) {
+                        $headers[strtolower($bits[0])] = trim($bits[1]);
+                    }
+                }
+            } else {
+                // no HTTP headers, probably a different protocol, e.g. file
+                $headers = null;
+            }
+            return array($data, $headers);
+        }
+
+        return $data;
+    }
+
+
     /**
      * This function parses the Accept-Language HTTP header and returns an associative array with each language and the
      * score for that language. If a language includes a region, then the result will include both the language with
diff --git a/modules/authwindowslive/lib/Auth/Source/LiveID.php b/modules/authwindowslive/lib/Auth/Source/LiveID.php
index a54061e08..47b41ba19 100644
--- a/modules/authwindowslive/lib/Auth/Source/LiveID.php
+++ b/modules/authwindowslive/lib/Auth/Source/LiveID.php
@@ -96,7 +96,7 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends SimpleSAML_Auth_Source {
 			),
 		);
 
-		$result = SimpleSAML_Utilities::fetch('https://consent.live.com/AccessToken.aspx', $context);
+		$result = \SimpleSAML\Utils\HTTP::fetch('https://consent.live.com/AccessToken.aspx', $context);
 
 		parse_str($result, $response);
 
@@ -111,8 +111,8 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends SimpleSAML_Auth_Source {
 		// Documentation at: http://msdn.microsoft.com/en-us/library/ff751708.aspx
 		$opts = array('http' => array('header' => "Accept: application/json\r\nAuthorization: WRAP access_token=" .
 						$response['wrap_access_token'] . "\r\n"));
-		$data = SimpleSAML_Utilities::fetch('https://apis.live.net/V4.1/cid-'. $response['uid'] . '/Profiles',$opts);
-                $userdata = json_decode($data, TRUE);
+		$data = \SimpleSAML\Utils\HTTP::fetch('https://apis.live.net/V4.1/cid-'. $response['uid'] . '/Profiles',$opts);
+		$userdata = json_decode($data, TRUE);
 
 		$attributes = array();
 		$attributes['windowslive_uid'] = array($response['uid']);
diff --git a/modules/cas/lib/Auth/Source/CAS.php b/modules/cas/lib/Auth/Source/CAS.php
index 81ae59e28..073eba615 100644
--- a/modules/cas/lib/Auth/Source/CAS.php
+++ b/modules/cas/lib/Auth/Source/CAS.php
@@ -93,7 +93,7 @@ class sspmod_cas_Auth_Source_CAS  extends SimpleSAML_Auth_Source  {
 				'ticket' => $ticket,
 				'service' => $service,
 		));
-		$result = SimpleSAML_Utilities::fetch($url);
+		$result = \SimpleSAML\Utils\HTTP::fetch($url);
 		$res = preg_split("/\r?\n/",$result);
 
 		if (strcmp($res[0], "yes") == 0) {
@@ -116,7 +116,7 @@ class sspmod_cas_Auth_Source_CAS  extends SimpleSAML_Auth_Source  {
 				'ticket' => $ticket,
 				'service' => $service,
 		));
-		$result = SimpleSAML_Utilities::fetch($url);
+		$result = \SimpleSAML\Utils\HTTP::fetch($url);
 
 		$dom = DOMDocument::loadXML($result);
 		$xPath = new DOMXpath($dom);
diff --git a/modules/casserver/www/serviceValidate.php b/modules/casserver/www/serviceValidate.php
index 8a413519b..ad5616d56 100644
--- a/modules/casserver/www/serviceValidate.php
+++ b/modules/casserver/www/serviceValidate.php
@@ -48,7 +48,7 @@ try {
 				'forceAuthn' => false,
 				'proxies' => array_merge(array($service), $ticketcontent['proxies']),
 				'validbefore' => time() + 60);
-			SimpleSAML_Utilities::fetch($pgtUrl . '?pgtIou=' . $pgtiou . '&pgtId=' . $pgt);
+			\SimpleSAML\Utils\HTTP::fetch($pgtUrl . '?pgtIou=' . $pgtiou . '&pgtId=' . $pgt);
 			storeTicket($pgt, $path, $content);
 			$pgtiouxml = "\n<cas:proxyGrantingTicket>$pgtiou</cas:proxyGrantingTicket>\n";
 		}
diff --git a/modules/metarefresh/lib/MetaLoader.php b/modules/metarefresh/lib/MetaLoader.php
index 93dab47c9..3f09817ea 100644
--- a/modules/metarefresh/lib/MetaLoader.php
+++ b/modules/metarefresh/lib/MetaLoader.php
@@ -50,7 +50,7 @@ class sspmod_metarefresh_MetaLoader {
 
 			// GET!
 			try {
-				list($data, $responseHeaders) = SimpleSAML_Utilities::fetch($source['src'], $context, TRUE);
+				list($data, $responseHeaders) = \SimpleSAML\Utils\HTTP::fetch($source['src'], $context, TRUE);
 			} catch(Exception $e) {
 				SimpleSAML_Logger::warning('metarefresh: ' . $e->getMessage());
 			}
-- 
GitLab