Пример #1
0
 /**
  * Attempt to get a CSRF from frontend, either using
  * the X-CSRF-Token HTTP header or the csrf_token
  * POST parameter.
  * */
 private function _getFrontendToken(Zend_Controller_Request_Abstract $request)
 {
     if ($request->getHeader('X-CSRF-Token')) {
         return $request->getHeader('X-CSRF-Token');
     } else {
         return $request->getPost('csrf_token');
     }
 }
Пример #2
0
 /**
  * Fetches authentication credentials from the current request
  *
  * @param Zend_Controller_Request_Abstract $request The current request object
  *
  * @return array
  */
 private function _getAuthHeaderCredentials(Zend_Controller_Request_Abstract $request)
 {
     $authHeader = $request->getHeader('Authorization');
     if (is_string($authHeader) && strlen($authHeader) > 0) {
         if (strtolower(substr($authHeader, 0, 8)) === 'foaf+ssl') {
             $auth = base64_decode(substr($authHeader, 9));
             $creds = explode('=', $auth);
             foreach ($creds as &$c) {
                 if (substr($c, 0, 1) === '"') {
                     $c = substr($c, 1, -1);
                 }
             }
             if (count($creds) > 0) {
                 return array('type' => 'foaf+ssl', 'creds' => $creds);
             }
         } else {
             if (strtolower(substr($authHeader, 0, 5)) === 'basic') {
                 $auth = base64_decode(substr($authHeader, 6));
                 $creds = array_filter(explode(':', $auth));
                 if (count($creds) > 0) {
                     return array('type' => 'basic', 'username' => $creds[0], 'password' => isset($creds[1]) ? $creds[1] : '');
                 }
             }
         }
     }
 }
Пример #3
0
 public function preDispatch(\Zend_Controller_Request_Abstract $request)
 {
     if (APPLICATION_ENV != 'development' && !$request->getHeader('DNT')) {
         $view = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view');
         $view->headScript()->appendFile('js/track.js');
     }
 }
Пример #4
0
 /**
  * @param Zend_Controller_Request_Abstract $request
  */
 public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
 {
     if (!$request instanceof Zend_Controller_Request_Http) {
         return;
     }
     // Accept URI parameter over Accept header for specifying of desired response format
     $format = $this->getRequest()->getParam('format') ?: $request->getHeader('Accept');
     // @todo Need to look into implementing Accept header supporting multiple types with quality factors
     switch (true) {
         // XML
         case stristr($format, 'text/xml') && !stristr($format, 'html'):
             $request->setParam('format', 'xml');
             break;
             // JSONP/Javascript
         // JSONP/Javascript
         case stristr($format, 'text/javascript'):
             $request->setParam('format', 'js');
             break;
             // JSON
         // JSON
         case stristr($format, 'application/json'):
         default:
             // Note the fall through!
             $request->setParam('format', 'json');
             break;
     }
 }
Пример #5
0
 public function preDispatch(Zend_Controller_Request_Abstract $request)
 {
     $context = $request->getHeader('X-Zrt-Format');
     if ($context) {
         $request->setParam('format', $context);
     }
 }
Пример #6
0
 /**
  * Validates the current request.
  *
  * All requests MUST include a valid User-Agent header. Requests with no
  * User-Agent header will be rejected.
  *
  * @internal
  * @param Zend_Controller_Request_Abstract $request
  * @see http://framework.zend.com/manual/1.12/en/zend.controller.request.html Zend_Controller_Request_Abstract
  */
 public function routeStartup(Zend_Controller_Request_Abstract $request)
 {
     if (!$request->getHeader('User-Agent')) {
         $this->getResponse()->setHttpResponseCode(403)->setHeader('Content-Type', 'text/plain; charset=utf-8')->setBody(implode("\n", self::$_errMessage))->sendResponse();
         exit(403);
     }
 }
Пример #7
0
 /**
  * Set REST action/method based on cascading priority of allowed syntaxes
  * 
  * @param Zend_Controller_Request_Abstract $request
  */
 public function routeShutdown(Zend_Controller_Request_Abstract $request)
 {
     // Only do for API module
     if ('api' != $this->getRequest()->getModuleName()) {
         return;
     }
     $action = $request->getMethod();
     // Support override of method request type
     if ('get' != strtolower($action)) {
         if ($request->getParam('_method')) {
             $action = $request->getParam('_method');
         } elseif ($request->getHeader('X-HTTP-Method-Override')) {
             $action = $request->getHeader('X-HTTP-Method-Override');
         }
     }
     $request->setActionName(strtolower($action));
 }
Пример #8
0
 /**
  * Sets the application locale and translation based on the locale param, if
  * one is not provided it defaults to english
  *
  * @param Zend_Controller_Request_Abstract $request
  * @return Void
  */
 public function routeShutdown(Zend_Controller_Request_Abstract $request)
 {
     $config = Zend_Registry::get('config');
     $frontController = Zend_Controller_Front::getInstance();
     $params = $request->getParams();
     $registry = Zend_Registry::getInstance();
     // Steps setting the locale.
     // 1. Default language is set in config
     // 2. TLD in host header
     // 3. Locale params specified in request
     $locale = $registry->get('Zend_Locale');
     // Check host header TLD.
     $tld = preg_replace('/^.*\\./', '', $request->getHeader('Host'));
     // Provide a list of tld's and their corresponding default languages
     $tldLocales = $frontController->getParam('tldLocales');
     if (is_array($tldLocales) && array_key_exists($tld, $tldLocales)) {
         // The TLD in the request matches one of our specified TLD -> Locales
         $locale->setLocale(strtolower($tldLocales[$tld]));
     } elseif (isset($params['locale'])) {
         // There is a locale specified in the request params.
         $locale->setLocale(strtolower($params['locale']));
     }
     // Now that our locale is set, let's check which language has been selected
     // and try to load a translation file for it.
     $language = $locale->getLanguage();
     $translate = Garp_I18n::getTranslateByLocale($locale);
     Zend_Registry::set('Zend_Translate', $translate);
     Zend_Form::setDefaultTranslator($translate);
     if (!$config->resources->router->locale->enabled) {
         return;
     }
     $path = '/' . ltrim($request->getPathInfo(), '/\\');
     // If the language is in the path, then we will want to set the baseUrl
     // to the specified language.
     $langIsInUrl = preg_match('/^\\/' . $language . '\\/?/', $path);
     $uiDefaultLangIsInUrl = false;
     $uiDefaultLanguage = false;
     if (isset($config->resources->locale->uiDefault)) {
         $uiDefaultLanguage = $config->resources->locale->uiDefault;
         $uiDefaultLangIsInUrl = preg_match('/^\\/' . $uiDefaultLanguage . '\\/?/', $path);
     }
     if ($langIsInUrl || $uiDefaultLangIsInUrl) {
         if ($uiDefaultLangIsInUrl) {
             $frontController->setBaseUrl($frontController->getBaseUrl() . '/' . $uiDefaultLanguage);
         } else {
             $frontController->setBaseUrl($frontController->getBaseUrl() . '/' . $language);
         }
     } elseif (!empty($config->resources->router->locale->enabled) && $config->resources->router->locale->enabled) {
         $redirectUrl = '/' . $language . $path;
         if ($frontController->getRouter()->getCurrentRouteName() === 'admin' && !empty($config->resources->locale->adminDefault)) {
             $adminDefaultLanguage = $config->resources->locale->adminDefault;
             $redirectUrl = '/' . $adminDefaultLanguage . $path;
         } elseif ($uiDefaultLanguage) {
             $redirectUrl = '/' . $uiDefaultLanguage . $path;
         }
         $this->getResponse()->setRedirect($redirectUrl, 301);
     }
 }
Пример #9
0
 public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
 {
     $header = $request->getHeader('Accept');
     if (strstr($header, 'application/json')) {
         $request->setParam('format', 'json');
     } elseif (strstr($header, 'application/xml')) {
         $request->setParam('format', 'xml');
     } else {
         $request->setParam('format', 'html');
     }
 }
Пример #10
0
 /**
  * Check if the request is HTTP, if so check for a Accept header and set the right format in the request object
  *
  * @param Zend_Controller_Request_Abstract $request
  * @return void
  */
 public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
 {
     // Skip header check when we don't have a HTTP request (for instance: cli-scripts)
     if (!$request instanceof Zend_Controller_Request_Http) {
         return;
     }
     $this->getResponse()->setHeader('Vary', 'Accept');
     $header = $request->getHeader('Accept');
     foreach (self::$_mapping as $format => $requestHeader) {
         if (false !== strstr($header, $requestHeader)) {
             $request->setParam('format', $format);
             break;
         }
     }
 }
Пример #11
0
 public function preDispatch(Zend_Controller_Request_Abstract $request)
 {
     $apiKey = $request->getHeader('Api-Key');
     //on récupère notre fichier de configuration
     //car notre apikey est stoquée dedans
     $config = Zend_Controller_Front::getInstance()->getParam('bootstrap');
     $configkeys = $config->getOption('apikey');
     //Si notre apikey est mauvaise alors qu'on essaie d'accéder à notre module rest et qu'on est pas sur la page d'erreur,
     //on renvoie vers la page d'erreur
     if ($apiKey != $configkeys['rest'] && $request->getControllerName() != "error") {
         //Ici, on met le code 403 ACCES_DENIED à notre réponse HTTP
         $this->getResponse()->setHttpResponseCode(403);
         //Et on redirige vers le controller d'erreur
         $request->setControllerName('error')->setActionName('api')->setDispatched(true);
     }
 }
Пример #12
0
 public function routeShutdown(Zend_Controller_Request_Abstract $request)
 {
     $this->_request = $request;
     $format = 'html';
     if ($accept = $request->getHeader('Accept')) {
         if (strpos($accept, 'html') === false) {
             $types = explode(',', $accept);
             $mainType = trim($types[0]);
             $mime = explode('/', $mainType);
             if ($mime[1] !== '') {
                 $format = $mime[1];
             }
         }
     }
     if ($request->getParam('format') === null) {
         $request->setParam('format', $format);
     }
     $context = $request->format;
     $contextHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('contextSwitch');
     $contextHelper->addContext('html', array())->setDefaultContext('html');
     $this->_initDependencies($context);
 }
Пример #13
0
 public function preDispatch(Zend_Controller_Request_Abstract $request)
 {
     Zend_Registry::set('requestIsAjax', $request->isXmlHttpRequest());
     $format = $this->parseAccept($request->getHeader('accept'));
     Zend_Registry::set('responseFormat', $format);
 }
 /**
  * PHP only parses the body into $_POST if its a POST request
  * this parses the reqest body in accordance with RFC2616 spec regardless of the HTTP method
  */
 private function handleRequestBody(Zend_Controller_Request_Abstract $request)
 {
     $header = strtolower($request->getHeader('Content-Type'));
     // cleanup the charset part
     $header = current(explode(';', $header));
     // detect request body content type
     foreach ($this->requestTypes as $contentType) {
         if ($header == $contentType) {
             break;
         }
     }
     // extract the raw body
     $rawBody = $request->getRawBody();
     // treat these two separately because of the way PHP treats POST
     if (in_array($contentType, array('multipart/form-data', 'application/x-www-form-urlencoded'))) {
         // PHP takes care of everything for us in this case lets just modify the $_FILES array
         if ($request->isPost() && $contentType == 'multipart/form-data') {
             // if there are files, lets modify the array to match what we've done below
             foreach ($_FILES as &$file) {
                 $data = file_get_contents($file['tmp_name']);
                 $file['content'] = base64_encode($data);
             }
             // reset the array pointer
             unset($file);
         } else {
             switch ($contentType) {
                 case 'application/x-www-form-urlencoded':
                     parse_str($rawBody, $_POST);
                     break;
                     // this is wher the magic happens
                     // creates the $_FILES array for none POST requests
                 // this is wher the magic happens
                 // creates the $_FILES array for none POST requests
                 case 'multipart/form-data':
                     // extract the boundary
                     parse_str(end(explode(';', $request->getHeader('Content-Type'))));
                     if (isset($boundary)) {
                         // get rid of the boundary at the edges
                         if (preg_match(sprintf('/--%s(.+)--%s--/s', $boundary, $boundary), $rawBody, $regs)) {
                             // split into chuncks
                             $chunks = explode('--' . $boundary, trim($regs[1]));
                             foreach ($chunks as $chunk) {
                                 // parse each chunk
                                 if (preg_match('/Content-Disposition: form-data; name="(?P<name>.+?)"(?:; filename="(?P<filename>.+?)")?(?P<headers>(?:\\r|\\n)+?.+?(?:\\r|\\n)+?)?(?P<data>.+)/si', $chunk, $regs)) {
                                     // dedect a file upload
                                     if (!empty($regs['filename'])) {
                                         // put aside for further analysis
                                         $data = $regs['data'];
                                         $headers = $this->parseHeaders($regs['headers']);
                                         // set our params variable
                                         $_FILES[$regs['name']] = array('name' => $regs['filename'], 'type' => $headers['Content-Type'], 'size' => mb_strlen($data), 'content' => base64_encode($data));
                                         // otherwise its a regular key=value combination
                                     } else {
                                         $_POST[$regs['name']] = trim($regs['data']);
                                     }
                                 }
                             }
                         }
                     }
                     break;
             }
         }
         $request->setParams($_POST + $_FILES);
     } elseif (!empty($rawBody)) {
         // seems like we are dealing with an encoded request
         try {
             switch ($contentType) {
                 case 'text/javascript':
                 case 'application/json':
                 case 'application/javascript':
                     $_POST = (array) Zend_Json::decode($rawBody, Zend_Json::TYPE_OBJECT);
                     break;
                 case 'text/xml':
                 case 'application/xml':
                     $json = @Zend_Json::fromXml($rawBody);
                     $_POST = (array) Zend_Json::decode($json, Zend_Json::TYPE_OBJECT)->request;
                     break;
                 case 'text/php':
                 case 'application/x-httpd-php':
                 case 'application/x-httpd-php-source':
                     $_POST = (array) unserialize($rawBody);
                     break;
                 default:
                     $_POST = (array) $rawBody;
                     break;
             }
             $request->setParams($_POST);
         } catch (Exception $e) {
             $request->dispatchError(REST_Response::BAD_REQUEST, 'Invalid Payload Format');
             return;
         }
     }
 }
Пример #15
0
 /**
  * Route shutdown hook -- Check for router exceptions
  *
  * @param Zend_Controller_Request_Abstract $request
  */
 public function routeShutdown(Zend_Controller_Request_Abstract $request)
 {
     // Avoid error override! :S
     if (count($this->getResponse()->getException())) {
         return;
     }
     if ($request->getHeader('Unica-Application')) {
         // External API authentication MicroGateway
         $adapter = new App_Auth_Adapter_ExternalUgw();
     } else {
         if ($request->getHeader('TransactionInfo')) {
             // External API authentication
             $adapter = new App_Auth_Adapter_External();
         } else {
             if ($request->getHeader(App_Auth_Adapter_ThirdParty::HEADER)) {
                 // External API authentication
                 $adapter = new App_Auth_Adapter_ThirdParty();
             } else {
                 if (($token = $request->getParam('downloadToken')) && $token instanceof Download\Model\DownloadTokenModel) {
                     // Download authentication
                     $adapter = new App_Auth_Adapter_DownloadToken();
                 } else {
                     $auth = Zend_Auth::getInstance();
                     // Temporal + Persistent login
                     $temporalLogins = array(self::AUTH_TYPE_AUTH_TOKEN, self::AUTH_TYPE_REGULAR, self::AUTH_TYPE_CORE, self::AUTH_TYPE_ACTIVATION_TOKEN, self::AUTH_TYPE_LOST_PASSWORD_TOKEN, self::AUTH_TYPE_PASSWORD_EXPIRED_TOKEN);
                     // Don't keep identity if authType is temporal
                     // remove false when FE fix their implementation
                     if ($auth->hasIdentity() && ($ident = $auth->getIdentity()) && !$request->getHeader('Authorization')) {
                         if (!empty($ident['authType']) && !in_array($ident['authType'], $temporalLogins)) {
                             $auth->clearIdentity();
                         } else {
                             if (!empty($ident['token'])) {
                                 // Send the token in the response and assume logged
                                 $this->getResponse()->setHeader('X-M2M-AuthToken', $ident['token'], true);
                                 return;
                             }
                         }
                     }
                     // Common authentication
                     $adapter = new App_Auth_Adapter_M2m();
                     // Register supported authentication schemes
                     $adapter->registerScheme('M2MUser', array($this, 'schemeM2MUser'));
                     $adapter->registerScheme('M2MToken', array($this, 'schemeM2MToken'));
                     $adapter->registerScheme('M2MLogout', array($this, 'schemeM2MLogout'));
                     $adapter->registerScheme('M2MActivationToken', array($this, 'schemeM2MActivationToken'));
                     $adapter->registerScheme('M2MCore', array($this, 'schemeM2MCore'));
                     // Used for request new password, use valid user+mail to bypass lostPassword action
                     $adapter->registerScheme('M2MLostPassword', array($this, 'schemeM2MLostPassword'));
                     // Used for change user password with a valid lostToken
                     $adapter->registerScheme('M2MLostPasswordToken', array($this, 'schemeM2MLostPasswordToken'));
                     // Used for change user password with a valid token
                     $adapter->registerScheme('M2MPasswordExpiredToken', array($this, 'schemeM2MPasswordExpiredToken'));
                     // If not explicitely disabled use also auth basic
                     if (FALSE === $request->getHeader('X-M2M-NoAuthBasic')) {
                         $adapter->registerScheme('Basic', array($this, 'schemeBasic'));
                     }
                     // If explicitely enabled use also auth async method
                     if (FALSE !== $request->getHeader('X-M2M-AuthAsync')) {
                         $adapter->registerScheme('M2MAsync', array($this, 'schemeM2MAsync'));
                     }
                 }
             }
         }
     }
     // Setup the authentication adapter
     $adapter->setRequest($request);
     $adapter->setResponse(Zend_Controller_Front::getInstance()->getResponse());
     // Throws exception when auth fails, ErrorController should catch it
     $result = Zend_Auth::getInstance()->authenticate($adapter);
     if (!$result->isValid()) {
         \App::log()->debug("Authentication failed using adapter: " . get_class($adapter));
         // Notify the browser about the login needed
         $response = $this->getResponse();
         $response->setHeader('Connection', 'close');
         throw new Application\Exceptions\UnauthorizedException("Authentication failed");
     }
 }
Пример #16
0
 public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
 {
     $tw = new TeraWurfl();
     $tw->getDeviceCapabilitiesFromAgent($request->getHeader('User-Agent'));
     Zend_Registry::set('twurfl', $tw);
 }
 /**
  * NOTE only executed in case is the external module
  * 1. uses    trackingtoken    plugin
  * 2. parses  transactioninfo  header
  * 3. gets    transactionid    value  from header
  * 4. concats transactionId to tracingtoken
  *
  * @param (Zend_Controller_Request_Abstract) $request
  *
  * @return null
  * @author fmp245 <*****@*****.**>
  **/
 public function routeShutdown(Zend_Controller_Request_Abstract $request)
 {
     if ($header = $request->getHeader('M2M-Tracking-Token')) {
         $this->trackingToken->setRequestToken($header);
         return;
     }
     if (!$this->isExternalModule($request)) {
         return;
     }
     $header = $request->getHeader('Unica-Correlator');
     if ($header) {
         $this->trackingToken->setRequestToken(implode('-', array($this->trackingToken->getRequestToken(), $header)));
     } else {
         $header = $request->getHeader('transactioninfo');
         $output = $this->parseExternalHeaderRequest($header);
         if (isset($output['transactionid'])) {
             $this->trackingToken->setRequestToken(implode('-', array($this->trackingToken->getRequestToken(), $output['transactionid'])));
         }
     }
 }
Пример #18
0
 /**
  * Matches an array of mime types against the Accept header in a request.
  *
  * @param Zend_Controller_Request_Abstract $request            the request
  * @param array                            $supportedMimetypes The mime types to match against
  *
  * @return string
  */
 public static function matchMimetypeFromRequest(Zend_Controller_Request_Abstract $request, array $supportedMimetypes)
 {
     // get accept header
     $acceptHeader = strtolower($request->getHeader('Accept'));
     require_once 'Mimeparse.php';
     try {
         $match = @Mimeparse::best_match($supportedMimetypes, $acceptHeader);
     } catch (Exception $e) {
         $match = '';
     }
     return $match;
 }