public function indexAction($url)
 {
     $this->setNoRender();
     // let shindig do the rendering
     set_include_path(ENGINEBLOCK_FOLDER_SHINDIG . PATH_SEPARATOR . get_include_path());
     include_once 'src/common/Config.php';
     include_once 'src/common/File.php';
     // You can't inject a Config, so force it to try loading
     // and ignore errors from config file not being there :(
     global $shindigConfig;
     $shindigConfig = array();
     @Config::setConfig(array('allow_plaintext_token' => true, 'person_service' => 'EngineBlock_Shindig_DataService', 'activity_service' => 'EngineBlock_Shindig_DataService', 'group_service' => 'EngineBlock_Shindig_DataService'));
     spl_autoload_register(array(get_class($this), 'shindigAutoLoad'));
     // Shindig expects urls to be moiunted on /social/rest so we enforce that.
     $_SERVER['REQUEST_URI'] = '/social/rest/' . $url;
     // We only support JSON
     $_SERVER['CONTENT_TYPE'] = 'application/json';
     // Shindig wants a security token, but interface F in coin is auth-less so we fake one.
     $_REQUEST["st"] = $_GET["st"] = $_POST["st"] = "o:v:a:d:u:m:c";
     $requestMethod = EngineBlock_ApplicationSingleton::getInstance()->getHttpRequest()->getMethod();
     $methodName = 'do' . ucfirst(strtolower($requestMethod));
     $servletInstance = new DataServiceServlet();
     if (is_callable(array($servletInstance, $methodName))) {
         $servletInstance->{$methodName}();
     } else {
         echo "Invalid method";
         // @todo Error out
     }
 }
 /**
  * Handle the forwarding of the user to the proper IdP0 after the WAYF screen.
  *
  * @param string $serviceName
  * @throws EngineBlock_Corto_Module_Services_Exception
  * @throws EngineBlock_Exception
  * @throws EngineBlock_Corto_Module_Services_SessionLostException
  */
 public function serve($serviceName)
 {
     $selectedIdp = urldecode($_REQUEST['idp']);
     if (!$selectedIdp) {
         throw new EngineBlock_Corto_Module_Services_Exception('No IdP selected after WAYF');
     }
     // Retrieve the request from the session.
     $id = $_POST['ID'];
     if (!$id) {
         throw new EngineBlock_Exception('Missing ID for AuthnRequest after WAYF', EngineBlock_Exception::CODE_NOTICE);
     }
     $authnRequestRepository = new EngineBlock_Saml2_AuthnRequestSessionRepository($this->_server->getSessionLog());
     $request = $authnRequestRepository->findRequestById($id);
     if (!$request) {
         throw new EngineBlock_Corto_Module_Services_SessionLostException('Session lost after WAYF');
     }
     // Flush log if SP or IdP has additional logging enabled
     $sp = $this->_server->getRepository()->fetchServiceProviderByEntityId($request->getIssuer());
     $idp = $this->_server->getRepository()->fetchIdentityProviderByEntityId($selectedIdp);
     if (EngineBlock_SamlHelper::doRemoteEntitiesRequireAdditionalLogging(array($sp, $idp))) {
         $application = EngineBlock_ApplicationSingleton::getInstance();
         $application->flushLog('Activated additional logging for the SP or IdP');
         $log = $application->getLogInstance();
         $log->info('Raw HTTP request', array('http_request' => (string) $application->getHttpRequest()));
     }
     $this->_server->sendAuthenticationRequest($request, $selectedIdp);
 }
 public function metadataAction()
 {
     $this->setNoRender();
     $request = EngineBlock_ApplicationSingleton::getInstance()->getHttpRequest();
     $entityId = $request->getQueryParameter("entityid");
     $gadgetUrl = $request->getQueryParameter('gadgeturl');
     // If we were only handed a gadget url, no entity id, lookup the Service Provider entity id
     if ($gadgetUrl && !$entityId) {
         $identifiers = $this->_getRegistry()->findIdentifiersByMetadata('coin:gadgetbaseurl', $gadgetUrl);
         if (count($identifiers) > 1) {
             EngineBlock_ApplicationSingleton::getLog()->warn("Multiple identifiers found for gadgetbaseurl: '{$gadgetUrl}'");
             throw new EngineBlock_Exception('Multiple identifiers found for gadgetbaseurl');
         }
         if (count($identifiers) === 0) {
             EngineBlock_ApplicationSingleton::getInstance()->getLog()->warn("No Entity Id found for gadgetbaseurl '{$gadgetUrl}'");
             $this->_getResponse()->setHeader('Content-Type', 'application/json');
             $this->_getResponse()->setBody(json_encode(new stdClass()));
             return;
         }
         $entityId = $identifiers[0];
     }
     if (!$entityId) {
         throw new EngineBlock_Exception('No entity id provided to get metadata for?!');
     }
     if (isset($_REQUEST["keys"])) {
         $result = $this->_getRegistry()->getMetaDataForKeys($entityId, explode(",", $_REQUEST["keys"]));
     } else {
         $result = $this->_getRegistry()->getMetadata($entityId);
     }
     $result['entityId'] = $entityId;
     $this->_getResponse()->setHeader('Content-Type', 'application/json');
     $this->_getResponse()->setBody(json_encode($result));
 }
 /**
  * Validate the license information
  *
  * @param string $userId
  * @param array $spMetadata
  * @param array $idpMetadata
  * @return string
  */
 public function validate($userId, array $spMetadata, array $idpMetadata)
 {
     if (!$this->_active) {
         return EngineBlock_LicenseEngine_ValidationManager::LICENSE_UNKNOWN;
     }
     $client = new Zend_Http_Client($this->_url);
     $client->setConfig(array('timeout' => 15));
     try {
         $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, 'application/json; charset=utf-8')->setParameterGet('userId', urlencode($userId))->setParameterGet('serviceProviderEntityId', urlencode($spMetadata['EntityId']))->setParameterGet('identityProviderEntityId', urlencode($idpMetadata['EntityId']))->request('GET');
         $body = $client->getLastResponse()->getBody();
         $response = json_decode($body, true);
         $status = $response['status'];
     } catch (Exception $exception) {
         $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo($userId, $idpMetadata['EntityId'], $spMetadata['EntityId'], $exception->getTraceAsString());
         EngineBlock_ApplicationSingleton::getLog()->error("Could not connect to License Manager" . $exception->getMessage(), $additionalInfo);
         return EngineBlock_LicenseEngine_ValidationManager::LICENSE_UNKNOWN;
     }
     if ($status['returnUrl']) {
         $currentResponse = EngineBlock_ApplicationSingleton::getInstance()->getHttpResponse();
         $currentResponse->setRedirectUrl($status['returnUrl']);
         $currentResponse->send();
         exit;
     } else {
         if ($status['licenseStatus']) {
             return $status['licenseStatus'];
         } else {
             return EngineBlock_LicenseEngine_ValidationManager::LICENSE_UNKNOWN;
         }
     }
 }
 protected function _getAccessToken($conf, $subjectId, $requireNew)
 {
     $cache = EngineBlock_ApplicationSingleton::getInstance()->getDiContainer()->getApplicationCache();
     if (!$requireNew && $cache instanceof Zend_Cache_Backend_Apc) {
         $accessToken = $cache->load(self::ACCESS_TOKEN_KEY);
         if ($accessToken) {
             return $accessToken;
         }
     }
     // for example https://api.dev.surfconext.nl/v1/oauth2/token
     $baseUrl = $this->_ensureTrailingSlash($conf->baseUrl) . 'v1/oauth2/token';
     $client = new Zend_Http_Client($baseUrl);
     try {
         $response = $client->setConfig(array('timeout' => 15))->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED)->setAuth($conf->key, $conf->secret)->setParameterPost('grant_type', 'client_credentials')->request(Zend_Http_Client::POST);
         $result = json_decode($response->getBody(), true);
         if (isset($result['access_token'])) {
             $accessToken = $result['access_token'];
             if ($cache instanceof Zend_Cache_Backend_Apc) {
                 $cache->save($accessToken, self::ACCESS_TOKEN_KEY);
             }
             return $accessToken;
         }
         throw new EngineBlock_VirtualOrganization_AccessTokenNotGrantedException('AccessToken not granted for EB as SP. Check SR and the Group Provider endpoint log.');
     } catch (Exception $exception) {
         $additionalInfo = EngineBlock_Log_Message_AdditionalInfo::create()->setUserId($subjectId)->setDetails($exception->getTraceAsString());
         EngineBlock_ApplicationSingleton::getLog()->error("Error in connecting to API(s) for access token grant" . $exception->getMessage(), array('additional_info' => $additionalInfo->toArray()));
         throw new EngineBlock_VirtualOrganization_AccessTokenNotGrantedException('AccessToken not granted for EB as SP. Check SR and the Group Provider endpoint log', EngineBlock_Exception::CODE_ALERT, $exception);
     }
 }
 public function tearDown()
 {
     if (!$this->_originalConfig) {
         return true;
     }
     EngineBlock_ApplicationSingleton::getInstance()->setConfiguration($this->_originalConfig);
 }
 public function setup()
 {
     $this->proxyServerMock = $this->mockProxyServer();
     $diContainer = EngineBlock_ApplicationSingleton::getInstance()->getDiContainer();
     $this->xmlConverterMock = $this->mockXmlConverter($diContainer[EngineBlock_Application_DiContainer::XML_CONVERTER]);
     $this->consentFactoryMock = $diContainer[EngineBlock_Application_DiContainer::CONSENT_FACTORY];
     $this->consentMock = $this->mockConsent();
 }
 protected function _setIsMember()
 {
     if (!isset($this->_responseAttributes[static::URN_IS_MEMBER_OF])) {
         $this->_responseAttributes[static::URN_IS_MEMBER_OF] = array();
     }
     $configuration = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration();
     $this->_responseAttributes[static::URN_IS_MEMBER_OF][] = $configuration->addgueststatus->guestqualifier;
 }
Esempio n. 9
0
 public function displayAction($exception)
 {
     $this->_getResponse()->setStatus(500, 'Internal Server Error');
     $application = EngineBlock_ApplicationSingleton::getInstance();
     if ($application->getConfigurationValue('debug', false)) {
         $this->exception = $exception;
     }
 }
 protected function _getUserDirectory()
 {
     if ($this->_userDirectory == NULL) {
         $ldapConfig = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration()->ldap;
         $this->_userDirectory = new EngineBlock_UserDirectory($ldapConfig);
     }
     return $this->_userDirectory;
 }
 public function execute()
 {
     $metadataRepository = EngineBlock_ApplicationSingleton::getInstance()->getDiContainer()->getMetadataRepository();
     $allowedIdpEntityIds = $metadataRepository->findAllowedIdpEntityIdsForSp($this->_serviceProvider);
     if (!in_array($this->_identityProvider->entityId, $allowedIdpEntityIds)) {
         throw new EngineBlock_Corto_Exception_InvalidConnection("Disallowed response by SP configuration. " . "Response from IdP '{$this->_identityProvider->entityId}' to SP '{$this->_serviceProvider->entityId}'");
     }
 }
 public function indexAction()
 {
     $this->previewOnly = $this->_getRequest()->getQueryParameter('preview') ? true : false;
     $deprovisionEngine = new EngineBlock_Deprovisioning();
     $this->deprovisionPreview = $deprovisionEngine->deprovision($this->previewOnly);
     $this->deprovisionConfig = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration()->cron->deprovision;
     $this->_redirectToController("Index");
 }
 public function displayAction($exception)
 {
     header('HTTP/1.1 500 Internal Server Error', true, 500);
     $application = EngineBlock_ApplicationSingleton::getInstance();
     if ($application->getConfigurationValue('debug', false)) {
         $this->exception = $exception;
     }
 }
 public function testItAddsANonEmptyStringToTheRecord()
 {
     // Assert the log ID is bootstrapped.
     $logId = EngineBlock_ApplicationSingleton::getInstance()->getLogRequestId();
     $this->assertInternalType('string', $logId);
     $this->assertNotEmpty($logId);
     $processor = new EngineBlock_Log_Monolog_Processor_RequestIdProcessor();
     $record = $processor(array('extra' => array()));
     $this->assertEquals($logId, $record['extra']['request_id'], 'Appended log request ID and bootstrapped log request ID do not match');
 }
 public function execute()
 {
     if (!$this->_collabPersonId) {
         throw new EngineBlock_Corto_Filter_Command_Exception_PreconditionFailed('Missing collabPersonId');
     }
     $config = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration();
     $licenseEngine = new EngineBlock_LicenseEngine_ValidationManager($config);
     $licenseCode = $licenseEngine->validate($this->_collabPersonId, $this->_spMetadata, $this->_idpMetadata);
     $this->_responseAttributes[EngineBlock_LicenseEngine_ValidationManager::LICENSE_SAML_ATTRIBUTE] = array($licenseCode);
 }
 public function indexAction()
 {
     $this->setNoRender();
     $configuration = EngineBlock_ApplicationSingleton::getInstance()->getConfigurationValue('engineApi');
     if (!$configuration) {
         throw new EngineBlock_Exception('API access disabled');
     }
     if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
         header('WWW-Authenticate: Basic realm="EngineBlock API"');
         header('HTTP/1.1 401 Unauthorized');
         echo json_encode('Unauthenticated');
         exit;
     }
     if ($_SERVER['PHP_AUTH_USER'] !== $configuration->user) {
         header('WWW-Authenticate: Basic realm="EngineBlock API"');
         header('HTTP/1.1 401 Unauthorized');
         echo json_encode('Invalid credentials');
         exit;
     }
     if ($_SERVER['PHP_AUTH_PW'] !== $configuration->password) {
         header('WWW-Authenticate: Basic realm="EngineBlock API"');
         header('HTTP/1.1 401 Unauthorized');
         echo json_encode('Invalid credentials');
         exit;
     }
     if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
         header('HTTP/1.1 400 Bad Request');
         echo json_encode('Not a POST request');
         return;
     }
     ini_set('memory_limit', '265M');
     $body = $this->_getRequest()->getRawBody();
     if (!$body) {
         header('HTTP/1.1 400 Bad Request');
         echo json_encode('No body');
         exit;
     }
     $connections = json_decode($body);
     if (!$connections) {
         header('HTTP/1.1 400 Bad Request');
         echo json_encode('Unable to decode body as JSON');
         exit;
     }
     if (!is_object($connections) || !isset($connections->connections) && !is_object($connections->connections)) {
         header('HTTP/1.1 400 Bad Request');
         echo json_encode('Unrecognized structure for JSON');
         exit;
     }
     $assembler = new JanusPushMetadataAssembler();
     $roles = $assembler->assemble($connections->connections);
     $doctrineRepository = DoctrineMetadataRepository::createFromConfig(array(), EngineBlock_ApplicationSingleton::getInstance()->getDiContainer());
     $result = $doctrineRepository->synchronize($roles);
     echo json_encode($result);
 }
 /**
  * @param SAML2_Response $response
  * @param SimpleSAML_Configuration $idpConfig
  */
 private function addSigns(SAML2_Response $response, SimpleSAML_Configuration $idpConfig)
 {
     $assertions = $response->getAssertions();
     $className = EngineBlock_ApplicationSingleton::getInstance()->getDiContainer()->getMessageUtilClassName();
     // Special case the 'normal' message verification class name so we have IDE support.
     if ($className === 'sspmod_saml_Message') {
         sspmod_saml_Message::addSign($idpConfig, SimpleSAML_Configuration::loadFromArray(array()), $assertions[0]);
         return;
     }
     $className::addSign($idpConfig, SimpleSAML_Configuration::loadFromArray(array()), $assertions[0]);
 }
 protected function _sendIntroductionMail(array $attributes)
 {
     if (!isset($attributes['urn:mace:dir:attribute-def:mail'])) {
         return;
     }
     $config = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration();
     if (!isset($config->email->sendWelcomeMail) || !$config->email->sendWelcomeMail) {
         return;
     }
     $emailAddress = $attributes['urn:mace:dir:attribute-def:mail'][0];
     $this->_mailer->sendMail($emailAddress, EngineBlock_Corto_Module_Services::INTRODUCTION_EMAIL, array('{user}' => $this->_preferredNameAttributeFilter->getAttribute($attributes)));
 }
 public function processedAssertionAction()
 {
     $this->setNoRender();
     $application = EngineBlock_ApplicationSingleton::getInstance();
     try {
         $proxyServer = new EngineBlock_Corto_Adapter();
         $proxyServer->processedAssertionConsumer();
     } catch (EngineBlock_Corto_Exception_UserNotMember $e) {
         $application->getLogInstance()->warn('User not a member error');
         $application->getHttpResponse()->setRedirectUrl('/authentication/feedback/vomembershiprequired');
     }
 }
 /**
  * @throws EngineBlock_Corto_Exception_MissingRequiredFields
  */
 public function execute()
 {
     // ServiceRegistry override of SchacHomeOrganization, set it and skip validation
     $excluded = array();
     if ($this->_identityProvider->schacHomeOrganization) {
         $this->_responseAttributes[self::URN_MACE_TERENA_SCHACHOMEORG] = array($this->_identityProvider->schacHomeOrganization);
         $excluded[] = static::URN_MACE_TERENA_SCHACHOMEORG;
     }
     $validationResult = EngineBlock_ApplicationSingleton::getInstance()->getDiContainer()->getAttributeValidator()->validate($this->_responseAttributes, $excluded);
     if ($validationResult->hasErrors()) {
         throw new EngineBlock_Corto_Exception_MissingRequiredFields('Errors validating attributes' . ' errors: ' . print_r($validationResult->getErrors(), true) . ' attributes: ' . print_r($this->_responseAttributes, true));
     }
 }
 /**
  * Creates services objects with their own specific needs
  *
  * @param string $className
  * @param EngineBlock_Corto_ProxyServer $server
  * @return EngineBlock_Corto_Module_Service_Abstract
  */
 private function factoryService($className, EngineBlock_Corto_ProxyServer $server)
 {
     $diContainer = EngineBlock_ApplicationSingleton::getInstance()->getDiContainer();
     switch ($className) {
         case 'EngineBlock_Corto_Module_Service_ProvideConsent':
             return new EngineBlock_Corto_Module_Service_ProvideConsent($server, $diContainer[EngineBlock_Application_DiContainer::XML_CONVERTER], $diContainer[EngineBlock_Application_DiContainer::CONSENT_FACTORY]);
         case 'EngineBlock_Corto_Module_Service_ProcessConsent':
             $preferredNameAttributeFilter = new EngineBlock_User_PreferredNameAttributeFilter();
             return new EngineBlock_Corto_Module_Service_ProcessConsent($server, $diContainer[EngineBlock_Application_DiContainer::XML_CONVERTER], $diContainer[EngineBlock_Application_DiContainer::CONSENT_FACTORY], $diContainer[EngineBlock_Application_DiContainer::MAILER], $preferredNameAttributeFilter);
         default:
             return new $className($server, $diContainer[EngineBlock_Application_DiContainer::XML_CONVERTER]);
     }
 }
 public function mapTo(array $rootElement)
 {
     $publication = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration()->edugain->publication;
     if (!isset($rootElement['md:Extensions'])) {
         $rootElement['md:Extensions'] = array(EngineBlock_Corto_XmlToArray::ATTRIBUTE_PFX . "xmlns:mdrpi" => "urn:oasis:names:tc:SAML:metadata:rpi");
     }
     if (!isset($rootElement['md:Extensions']['mdrpi:PublicationInfo'])) {
         $publicationInfo = array(EngineBlock_Corto_XmlToArray::ATTRIBUTE_PFX . "creationInstant" => date(DateTime::W3C), EngineBlock_Corto_XmlToArray::ATTRIBUTE_PFX . "publisher" => $publication->publisher);
         $publicationInfo['mdrpi:UsagePolicy'] = array(array(EngineBlock_Corto_XmlToArray::ATTRIBUTE_PFX . 'xml:lang' => "en", EngineBlock_Corto_XmlToArray::VALUE_PFX => $publication->policy));
         $rootElement['md:Extensions']['mdrpi:PublicationInfo'] = array($publicationInfo);
     }
     return $rootElement;
 }
 protected function _handleDispatchException(Exception $e)
 {
     $application = EngineBlock_ApplicationSingleton::getInstance();
     $application->reportError($e);
     if (!$this->_useErrorHandling) {
         throw $e;
     } else {
         $errorConfiguration = $application->getConfiguration()->error;
         $module = $errorConfiguration->module;
         $controllerName = $errorConfiguration->controller;
         $action = $errorConfiguration->action;
         $controllerInstance = $this->_getControllerInstance($module, $controllerName);
         $controllerInstance->handleAction($action, array($e));
     }
 }
 public function execute()
 {
     $userDirectory = EngineBlock_ApplicationSingleton::getInstance()->getDiContainer()->getUserDirectory();
     $user = $userDirectory->registerUser($this->_responseAttributes);
     $subjectIdField = EngineBlock_ApplicationSingleton::getInstance()->getConfigurationValue('subjectIdAttribute', EngineBlock_UserDirectory::LDAP_ATTR_COLLAB_PERSON_ID);
     if (empty($user[$subjectIdField])) {
         throw new EngineBlock_Exception("SubjectIdField '{$subjectIdField}' does not contain data for user: " . var_export($user, true));
     }
     $subjectId = $user[$subjectIdField];
     $this->setCollabPersonId($subjectId);
     $this->_response->setCollabPersonId($subjectId);
     $this->_response->setOriginalNameId($this->_response->getAssertion()->getNameId());
     // Adjust the NameID in the OLD response (for consent), set the collab:person uid
     $this->_response->getAssertion()->setNameId(array('Value' => $subjectId, 'Format' => SAML2_Const::NAMEID_PERSISTENT));
 }
 protected function _sendAttributeSupportMail()
 {
     $normalizer = new EngineBlock_Attributes_Normalizer($this->attributes);
     $normalizedAttributes = $normalizer->normalize();
     $email = EngineBlock_ApplicationSingleton::getInstance()->getConfigurationValue('email')->help;
     $nameId = $normalizedAttributes['nameid'][0];
     $view = $this->_getView();
     $view->setData(array('metadata' => EngineBlock_ApplicationSingleton::getInstance()->getDiContainer()->getAttributeMetadata(), 'userAttributes' => $normalizedAttributes, 'lang' => $view->language()));
     $body = $view->render(ENGINEBLOCK_FOLDER_MODULES . '/Profile/View/AttributeSupport/ProfileMail.phtml', false);
     $mailer = new Zend_Mail('UTF-8');
     $mailer->setFrom($email);
     $mailer->addTo($email);
     $mailer->setSubject(sprintf("Personal debug info of %s", $nameId));
     $mailer->setBodyHtml($body);
     $mailer->send();
 }
Esempio n. 26
0
 public function processedAssertionAction()
 {
     $this->setNoRender();
     $application = EngineBlock_ApplicationSingleton::getInstance();
     try {
         $proxyServer = new EngineBlock_Corto_Adapter();
         $proxyServer->processedAssertionConsumer();
     } catch (EngineBlock_Corto_Exception_UserNotMember $e) {
         $application->getLogInstance()->notice("VO membership required", array('exception' => $e));
         $application->handleExceptionWithFeedback($e, '/authentication/feedback/vomembershiprequired');
     } catch (EngineBlock_Attributes_Manipulator_CustomException $e) {
         $application->getLogInstance()->notice("Custom attribute manipulator exception", array('exception' => $e));
         $_SESSION['feedback_custom'] = $e->getFeedback();
         $application->handleExceptionWithFeedback($e, '/authentication/feedback/custom');
     }
 }
 public function trackLogin($spEntityMetadata, $idpEntityMetadata, $subjectId, $voContext)
 {
     $request = EngineBlock_ApplicationSingleton::getInstance()->getInstance()->getHttpRequest();
     $db = $this->_getDbConnection();
     $stmt = $db->prepare("\n            INSERT INTO log_logins (loginstamp, userid , spentityid , spentityname , idpentityid , idpentityname, useragent, voname)\n            VALUES                 (now()     , :userid, :spentityid, :spentityname, :idpentityid, :idpentityname, :useragent, :voname)");
     $spEntityName = isset($spEntityMetadata['Name']['en']) ? $spEntityMetadata['Name']['en'] : $spEntityMetadata['EntityId'];
     $idpEntityName = isset($idpEntityMetadata['Name']['en']) ? $idpEntityMetadata['Name']['en'] : $idpEntityMetadata['EntityId'];
     $stmt->bindParam('userid', $subjectId);
     $stmt->bindParam('spentityid', $spEntityMetadata['EntityId']);
     $stmt->bindParam('spentityname', $spEntityName);
     $stmt->bindParam('idpentityid', $idpEntityMetadata['EntityId']);
     $stmt->bindParam('idpentityname', $idpEntityName);
     $stmt->bindParam('useragent', $request->getHeader('User-Agent'));
     $stmt->bindParam('voname', $voContext);
     $stmt->execute();
 }
 public function serve($serviceName)
 {
     $receivedResponse = $this->_server->getBindingsModule()->receiveResponse();
     $receivedRequest = $this->_server->getReceivedRequestFromResponse($receivedResponse);
     $sp = $this->_server->getRepository()->fetchServiceProviderByEntityId($receivedRequest->getIssuer());
     // Verify the SP requester chain.
     EngineBlock_SamlHelper::getSpRequesterChain($sp, $receivedRequest, $this->_server->getRepository());
     // Flush log if SP or IdP has additional logging enabled
     $idp = $this->_server->getRepository()->fetchIdentityProviderByEntityId($receivedResponse->getIssuer());
     if (EngineBlock_SamlHelper::doRemoteEntitiesRequireAdditionalLogging(array($sp, $idp))) {
         $application = EngineBlock_ApplicationSingleton::getInstance();
         $application->flushLog('Activated additional logging for the SP or IdP');
         $log = $application->getLogInstance();
         $log->info('Raw HTTP request', array('http_request' => (string) $application->getHttpRequest()));
     }
     if ($receivedRequest->isDebugRequest()) {
         $_SESSION['debugIdpResponse'] = $receivedResponse;
         $this->_server->redirect($this->_server->getUrl('debugSingleSignOnService'), 'Show original Response from IDP');
         return;
     }
     if ($receivedRequest->getKeyId()) {
         $this->_server->setKeyId($receivedRequest->getKeyId());
     }
     // Cache the response
     EngineBlock_Corto_Model_Response_Cache::cacheResponse($receivedRequest, $receivedResponse, EngineBlock_Corto_Model_Response_Cache::RESPONSE_CACHE_TYPE_IN);
     $this->_server->filterInputAssertionAttributes($receivedResponse, $receivedRequest);
     $processingEntities = $this->_server->getConfig('Processing', array());
     if (!empty($processingEntities)) {
         /** @var AbstractRole $firstProcessingEntity */
         $firstProcessingEntity = array_shift($processingEntities);
         $_SESSION['Processing'][$receivedRequest->getId()]['RemainingEntities'] = $processingEntities;
         $_SESSION['Processing'][$receivedRequest->getId()]['OriginalDestination'] = $receivedResponse->getDestination();
         $_SESSION['Processing'][$receivedRequest->getId()]['OriginalIssuer'] = $receivedResponse->getOriginalIssuer();
         $_SESSION['Processing'][$receivedRequest->getId()]['OriginalBinding'] = $receivedResponse->getOriginalBinding();
         $this->_server->setProcessingMode();
         $newResponse = $this->_server->createEnhancedResponse($receivedRequest, $receivedResponse);
         // Change the destiny of the received response
         $newResponse->setInResponseTo($receivedResponse->getInResponseTo());
         $newResponse->setDestination($firstProcessingEntity->responseProcessingService->location);
         $newResponse->setDeliverByBinding($firstProcessingEntity->responseProcessingService->binding);
         $newResponse->setReturn($this->_server->getUrl('processedAssertionConsumerService'));
         $this->_server->getBindingsModule()->send($newResponse, $firstProcessingEntity);
     } else {
         $newResponse = $this->_server->createEnhancedResponse($receivedRequest, $receivedResponse);
         $this->_server->sendResponseToRequestIssuer($receivedRequest, $newResponse);
     }
 }
 /**
  * @return Zend_Cache_Frontend_Function
  */
 protected function _getCacheFrontend()
 {
     $application = EngineBlock_ApplicationSingleton::getInstance();
     $serviceRegistryConfig = $application->getConfiguration()->serviceRegistry;
     if (!isset($serviceRegistryConfig->caching)) {
         return null;
     }
     $cachingConfiguration = $serviceRegistryConfig->caching;
     $backendCaching = $cachingConfiguration->backend->get('name', 'File');
     $backendCachingOptions = $cachingConfiguration->backend->options->toArray();
     if (isset($backendCachingOptions['file_name_prefix'])) {
         $backendCachingOptions['file_name_prefix'] .= '_' . str_replace($application->getApplicationEnvironmentId(), '.', '_');
     }
     $cache = Zend_Cache::factory('Function', $backendCaching, array(), $backendCachingOptions);
     $cache->setLifetime($cachingConfiguration->get('lifetime', self::DEFAULT_LIFETIME));
     return $cache;
 }
 protected function getConfig($filename = null)
 {
     $engineBlock = EngineBlock_ApplicationSingleton::getInstance();
     $engineBlock->bootstrap();
     $ebConfig = $engineBlock->getConfiguration();
     $masterDbConfigName = $ebConfig->database->masters->get(0);
     $dbConfig = $ebConfig->database->get($masterDbConfigName);
     $dsnParsed = parse_url($dbConfig->dsn);
     $dsnPathParts = explode(';', $dsnParsed['path']);
     $dsnProperties = array();
     foreach ($dsnPathParts as $dsnPathPart) {
         $dsnPathPart = explode('=', $dsnPathPart);
         $dsnProperties[array_shift($dsnPathPart)] = implode($dsnPathPart, '=');
     }
     $config = array('db' => array('adapter' => $this->_convertPdoDriverToZendDbAdapter($dsnParsed['scheme']), 'params' => array('host' => $dsnProperties['host'], 'username' => $dbConfig->user, 'password' => $dbConfig->password, 'dbname' => $dsnProperties['dbname'])), 'patch_directory' => realpath(__DIR__ . '/../../../../database/patch'), 'color' => true);
     return new Zend_Config($config);
 }