ServerUrl.php 8.2 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\View\Helper;

/**
 * Helper for returning the current server URL (optionally with request URI)
 */
class ServerUrl extends AbstractHelper
{
    /**
     * Host (including port)
     *
     * @var string
     */
    protected $host;

    /**
     * Port
     *
     * @var int
     */
    protected $port;

    /**
     * Scheme
     *
     * @var string
     */
    protected $scheme;

    /**
     * Whether or not to query proxy servers for address
     *
     * @var bool
     */
    protected $useProxy = false;

    /**
     * View helper entry point:
     * Returns the current host's URL like http://site.com
     *
     * @param  string|bool $requestUri  [optional] if true, the request URI
     *                                     found in $_SERVER will be appended
     *                                     as a path. If a string is given, it
     *                                     will be appended as a path. Default
     *                                     is to not append any path.
     * @return string
     */
    public function __invoke($requestUri = null)
    {
        if ($requestUri === true) {
            $path = $_SERVER['REQUEST_URI'];
        } elseif (is_string($requestUri)) {
            $path = $requestUri;
        } else {
            $path = '';
        }

        return $this->getScheme() . '://' . $this->getHost() . $path;
    }

    /**
     * Detect the host based on headers
     *
     * @return void
     */
    protected function detectHost()
    {
        if ($this->setHostFromProxy()) {
            return;
        }

        if (isset($_SERVER['HTTP_HOST']) && ! empty($_SERVER['HTTP_HOST'])) {
            // Detect if the port is set in SERVER_PORT and included in HTTP_HOST
            if (isset($_SERVER['SERVER_PORT'])
                && preg_match('/^(?P<host>.*?):(?P<port>\d+)$/', $_SERVER['HTTP_HOST'], $matches)
            ) {
                // If they are the same, set the host to just the hostname
                // portion of the Host header.
                if ((int) $matches['port'] === (int) $_SERVER['SERVER_PORT']) {
                    $this->setHost($matches['host']);
                    return;
                }

                // At this point, we have a SERVER_PORT that differs from the
                // Host header, indicating we likely have a port-forwarding
                // situation. As such, we'll set the host and port from the
                // matched values.
                $this->setPort((int) $matches['port']);
                $this->setHost($matches['host']);
                return;
            }

            $this->setHost($_SERVER['HTTP_HOST']);

            return;
        }

        if (! isset($_SERVER['SERVER_NAME']) || ! isset($_SERVER['SERVER_PORT'])) {
            return;
        }

        $name = $_SERVER['SERVER_NAME'];
        $this->setHost($name);
    }

    /**
     * Detect the port
     *
     * @return null
     */
    protected function detectPort()
    {
        if ($this->setPortFromProxy()) {
            return;
        }

        if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT']) {
            if ($this->isReversedProxy()) {
                $this->setPort(443);
                return;
            }
            $this->setPort($_SERVER['SERVER_PORT']);
            return;
        }
    }

    /**
     * Detect the scheme
     *
     * @return null
     */
    protected function detectScheme()
    {
        if ($this->setSchemeFromProxy()) {
            return;
        }

        switch (true) {
            case (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] === true)):
            case (isset($_SERVER['HTTP_SCHEME']) && ($_SERVER['HTTP_SCHEME'] == 'https')):
            case (443 === $this->getPort()):
            case $this->isReversedProxy():
                $scheme = 'https';
                break;
            default:
                $scheme = 'http';
                break;
        }

        $this->setScheme($scheme);
    }

    protected function isReversedProxy()
    {
        return isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https';
    }

    /**
     * Detect if a proxy is in use, and, if so, set the host based on it
     *
     * @return bool
     */
    protected function setHostFromProxy()
    {
        if (! $this->useProxy) {
            return false;
        }

        if (! isset($_SERVER['HTTP_X_FORWARDED_HOST']) || empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
            return false;
        }

        $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
        if (strpos($host, ',') !== false) {
            $hosts = explode(',', $host);
            $host = trim(array_pop($hosts));
        }
        if (empty($host)) {
            return false;
        }
        $this->setHost($host);

        return true;
    }

    /**
     * Set port based on detected proxy headers
     *
     * @return bool
     */
    protected function setPortFromProxy()
    {
        if (! $this->useProxy) {
            return false;
        }

        if (! isset($_SERVER['HTTP_X_FORWARDED_PORT']) || empty($_SERVER['HTTP_X_FORWARDED_PORT'])) {
            return false;
        }

        $port = $_SERVER['HTTP_X_FORWARDED_PORT'];
        $this->setPort($port);

        return true;
    }

    /**
     * Set the current scheme based on detected proxy headers
     *
     * @return bool
     */
    protected function setSchemeFromProxy()
    {
        if (! $this->useProxy) {
            return false;
        }

        if (isset($_SERVER['SSL_HTTPS'])) {
            $sslHttps = strtolower($_SERVER['SSL_HTTPS']);
            if (in_array($sslHttps, ['on', 1])) {
                $this->setScheme('https');
                return true;
            }
        }

        if (! isset($_SERVER['HTTP_X_FORWARDED_PROTO']) || empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
            return false;
        }

        $scheme = trim(strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']));
        if (empty($scheme)) {
            return false;
        }

        $this->setScheme($scheme);

        return true;
    }

    /**
     * Sets host
     *
     * @param  string $host
     * @return ServerUrl
     */
    public function setHost($host)
    {
        $port   = $this->getPort();
        $scheme = $this->getScheme();

        if (($scheme == 'http' && (null === $port || $port == 80))
            || ($scheme == 'https' && (null === $port || $port == 443))
        ) {
            $this->host = $host;
            return $this;
        }

        $this->host = $host . ':' . $port;

        return $this;
    }

    /**
     * Returns host
     *
     * @return string
     */
    public function getHost()
    {
        if (null === $this->host) {
            $this->detectHost();
        }

        return $this->host;
    }

    /**
     * Set server port
     *
     * @param  int $port
     * @return ServerUrl
     */
    public function setPort($port)
    {
        $this->port = (int) $port;

        return $this;
    }

    /**
     * Retrieve the server port
     *
     * @return int|null
     */
    public function getPort()
    {
        if (null === $this->port) {
            $this->detectPort();
        }

        return $this->port;
    }

    /**
     * Sets scheme (typically http or https)
     *
     * @param  string $scheme
     * @return ServerUrl
     */
    public function setScheme($scheme)
    {
        $this->scheme = $scheme;

        return $this;
    }

    /**
     * Returns scheme (typically http or https)
     *
     * @return string
     */
    public function getScheme()
    {
        if (null === $this->scheme) {
            $this->detectScheme();
        }

        return $this->scheme;
    }

    /**
     * Set flag indicating whether or not to query proxy servers
     *
     * @param  bool $useProxy
     * @return ServerUrl
     */
    public function setUseProxy($useProxy = false)
    {
        $this->useProxy = (bool) $useProxy;

        return $this;
    }
}