Overview

Namespaces

  • MvcCore
    • Ext
      • Auth
        • Virtual
      • Debug
        • Tracy
      • Form
        • Core
        • Validators
      • Request
      • Router
        • Lang
      • View
        • Helpers
  • None

Classes

  • MvcCore
  • MvcCore\Config
  • MvcCore\Controller
  • MvcCore\Debug
  • MvcCore\Ext\Auth
  • MvcCore\Ext\Auth\Controller
  • MvcCore\Ext\Auth\SignInForm
  • MvcCore\Ext\Auth\SignOutForm
  • MvcCore\Ext\Auth\User
  • MvcCore\Ext\Auth\Virtual\Controller
  • MvcCore\Ext\Auth\Virtual\Form
  • MvcCore\Ext\Auth\Virtual\User
  • MvcCore\Ext\Debug\Tracy
  • MvcCore\Ext\Debug\Tracy\AuthPanel
  • MvcCore\Ext\Debug\Tracy\IncludePanel
  • MvcCore\Ext\Debug\Tracy\MvcCorePanel
  • MvcCore\Ext\Debug\Tracy\RoutingPanel
  • MvcCore\Ext\Debug\Tracy\SessionPanel
  • MvcCore\Ext\Form
  • MvcCore\Ext\Form\Button
  • MvcCore\Ext\Form\Checkbox
  • MvcCore\Ext\Form\CheckboxGroup
  • MvcCore\Ext\Form\Core\Base
  • MvcCore\Ext\Form\Core\Configuration
  • MvcCore\Ext\Form\Core\Field
  • MvcCore\Ext\Form\Core\FieldGroup
  • MvcCore\Ext\Form\Core\Helpers
  • MvcCore\Ext\Form\Core\Validator
  • MvcCore\Ext\Form\Core\View
  • MvcCore\Ext\Form\CountrySelect
  • MvcCore\Ext\Form\Date
  • MvcCore\Ext\Form\DateTime
  • MvcCore\Ext\Form\Email
  • MvcCore\Ext\Form\Hidden
  • MvcCore\Ext\Form\NoType
  • MvcCore\Ext\Form\Number
  • MvcCore\Ext\Form\Password
  • MvcCore\Ext\Form\RadioGroup
  • MvcCore\Ext\Form\Range
  • MvcCore\Ext\Form\ResetButton
  • MvcCore\Ext\Form\ResetInput
  • MvcCore\Ext\Form\Select
  • MvcCore\Ext\Form\SubmitButton
  • MvcCore\Ext\Form\SubmitInput
  • MvcCore\Ext\Form\Text
  • MvcCore\Ext\Form\Textarea
  • MvcCore\Ext\Form\Time
  • MvcCore\Ext\Form\Validators\CompanyId
  • MvcCore\Ext\Form\Validators\CompanyVatId
  • MvcCore\Ext\Form\Validators\Date
  • MvcCore\Ext\Form\Validators\Email
  • MvcCore\Ext\Form\Validators\FloatVal
  • MvcCore\Ext\Form\Validators\Integer
  • MvcCore\Ext\Form\Validators\Maxlength
  • MvcCore\Ext\Form\Validators\MaxSelectedOptions
  • MvcCore\Ext\Form\Validators\MinSelectedOptions
  • MvcCore\Ext\Form\Validators\NumberField
  • MvcCore\Ext\Form\Validators\Pattern
  • MvcCore\Ext\Form\Validators\Phone
  • MvcCore\Ext\Form\Validators\RangeField
  • MvcCore\Ext\Form\Validators\SafeString
  • MvcCore\Ext\Form\Validators\Time
  • MvcCore\Ext\Form\Validators\Url
  • MvcCore\Ext\Form\Validators\ValueInOptions
  • MvcCore\Ext\Form\Validators\ZipCode
  • MvcCore\Ext\Request\ApacheDpi
  • MvcCore\Ext\Request\Cli
  • MvcCore\Ext\Router\Lang
  • MvcCore\Ext\Router\Lang\Route
  • MvcCore\Ext\Router\Media
  • MvcCore\Ext\Router\MediaSiteKey
  • MvcCore\Ext\View\Helpers\Assets
  • MvcCore\Ext\View\Helpers\Css
  • MvcCore\Ext\View\Helpers\Js
  • MvcCore\Ext\View\Helpers\LineBreaks
  • MvcCore\Model
  • MvcCore\Request
  • MvcCore\Response
  • MvcCore\Route
  • MvcCore\Router
  • MvcCore\Session
  • MvcCore\Tool
  • MvcCore\View

Exceptions

  • MvcCore\Ext\Form\Core\Exception
  • Overview
  • Namespace
  • Class
  • Tree
  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: 
<?php

/**
 * MvcCore
 *
 * This source file is subject to the BSD 3 License
 * For the full copyright and license information, please view
 * the LICENSE.md file that are distributed with this source code.
 *
 * @copyright   Copyright (c) 2016 Tom FlĂ­dr (https://github.com/mvccore/mvccore)
 * @license     https://mvccore.github.io/docs/mvccore/4.0.0/LICENCE.md
 */

namespace MvcCore\Ext\Router;

class MediaSiteKey {
    const FULL = 'full';
    const TABLET = 'tablet';
    const MOBILE = 'mobile';
}

class Media extends \MvcCore\Router {

    /**
     * MvcCore Extension - Router Media - version:
     * Comparation by PHP function version_compare();
     * @see http://php.net/manual/en/function.version-compare.php
     */
    const VERSION = '4.2.0';

    /**
     * Key name for media version in second argument $params in $router->Url();  method,
     * to tell $router->Url() method to generate different media version url.
     */
    const MEDIA_SITE_KEY_URL_PARAM = 'mediaSiteKey';

    /**
     * Special $_GET param name for session strict mode, how to change site media version.
     */
    const MEDIA_SITE_KEY_SWITCH_URL_PARAM = 'media_site_key';

    /**
     * Session expiration seconds for remembering detected media site version by user agent.
     * Session record is always used to compare if user is requesting different media 
     * site version then he has in session - if there is difference - user is redirected 
     * to session media site version and this seconds is time to remember that sessio record 
     * for described redirection.
     * @var int
     */
    public $SessionExpirationSeconds = 3600; // hour

    /**
     * Url prefixes prepended before url paths to describe media site version in url.
     * Key is media site version value and value in array is url prefix how 
     * to describe media site version in url.
     * @var array
     */
    public $AllowedSiteKeysAndUrlPrefixes = array(
        MediaSiteKey::MOBILE    => '/m',
        MediaSiteKey::TABLET    => '/t',
        MediaSiteKey::FULL      => '',
    );

    /**
     * Session record is always used to compare if user is requesting different media
     * site version then he has in session - if there is difference - user is redirected
     * to session media site version
     * @var \MvcCore\Session|\stdClass
     */
    protected $session = NULL;

    /**
     * Media site version founded in session.
     * @var string
     */
    protected $sessionMediaSiteKey = '';

    /**
     * Final media site key used in \MvcCore\Request object
     * @var string
     */
    protected $mediaSiteKey = '';

    /**
     * Media site version for switching, always initialized by special switching $_GET param.
     * @var string|bool
     */
    protected $mediaSiteKeySwitchUriParam = FALSE;

    /**
     * If true, process media site version strictly by session stored version,
     * so if request contains some version and in session is different, redirect
     * user to session version value adress, only when media site switching param 
     * is contained in $_GET, switch the version in session.
     * If false, process media site version more benevolently, so if request 
     * contains some version and in session is different, store in session media
     * site version from request and do not redirect user.
     * @var bool
     */
    protected $stricModeBySession = FALSE;

    /**
     * Static initialization - called when class is included by autoloader
     * @return void
     */
    public static function StaticInit () {
        \MvcCore::AddPreRouteHandler(function (\MvcCore\Request & $request, \MvcCore\Response & $response) {
            \MvcCore::SessionStart();
            static::GetInstance()->ProcessMediaSiteVersion($request);
        });
    }

    /**
     * Set session expiration seconds for remembering detected media site version by user agent.
     * Session record is always used to compare if user is requesting different media
     * site version then he has in session - if there is difference - user is redirected
     * to session media site version and this seconds is time to remember that sessio record
     * for described redirection.
     * @var int
     */
    public function SetSessionExpirationSeconds ($sessionExpirationSeconds = 3600) {
        $this->SessionExpirationSeconds = $sessionExpirationSeconds;
        return $this;
    }

    /**
     * Set url prefixes prepended before url paths to describe media site version in url
     * and by defined keys in given array - set only allowed media versions to work with.
     * Key is media site version value and value is url prefix how to describe 
     * media site version in url.
     * @param array $allowedSiteKeysAndUrlPrefixes 
     * @return \MvcCore\Ext\Router\Media
     */
    public function SetAllowedSiteKeysAndUrlPrefixes ($allowedSiteKeysAndUrlPrefixes = array()) {
        $this->AllowedSiteKeysAndUrlPrefixes = $allowedSiteKeysAndUrlPrefixes;
        return $this;
    }

    /**
     * Set session strict mode.
     * If true, process media site version strictly by session stored version,
     * so if request contains some version and in session is different, redirect
     * user to session version value adress, only when media site switching param
     * is contained in $_GET, switch the version in session.
     * If false, process media site version more benevolently, so if request
     * contains some version and in session is different, store in session media
     * site version from request and do not redirect user.
     * @param bool $stricModeBySession 
     * @return \MvcCore\Ext\Router\Media
     */
    public function SetStricModeBySession ($stricModeBySession = TRUE) {
        $this->stricModeBySession = $stricModeBySession;
        return $this;
    }

    /**
     * Complete url by route instance reverse info
     * @param string $controllerActionOrRouteName
     * @param array  $params
     * @return string
     */
    protected function urlByRoute ($controllerActionOrRouteName, $params) {
        $route = $this->urlRoutes[$controllerActionOrRouteName];
        $allParams = array_merge(
            is_array($route->Params) ? $route->Params : array(), $params
        );
        $mediaSiteKey = '';
        if (isset($allParams[static::MEDIA_SITE_KEY_URL_PARAM])) {
            $mediaSiteKey = $allParams[static::MEDIA_SITE_KEY_URL_PARAM];
            unset($allParams[static::MEDIA_SITE_KEY_URL_PARAM]);
        } else {
            $mediaSiteKey = $this->mediaSiteKey;
        }
        $result = rtrim($route->Reverse, '?&');
        foreach ($allParams as $key => $value) {
            $paramKeyReplacement = "{%$key}";
            if (mb_strpos($result, $paramKeyReplacement) === FALSE) {
                $glue = (mb_strpos($result, '?') === FALSE) ? '?' : '&';
                $result .= $glue . http_build_query(array($key => $value));
            } else {
                $result = str_replace($paramKeyReplacement, $value, $result);
            }
        }
        return $this->request->BasePath . $this->AllowedSiteKeysAndUrlPrefixes[$mediaSiteKey] . $result;
    }

    /**
     * Process media site version before request is routed by \MvcCore\Router
     * Prepare: 
     * - media version from request
     * - media version from session (setted by any previous request)
     * - detect if there is any special media site switching parameter in $_GET (static::MEDIA_SITE_KEY_SWITCH_URL_PARAM)
     * For each GET request - do:
     * - if there is special media site switching param in request $_GET and it's allowed
     *   - switch media site version in session by it and redirect to the same url with new media site version substring in url
     * - if there is no media site version in session or if media site version from sesson is not allowed
     *   - recognize media site version by Mobile_Detect third party library and store recognized version in this context and in session
     * - else set up media site version from session
     * - later if detected media site version is not the same as requested media site version - redirect to detected version
     * @param \MvcCore\Request $request
     * @return void
     */
    public function ProcessMediaSiteVersion (\MvcCore\Request & $request)
    {
        $this->request = & $request;
        $this->request->OriginalPath = $this->request->Path;
        // switching media site version will be only by get:
        $this->isGet = $request->Method == \MvcCore\Request::METHOD_GET;
        // look into request params if are we just switching any new site media version
        if (isset($_GET[static::MEDIA_SITE_KEY_SWITCH_URL_PARAM])) {
            $this->mediaSiteKeySwitchUriParam = strtolower($_GET[static::MEDIA_SITE_KEY_SWITCH_URL_PARAM]);
        }
        // set up current media site version from url string
        $this->setUpRequestMediaSiteKeyFromUrl();
        // set up session object to look inside for something from previous requests
        static::setUpSession();
        // look into session object if there are or not any record about recognized device from previous request
        if (isset($this->session->{static::MEDIA_SITE_KEY_URL_PARAM})) {
            $this->sessionMediaSiteKey = $this->session->{static::MEDIA_SITE_KEY_URL_PARAM};
        }

        if (
            $this->isGet && 
            $this->mediaSiteKeySwitchUriParam !== FALSE && 
            isset($this->AllowedSiteKeysAndUrlPrefixes[$this->mediaSiteKeySwitchUriParam])
        ) {
            $this->manageSwitchingAndRedirect();

        } else if (
            $this->isGet && 
            (
                $this->sessionMediaSiteKey === '' || 
                !isset($this->AllowedSiteKeysAndUrlPrefixes[$this->sessionMediaSiteKey])
            )
        ) {
            $this->manageDetectionAndStoreInSession();
            $this->checkMediaSiteVersionWithRequestVersionAndRedirectIfDifferent();
            
        } else {
            $this->mediaSiteKey = $this->sessionMediaSiteKey;
            $this->checkMediaSiteVersionWithRequestVersionAndRedirectIfDifferent();
        }
        
        $request->MediaSiteKey = $this->mediaSiteKey;
    }

    /**
     * Store new media site key from url into session, 
     * remove it from $_GET, redirect to the same url as reqest without
     * switch media site version param and exit inside redirect function
     * @return void
     */
    protected function manageSwitchingAndRedirect () {
        $mediaSiteKey = $this->mediaSiteKeySwitchUriParam;
        // store switched site key into session
        $this->session->{static::MEDIA_SITE_KEY_URL_PARAM} = $mediaSiteKey;
        unset($_GET[static::MEDIA_SITE_KEY_SWITCH_URL_PARAM]);
        // unset site key switch param and redirect to no switch param uri version
        $query = count($_GET) > 0 ? '?' . http_build_query($_GET) : '';
        $targetUrl = $this->request->DomainUrl . $this->request->BasePath
            . $this->AllowedSiteKeysAndUrlPrefixes[$mediaSiteKey] . $this->request->Path . $query;
        \MvcCore\Controller::Redirect($targetUrl);
    }

    /**
     * Detect media site version by sended user agent string (Mobile_Detect library)
     * and store detected result in session for next requests
     * @return void
     */
    protected function manageDetectionAndStoreInSession() {
        $detect = new \Mobile_Detect();
        $mediaSiteKeys = array_keys($this->AllowedSiteKeysAndUrlPrefixes);
        if ($detect->isMobile()) {
            $this->mediaSiteKey = $mediaSiteKeys[0];
        } else if ($detect->isTablet()) {
            $this->mediaSiteKey = $mediaSiteKeys[1];
        } else {
            $this->mediaSiteKey = $mediaSiteKeys[2];
        }
        $this->session->{static::MEDIA_SITE_KEY_URL_PARAM} = $this->mediaSiteKey;
    }

    /**
     * If local media site version (completed previously from session or Mobile_Detect library)
     * is different then media site version from request - redirect to url with media site version 
     * from local $this context and exit (inside redirect function)
     * @return void
     */
    protected function checkMediaSiteVersionWithRequestVersionAndRedirectIfDifferent() {
        $sessionOrDetectionSameWithRequest = $this->mediaSiteKey === $this->request->MediaSiteKey;
        if (!$sessionOrDetectionSameWithRequest) {
            if ($this->stricModeBySession) {
                $targetUrl = $this->request->Protocol . '//' . $this->request->Host . $this->request->BasePath
                    . $this->AllowedSiteKeysAndUrlPrefixes[$this->mediaSiteKey] . $this->request->Path;
                $targetUrl .= $this->request->Query ? '?' . $this->request->Query : '';
                if ($this->isGet) \MvcCore\Controller::Redirect($targetUrl);
            } else {
                $this->session->{static::MEDIA_SITE_KEY_URL_PARAM} = $this->request->MediaSiteKey;
                $this->mediaSiteKey = $this->request->MediaSiteKey;
            }
        }
    }

    /**
     * If session namespace by this class is not initialized,
     * init namespace and move expiration to next hour
     * @return void
     */
    protected function setUpSession () {
        if (is_null($this->session)) {
            $this->session = \MvcCore\Session::GetNamespace(__CLASS__);
            $this->session->SetExpirationSeconds($this->SessionExpirationSeconds);
        }
    }

    /**
     * Try to set up into \MvcCore\Request object a MediaSiteKey property by requested url
     * by defined url prefixes founded in requested url.
     * @return void
     */
    protected function setUpRequestMediaSiteKeyFromUrl () {
        foreach ($this->AllowedSiteKeysAndUrlPrefixes as $mediaSiteKey => $requestPathPrefix) {
            if (mb_strpos($this->request->Path, $requestPathPrefix . '/') === 0) {
                $this->request->MediaSiteKey = $mediaSiteKey;
                $this->request->Path = mb_substr($this->request->Path, strlen($requestPathPrefix));
                break;
            }
        }
    }
}
Media::StaticInit();
MvcCore API documentation generated by ApiGen