From 85244fa0d06eec620f8476817f68d8ea2dca0e38 Mon Sep 17 00:00:00 2001
From: ArthurHoaro <arthur@hoa.ro>
Date: Sun, 28 Feb 2016 16:24:18 +0100
Subject: Fixes #477: support multi reverse proxy with comma syntax

Going through multiple reverse proxy will store multiple scheme and port in HTTP header separated by a comma. Shaarli will use the first one to generate server_url.
---
 application/HttpUtils.php         | 14 ++++++++++++--
 tests/HttpUtils/ServerUrlTest.php | 13 +++++++++++++
 2 files changed, 25 insertions(+), 2 deletions(-)

diff --git a/application/HttpUtils.php b/application/HttpUtils.php
index e2c1cb47..af7cb371 100644
--- a/application/HttpUtils.php
+++ b/application/HttpUtils.php
@@ -106,11 +106,21 @@ function server_url($server)
     // Shaarli is served behind a proxy
     if (isset($server['HTTP_X_FORWARDED_PROTO'])) {
         // Keep forwarded scheme
-        $scheme = $server['HTTP_X_FORWARDED_PROTO'];
+        if (strpos($server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
+            $schemes = explode(',', $server['HTTP_X_FORWARDED_PROTO']);
+            $scheme = trim($schemes[0]);
+        } else {
+            $scheme = $server['HTTP_X_FORWARDED_PROTO'];
+        }
 
         if (isset($server['HTTP_X_FORWARDED_PORT'])) {
             // Keep forwarded port
-            $port = ':'.$server['HTTP_X_FORWARDED_PORT'];
+            if (strpos($server['HTTP_X_FORWARDED_PORT'], ',') !== false) {
+                $ports = explode(',', $server['HTTP_X_FORWARDED_PORT']);
+                $port = ':' . trim($ports[0]);
+            } else {
+                $port = ':' . $server['HTTP_X_FORWARDED_PORT'];
+            }
         }
 
         return $scheme.'://'.$server['SERVER_NAME'].$port;
diff --git a/tests/HttpUtils/ServerUrlTest.php b/tests/HttpUtils/ServerUrlTest.php
index 5096db65..8a55a220 100644
--- a/tests/HttpUtils/ServerUrlTest.php
+++ b/tests/HttpUtils/ServerUrlTest.php
@@ -67,6 +67,19 @@ class ServerUrlTest extends PHPUnit_Framework_TestCase
                 )
             )
         );
+
+        $this->assertEquals(
+            'https://host.tld:4974',
+            server_url(
+                array(
+                    'HTTPS' => 'Off',
+                    'SERVER_NAME' => 'host.tld',
+                    'SERVER_PORT' => '80',
+                    'HTTP_X_FORWARDED_PROTO' => 'https, https',
+                    'HTTP_X_FORWARDED_PORT' => '4974, 80'
+                )
+            )
+        );
     }
 
     /**
-- 
cgit v1.2.3