/**
  * authenticate and store result in session to avoid sending any request
  * twice. The SSL handshake for SNOM 320 takes very long
  */
 protected function _authenticate()
 {
     if (Tinebase_Session::isStarted()) {
         $snomSession = Phone_Session::getSessionNamespace();
         if (isset($snomSession->phoneIsAuthenticated)) {
             return;
         }
     }
     parent::_authenticate();
     if (!Tinebase_Session::isStarted()) {
         Tinebase_Core::startCoreSession();
     }
     $snomSession = Phone_Session::getSessionNamespace();
     $snomSession->phoneIsAuthenticated = 1;
 }
 /**
  * destroy session
  *
  * @return array
  */
 public function logout()
 {
     Tinebase_Controller::getInstance()->logout($_SERVER['REMOTE_ADDR']);
     Tinebase_Auth_CredentialCache::getInstance()->getCacheAdapter()->resetCache();
     if (Tinebase_Session::isStarted()) {
         Tinebase_Session::destroyAndRemoveCookie();
     }
     $result = array('success' => true);
     return $result;
 }
 /**
  * return current session id
  *
  * @param boolean $generateUid
  * @return mixed|null
  */
 public static function getSessionId($generateUid = true)
 {
     if (!self::isRegistered(self::SESSIONID)) {
         $sessionId = null;
         // TODO allow to access Tinebase/Core methods with Setup session and remove this workaround
         if (Tinebase_Session::isStarted() && !Tinebase_Session::isSetupSession()) {
             $sessionId = Tinebase_Session::getId();
         }
         if (empty($sessionId)) {
             $sessionId = 'NOSESSION';
             if ($generateUid) {
                 $sessionId .= Tinebase_Record_Abstract::generateUID(31);
             }
         }
         self::set(self::SESSIONID, $sessionId);
     }
     return self::get(self::SESSIONID);
 }
 /**
  * authenticate user
  *
  * @param string $_username
  * @param string $_password
  * @return Zend_Auth_Result
  */
 public function authenticate($_username, $_password)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Trying to authenticate ' . $_username);
     }
     try {
         $this->_backend->setIdentity($_username);
     } catch (Zend_Auth_Adapter_Exception $zaae) {
         return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, $_username, array($zaae->getMessage()));
     }
     $this->_backend->setCredential($_password);
     if (Tinebase_Session::isStarted()) {
         Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_Session());
     } else {
         Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_NonPersistent());
     }
     $result = Zend_Auth::getInstance()->authenticate($this->_backend);
     return $result;
 }
 /**
  * Gets Tinebase User session namespace
  *
  * @throws Zend_Session_Exception
  * @return Zend_Session_Namespace
  */
 public static function getSessionNamespace()
 {
     if (!Tinebase_Session::isStarted()) {
         throw new Zend_Session_Exception('Session not started');
     }
     if (!self::getSessionEnabled()) {
         throw new Zend_Session_Exception('Session not enabled for request');
     }
     try {
         return self::_getSessionNamespace(static::NAMESPACE_NAME);
     } catch (Exception $e) {
         Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Session error: ' . $e->getMessage());
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $e->getTraceAsString());
         throw $e;
     }
 }
 /**
  * Gets Tinebase User session namespace
  *
  * @param string $sessionNamespace (optional)
  * @throws Zend_Session_Exception
  * @return Zend_Session_Namespace
  */
 public static function getSessionNamespace($sessionNamespace = 'Default')
 {
     if (!Tinebase_Session::isStarted()) {
         throw new Zend_Session_Exception('Session not started');
     }
     if (!self::getSessionEnabled()) {
         throw new Zend_Session_Exception('Session not enabled for request');
     }
     $sessionNamespace = is_null($sessionNamespace) ? get_called_class() . '_Namespace' : $sessionNamespace;
     try {
         return self::_getSessionNamespace($sessionNamespace);
     } catch (Exception $e) {
         Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Session error: ' . $e->getMessage());
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $e->getTraceAsString());
         throw $e;
     }
 }
 /**
  * handler for JSON api requests
  * @todo session expire handling
  * 
  * @param $request
  * @return JSON
  */
 protected function _handle($request)
 {
     try {
         $method = $request->getMethod();
         Tinebase_Core::getLogger()->INFO(__METHOD__ . '::' . __LINE__ . ' is JSON request. method: ' . $method);
         $jsonKey = isset($_SERVER['HTTP_X_TINE20_JSONKEY']) ? $_SERVER['HTTP_X_TINE20_JSONKEY'] : '';
         $this->_checkJsonKey($method, $jsonKey);
         if (empty($method)) {
             // SMD request
             return self::getServiceMap();
         }
         $this->_methods[] = $method;
         $classes = array();
         // add json apis which require no auth
         $classes['Tinebase_Frontend_Json'] = 'Tinebase';
         // register additional Json apis only available for authorised users
         if (Tinebase_Session::isStarted() && Zend_Auth::getInstance()->hasIdentity()) {
             $applicationParts = explode('.', $method);
             $applicationName = ucfirst($applicationParts[0]);
             switch ($applicationName) {
                 // additional Tinebase json apis
                 case 'Tinebase_Container':
                     $classes['Tinebase_Frontend_Json_Container'] = 'Tinebase_Container';
                     break;
                 case 'Tinebase_PersistentFilter':
                     $classes['Tinebase_Frontend_Json_PersistentFilter'] = 'Tinebase_PersistentFilter';
                     break;
                 default:
                     if (Tinebase_Core::getUser() && Tinebase_Core::getUser()->hasRight($applicationName, Tinebase_Acl_Rights_Abstract::RUN)) {
                         $classes[$applicationName . '_Frontend_Json'] = $applicationName;
                     }
                     break;
             }
         }
         $server = self::_getServer($classes);
         $response = $server->handle($request);
         if ($response->isError()) {
             Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' Got response error: ' . print_r($response->getError()->toArray(), true));
         }
         return $response;
     } catch (Exception $exception) {
         return $this->_handleException($request, $exception);
     }
 }
 /**
  * (non-PHPdoc)
  * @see Tinebase_Server_Interface::handle()
  */
 public function handle(\Zend\Http\Request $request = null, $body = null)
 {
     $this->_request = $request instanceof \Zend\Http\Request ? $request : Tinebase_Core::get(Tinebase_Core::REQUEST);
     $this->_body = $body !== null ? $body : fopen('php://input', 'r');
     $server = new Tinebase_Http_Server();
     $server->setClass('Tinebase_Frontend_Http', 'Tinebase');
     $server->setClass('Filemanager_Frontend_Download', 'Download');
     try {
         if (Tinebase_Session::sessionExists()) {
             try {
                 Tinebase_Core::startCoreSession();
             } catch (Zend_Session_Exception $zse) {
                 // expire session cookie for client
                 Tinebase_Session::expireSessionCookie();
             }
         }
         Tinebase_Core::initFramework();
         if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
             Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Is HTTP request. method: ' . $this->getRequestMethod());
         }
         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' REQUEST: ' . print_r($_REQUEST, TRUE));
         }
         // register additional HTTP apis only available for authorised users
         if (Tinebase_Session::isStarted() && Zend_Auth::getInstance()->hasIdentity()) {
             if (empty($_REQUEST['method'])) {
                 $_REQUEST['method'] = 'Tinebase.mainScreen';
             }
             $applicationParts = explode('.', $this->getRequestMethod());
             $applicationName = ucfirst($applicationParts[0]);
             if (Tinebase_Core::getUser() && Tinebase_Core::getUser()->hasRight($applicationName, Tinebase_Acl_Rights_Abstract::RUN)) {
                 try {
                     $server->setClass($applicationName . '_Frontend_Http', $applicationName);
                 } catch (Exception $e) {
                     Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . " Failed to add HTTP API for application '{$applicationName}' Exception: \n" . $e);
                 }
             }
         } else {
             if (empty($_REQUEST['method'])) {
                 $_REQUEST['method'] = 'Tinebase.login';
             }
             // sessionId got send by client, but we don't use sessions for non authenticated users
             if (Tinebase_Session::sessionExists()) {
                 // expire session cookie on client
                 Tinebase_Session::expireSessionCookie();
             }
         }
         $this->_method = $this->getRequestMethod();
         $server->handle($_REQUEST);
     } catch (Zend_Json_Server_Exception $zjse) {
         // invalid method requested or not authenticated, etc.
         Tinebase_Exception::log($zjse);
         Tinebase_Core::getLogger()->INFO(__METHOD__ . '::' . __LINE__ . ' Attempt to request a privileged Http-API method without valid session from "' . $_SERVER['REMOTE_ADDR']);
         header('HTTP/1.0 403 Forbidden');
         exit;
     } catch (Exception $exception) {
         Tinebase_Exception::log($exception, false);
         try {
             $setupController = Setup_Controller::getInstance();
             if ($setupController->setupRequired()) {
                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Setup required');
                 }
                 $this->_method = 'Tinebase.setupRequired';
             } else {
                 if (preg_match('/download|export/', $this->_method)) {
                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Server error during download/export - exit with 500');
                     }
                     header('HTTP/1.0 500 Internal Server Error');
                     exit;
                 } else {
                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Show mainscreen with setup exception');
                     }
                     $this->_method = 'Tinebase.exception';
                 }
             }
             $server->handle(array('method' => $this->_method));
         } catch (Exception $e) {
             header('HTTP/1.0 503 Service Unavailable');
             die('Service Unavailable');
         }
     }
 }