/**
  * the singleton pattern
  *
  * @return Tinebase_Controller
  */
 public static function getInstance()
 {
     if (self::$_instance === NULL) {
         self::$_instance = new Tinebase_Controller();
     }
     return self::$_instance;
 }
Пример #2
0
 /**
  * handler for command line scripts
  * 
  * @return boolean
  */
 public function handle()
 {
     Tinebase_Core::initFramework();
     #if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ .' is Asterisk curl request: ' . print_r($_REQUEST, true));
     if (Tinebase_Controller::getInstance()->login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $_SERVER['REMOTE_ADDR'], 'TineAsterisk') === true) {
         $server = new Tinebase_Http_Server();
         $server->setClass('Voipmanager_Frontend_Asterisk_SipPeers', 'Voipmanager_SipPeers');
         $server->setClass('Voipmanager_Frontend_Asterisk_SipRegs', 'Voipmanager_SipRegs');
         $server->setClass('Voipmanager_Frontend_Asterisk_CallForward', 'Voipmanager_CallForward');
         $server->setClass('Voipmanager_Frontend_Asterisk_MeetMe', 'Voipmanager_MeetMe');
         list($class, $method) = explode('.', $_REQUEST['method']);
         // ugly hack to parse requests from res_config_curl
         if ($method == 'handleResConfig') {
             // set method to a usefull value
             $pos = strpos($_REQUEST['action'], '?');
             if ($pos !== false) {
                 $action = substr($_REQUEST['action'], 0, $pos);
                 list($key, $value) = explode('=', substr($_REQUEST['action'], $pos + 1));
                 $_REQUEST[$key] = $value;
             } else {
                 $action = $_REQUEST['action'];
             }
             #if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ .' action: ' . $action);
             $method = ucfirst(substr($action, 1));
             $_REQUEST['method'] = $class . '.handle' . $method;
         }
         #if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ .' action: ' . print_r($_REQUEST, true));
         $server->handle($_REQUEST);
         Tinebase_Controller::getInstance()->logout($_SERVER['REMOTE_ADDR']);
     } else {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' auth failed ');
         }
     }
 }
Пример #3
0
 public function handle()
 {
     try {
         Tinebase_Core::initFramework();
     } catch (Zend_Session_Exception $exception) {
         if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) {
             Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' invalid session. Delete session cookie.');
         }
         Zend_Session::expireSessionCookie();
         header('WWW-Authenticate: Basic realm="WebDAV for Tine 2.0"');
         header('HTTP/1.1 401 Unauthorized');
         return;
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' is CalDav, CardDAV or WebDAV request.');
     }
     if (empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['REMOTE_USER']) && empty($_SERVER['REDIRECT_REMOTE_USER'])) {
         header('WWW-Authenticate: Basic realm="WebDav for Tine 2.0"');
         header('HTTP/1.1 401 Unauthorized');
         return;
     }
     // when used with (f)cgi no PHP_AUTH variables are available without defining a special rewrite rule
     if (!isset($_SERVER['PHP_AUTH_USER'])) {
         // $_SERVER["REMOTE_USER"] == "Basic didhfiefdhfu4fjfjdsa34drsdfterrde..."
         $basicAuthData = base64_decode(substr(isset($_SERVER["REMOTE_USER"]) ? $_SERVER["REMOTE_USER"] : $_SERVER['REDIRECT_REMOTE_USER'], 6));
         list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(":", $basicAuthData);
     }
     if (Tinebase_Controller::getInstance()->login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $_SERVER['REMOTE_ADDR'], 'TineWebDav') !== true) {
         header('WWW-Authenticate: Basic realm="CardDav for Tine 2.0"');
         header('HTTP/1.1 401 Unauthorized');
         return;
     }
     self::$_server = new Sabre_DAV_Server(new Tinebase_WebDav_Root());
     // compute base uri
     $request = new Zend_Controller_Request_Http();
     self::$_server->setBaseUri($request->getBaseUrl() . '/');
     $tempDir = Tinebase_Core::getTempDir();
     if (!empty($tempDir)) {
         $lockBackend = new Sabre_DAV_Locks_Backend_File($tempDir . '/webdav.lock');
         $lockPlugin = new Sabre_DAV_Locks_Plugin($lockBackend);
         self::$_server->addPlugin($lockPlugin);
     }
     $authPlugin = new Sabre_DAV_Auth_Plugin(new Tinebase_WebDav_Auth(), null);
     self::$_server->addPlugin($authPlugin);
     $aclPlugin = new Sabre_DAVACL_Plugin();
     $aclPlugin->defaultUsernamePath = 'principals/users';
     $aclPlugin->principalCollectionSet = array($aclPlugin->defaultUsernamePath);
     self::$_server->addPlugin($aclPlugin);
     self::$_server->addPlugin(new Sabre_CardDAV_Plugin());
     self::$_server->addPlugin(new Sabre_CalDAV_Plugin());
     self::$_server->addPlugin(new Sabre_CalDAV_Schedule_Plugin());
     self::$_server->addPlugin(new Sabre_DAV_Browser_Plugin());
     self::$_server->exec();
 }
 /**
  * testCleanupCache
  */
 public function testCleanupCache()
 {
     $this->_instance->cleanupCache(Zend_Cache::CLEANING_MODE_ALL);
     $cache = Tinebase_Core::getCache();
     $oldLifetime = $cache->getOption('lifetime');
     $cache->setLifetime(1);
     $cacheId = Tinebase_Helper::convertCacheId('testCleanupCache');
     $cache->save('value', $cacheId);
     sleep(3);
     // cleanup with CLEANING_MODE_OLD
     $this->_instance->cleanupCache();
     $cache->setLifetime($oldLifetime);
     $this->assertFalse($cache->load($cacheId));
     // check for cache files
     $config = Tinebase_Core::getConfig();
     if ($config->caching && $config->caching->backend == 'File' && $config->caching->path) {
         $cacheFile = $this->_lookForCacheFile($config->caching->path);
         $this->assertEquals(NULL, $cacheFile, 'found cache file: ' . $cacheFile);
     }
 }
 /**
  * (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');
     Tinebase_Core::initFramework();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' is Asterisk curl request: ' . print_r($_REQUEST, true));
     }
     if (Tinebase_Controller::getInstance()->login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $this->_request, self::REQUEST_TYPE) === true) {
         $server = new Tinebase_Http_Server();
         $server->setClass('Voipmanager_Frontend_Asterisk_SipPeers', 'Voipmanager_SipPeers');
         $server->setClass('Voipmanager_Frontend_Asterisk_SipRegs', 'Voipmanager_SipRegs');
         $server->setClass('Voipmanager_Frontend_Asterisk_CallForward', 'Voipmanager_CallForward');
         $server->setClass('Voipmanager_Frontend_Asterisk_MeetMe', 'Voipmanager_MeetMe');
         $_REQUEST['method'] = $this->getRequestMethod();
         $server->handle($_REQUEST);
         Tinebase_Controller::getInstance()->logout($_SERVER['REMOTE_ADDR']);
     } else {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' auth failed ');
         }
     }
 }
 /**
  * Verify if OpenID with given $id exists and has specified $password
  *
  * @param  string  $id        user identity URL
  * @param  string  $password  the Tine 2.0 password
  * @param  string  $username  the Tine 2.0 username
  * @return bool
  */
 public function checkUser($id, $password, $username = null)
 {
     // strip of everything before last /
     $localPart = substr(strrchr($id, '/'), 1);
     if (empty($localPart)) {
         Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . " invalid id: {$id} supplied");
         return false;
     }
     Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " localPart: {$localPart}");
     try {
         $account = $this->_getAccountForId($id);
     } catch (Tinebase_Exception_NotFound $tenf) {
         return false;
     }
     $authResult = Tinebase_Controller::getInstance()->authenticate($account->accountLoginName, $password, $_SERVER['REMOTE_ADDR'], 'OpenId');
     if ($authResult !== true) {
         Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . " authentication for {$id} failed");
         return false;
     }
     return true;
 }
    /**
     * @group ServerTests
     */
    public function testAccountBlocking()
    {
        Zend_Session::$_unitTestEnabled = true;
        $request = \Zend\Http\PhpEnvironment\Request::fromString(<<<EOS
POST /index.php HTTP/1.1
Content-Type: application/json
Content-Length: 122
Host: 192.168.122.158
Connection: keep-alive
Origin: http://192.168.1.158
X-Tine20-Request-Type: JSON
X-Tine20-Jsonkey: undefined
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36
X-Tine20-Transactionid: 9c7129898e9f8ab7e4621fddf7077a1eaa425aac
X-Requested-With: XMLHttpRequest
Accept: */*
Referer: http://192.168.122.158/tine20dev/
Accept-Encoding: gzip,deflate
Accept-Language: de-DE,de;q=0.8,en-GB;q=0.6,en;q=0.4
EOS
);
        $credentials = $this->getTestCredentials();
        $maxLoginFailures = Tinebase_Config::getInstance()->get(Tinebase_Config::MAX_LOGIN_FAILURES, 5);
        for ($i = 0; $i <= $maxLoginFailures; $i++) {
            $result = Tinebase_Controller::getInstance()->login($credentials['username'], 'foobar', $request);
            $this->assertFalse($result);
        }
        // account must be blocked now
        $result = Tinebase_Controller::getInstance()->login($credentials['username'], $credentials['password'], $request);
        $this->assertFalse($result);
    }
 /**
  * (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);
     if ($body !== null) {
         $this->_body = $body;
     } else {
         if ($this->_request instanceof \Zend\Http\Request) {
             $this->_body = fopen('php://temp', 'r+');
             fwrite($this->_body, $request->getContent());
             rewind($this->_body);
         }
     }
     try {
         list($loginName, $password) = $this->_getAuthData($this->_request);
     } catch (Tinebase_Exception_NotFound $tenf) {
         header('WWW-Authenticate: Basic realm="WebDAV for Tine 2.0"');
         header('HTTP/1.1 401 Unauthorized');
         return;
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' is CalDav, CardDAV or WebDAV request.');
     }
     Tinebase_Core::initFramework();
     if (Tinebase_Controller::getInstance()->login($loginName, $password, $this->_request, self::REQUEST_TYPE) !== true) {
         header('WWW-Authenticate: Basic realm="WebDAV for Tine 2.0"');
         header('HTTP/1.1 401 Unauthorized');
         return;
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' requestUri:' . $this->_request->getRequestUri());
     }
     self::$_server = new \Sabre\DAV\Server(new Tinebase_WebDav_Root());
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         $contentType = self::$_server->httpRequest->getHeader('Content-Type');
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " requestContentType: " . $contentType);
         if (preg_match('/^text/', $contentType)) {
             // NOTE inputstream can not be rewinded
             $debugStream = fopen('php://temp', 'r+');
             stream_copy_to_stream($this->_body, $debugStream);
             rewind($debugStream);
             $this->_body = $debugStream;
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " <<< *DAV request\n" . stream_get_contents($this->_body));
             rewind($this->_body);
         } else {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " <<< *DAV request\n -- BINARY DATA --");
         }
     }
     self::$_server->httpRequest->setBody($this->_body);
     // compute base uri
     self::$_server->setBaseUri($this->_request->getBaseUrl() . '/');
     $tempDir = Tinebase_Core::getTempDir();
     if (!empty($tempDir)) {
         self::$_server->addPlugin(new \Sabre\DAV\Locks\Plugin(new \Sabre\DAV\Locks\Backend\File($tempDir . '/webdav.lock')));
     }
     self::$_server->addPlugin(new \Sabre\DAV\Auth\Plugin(new Tinebase_WebDav_Auth(), null));
     $aclPlugin = new \Sabre\DAVACL\Plugin();
     $aclPlugin->defaultUsernamePath = Tinebase_WebDav_PrincipalBackend::PREFIX_USERS;
     $aclPlugin->principalCollectionSet = array(Tinebase_WebDav_PrincipalBackend::PREFIX_USERS, Tinebase_WebDav_PrincipalBackend::PREFIX_GROUPS);
     $aclPlugin->principalSearchPropertySet = array('{DAV:}displayname' => 'Display name', '{' . \Sabre\DAV\Server::NS_SABREDAV . '}email-address' => 'Email address', '{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}email-address-set' => 'Email addresses', '{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}first-name' => 'First name', '{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}last-name' => 'Last name', '{' . \Sabre\CalDAV\Plugin::NS_CALDAV . '}calendar-user-address-set' => 'Calendar user address set', '{' . \Sabre\CalDAV\Plugin::NS_CALDAV . '}calendar-user-type' => 'Calendar user type');
     self::$_server->addPlugin($aclPlugin);
     self::$_server->addPlugin(new \Sabre\CardDAV\Plugin());
     self::$_server->addPlugin(new Calendar_Frontend_CalDAV_SpeedUpPlugin());
     // this plugin must be loaded before CalDAV plugin
     self::$_server->addPlugin(new \Sabre\CalDAV\Plugin());
     self::$_server->addPlugin(new \Sabre\CalDAV\SharingPlugin());
     self::$_server->addPlugin(new Calendar_Frontend_CalDAV_PluginAutoSchedule());
     self::$_server->addPlugin(new Calendar_Frontend_CalDAV_PluginDefaultAlarms());
     self::$_server->addPlugin(new Calendar_Frontend_CalDAV_PluginManagedAttachments());
     self::$_server->addPlugin(new Calendar_Frontend_CalDAV_PluginPrivateEvents());
     self::$_server->addPlugin(new Tinebase_WebDav_Plugin_Inverse());
     self::$_server->addPlugin(new Tinebase_WebDav_Plugin_OwnCloud());
     self::$_server->addPlugin(new Tinebase_WebDav_Plugin_PrincipalSearch());
     #self::$_server->addPlugin(new DAV\Sync\Plugin());
     self::$_server->addPlugin(new \Sabre\DAV\Browser\Plugin());
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         ob_start();
     }
     self::$_server->exec();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " >>> *DAV response:\n" . ob_get_contents());
         ob_end_flush();
     }
     Tinebase_Controller::getInstance()->logout($this->_request->getServer('REMOTE_ADDR'));
 }
    /**
     * @group ServerTests
     *
     * @see 0011440: rework login failure handling
     */
    public function testAccountBlocking()
    {
        // NOTE: end transaction here as NOW() returns the start of the current transaction in pgsql
        //  and is used in user status statement (think about using statement_timestamp() instead of NOW() with pgsql)
        Tinebase_TransactionManager::getInstance()->commitTransaction($this->_transactionId);
        $this->_transactionId = null;
        $request = \Zend\Http\PhpEnvironment\Request::fromString(<<<EOS
POST /index.php HTTP/1.1
Content-Type: application/json
Content-Length: 122
Host: 192.168.122.158
Connection: keep-alive
Origin: http://192.168.1.158
X-Tine20-Request-Type: JSON
X-Tine20-Jsonkey: undefined
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36
X-Tine20-Transactionid: 9c7129898e9f8ab7e4621fddf7077a1eaa425aac
X-Requested-With: XMLHttpRequest
Accept: */*
Referer: http://192.168.122.158/tine20dev/
Accept-Encoding: gzip,deflate
Accept-Language: de-DE,de;q=0.8,en-GB;q=0.6,en;q=0.4
EOS
);
        $credentials = $this->getTestCredentials();
        for ($i = 0; $i <= 3; $i++) {
            $result = Tinebase_Controller::getInstance()->login($credentials['username'], 'foobar', $request);
            $this->assertFalse($result);
        }
        $result = Tinebase_Controller::getInstance()->login($credentials['username'], $credentials['password'], $request);
        $this->assertFalse($result, 'account must be blocked now');
        // wait for some time (2^4 = 16 +1 seconds)
        $timeToWait = 17;
        if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
            Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Waiting for ' . $timeToWait . ' seconds...');
        }
        sleep($timeToWait);
        $result = Tinebase_Controller::getInstance()->login($credentials['username'], $credentials['password'], $request);
        $this->assertTrue($result, 'account should be unblocked now');
    }
 /**
  * switch to another user's account
  * 
  * @param string $loginName
  * @return array
  */
 public function changeUserAccount($loginName)
 {
     $result = Tinebase_Controller::getInstance()->changeUserAccount($loginName);
     return array('success' => $result);
 }
 /**
  * returns list of applications the current user is able to use
  *
  * this function takes group memberships into user. Applications the user is able to use
  * must have the 'run' right set 
  * 
  * @param boolean $_anyRight is any right enough to geht app?
  * @return array list of enabled applications for this user
  */
 public function getApplications($_anyRight = FALSE)
 {
     $roles = Tinebase_Acl_Roles::getInstance();
     $result = $roles->getApplications($this->accountId, $_anyRight);
     if (Tinebase_Controller::getInstance()->userAccountChanged()) {
         // TODO this information should be saved in application table
         $disabledAppsForChangedUserAccounts = array('Felamimail');
         foreach ($result as $key => $app) {
             if (in_array($app, $disabledAppsForChangedUserAccounts)) {
                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Skipping ' . $app . ' because app is disabled for changed user accounts');
                 }
                 unset($result[$key]);
             }
         }
     }
     return $result;
 }
 /**
  * login user
  *
  * @throws Exception
  */
 public function login()
 {
     $tinebaseController = Tinebase_Controller::getInstance();
     $credentials = $this->getTestCredentials();
     $config = $this->getConfig();
     $_SERVER['REMOTE_ADDR'] = $config->ip ? $config->ip : '127.0.0.1';
     $_SERVER['HTTP_USER_AGENT'] = 'Unit Test Client';
     if (!$tinebaseController->login($credentials['username'], $credentials['password'], new \Zend\Http\PhpEnvironment\Request(), 'TineUnittest')) {
         throw new Exception("Couldn't login, user session required for tests! \n");
     }
 }
Пример #13
0
    if (version_compare($phpUnitVersion[1], "3.5.0") >= 0) {
        PHP_CodeCoverage_Filter::getInstance()->addDirectoryToBlacklist(PATH_TO_TEST_DIR);
        PHP_CodeCoverage_Filter::getInstance()->addDirectoryToBlacklist(PATH_TO_TINE_LIBRARY);
        PHP_CodeCoverage_Filter::getInstance()->addDirectoryToBlacklist(PATH_TO_REAL_DIR . '/Setup');
        PHP_CodeCoverage_Filter::getInstance()->addDirectoryToBlacklist(PATH_TO_REAL_DIR . '/Zend');
    } else {
        PHPUnit_Util_Filter::addDirectoryToFilter(PATH_TO_TEST_DIR);
        PHPUnit_Util_Filter::addDirectoryToFilter(PATH_TO_TINE_LIBRARY);
        PHPUnit_Util_Filter::addDirectoryToFilter(PATH_TO_REAL_DIR . '/Setup');
        PHPUnit_Util_Filter::addDirectoryToFilter(PATH_TO_REAL_DIR . '/Zend');
    }
}
$path = array(PATH_TO_REAL_DIR, PATH_TO_TEST_DIR, PATH_TO_TINE_LIBRARY, get_include_path());
set_include_path(implode(PATH_SEPARATOR, $path));
/**
 * Set up basic tine 2.0 environment
 */
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);
Tinebase_Autoloader::initialize($autoloader);
// init base framework
TestServer::getInstance()->initFramework();
$tinebaseController = Tinebase_Controller::getInstance();
$config = TestServer::getInstance()->getConfig();
if (!$tinebaseController->login($config->username, $config->password, $config->ip, 'TineUnittest')) {
    throw new Exception("Couldn't login, user session required for tests! \n");
}
// do this after login because we need the current user
TestServer::getInstance()->initTestUsers();
TestServer::getInstance()->setTestUserEmail();
 /**
  * return small contact image for sync
  *
  * @param $maxSize
  *
  * @return string
  * @throws Tinebase_Exception_InvalidArgument
  * @throws Tinebase_Exception_NotFound
  */
 public function getSmallContactImage($maxSize = self::SMALL_PHOTO_SIZE)
 {
     $image = Tinebase_Controller::getInstance()->getImage('Addressbook', $this->getId());
     return $image->getBlob('image/jpeg', $maxSize);
 }
Пример #15
0
 /**
  * convert contact from xml to Addressbook_Model_Contact
  *
  * @param SimpleXMLElement $_data
  * @return Addressbook_Model_Contact
  */
 public function toTineModel(SimpleXMLElement $_data, $_entry = null)
 {
     if ($_entry instanceof Addressbook_Model_Contact) {
         $contact = $_entry;
     } else {
         $contact = new Addressbook_Model_Contact(null, true);
     }
     unset($contact->jpegphoto);
     $xmlData = $_data->children('uri:Contacts');
     $airSyncBase = $_data->children('uri:AirSyncBase');
     foreach ($this->_mapping as $fieldName => $value) {
         switch ($value) {
             case 'jpegphoto':
                 // do not change if not set
                 if (isset($xmlData->{$fieldName})) {
                     if (!empty($xmlData->{$fieldName})) {
                         $devicePhoto = base64_decode((string) $xmlData->{$fieldName});
                         try {
                             $currentPhoto = Tinebase_Controller::getInstance()->getImage('Addressbook', $contact->getId())->getBlob('image/jpeg', 36000);
                         } catch (Exception $e) {
                         }
                         if (isset($currentPhoto) && $currentPhoto == $devicePhoto) {
                             if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                                 Tinebase_Core::getLogger()->INFO(__METHOD__ . '::' . __LINE__ . " photo did not change on device -> preserving server photo");
                             }
                         } else {
                             if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                                 Tinebase_Core::getLogger()->INFO(__METHOD__ . '::' . __LINE__ . " using new contact photo from device (" . strlen($devicePhoto) . "KB)");
                             }
                             $contact->jpegphoto = $devicePhoto;
                         }
                     } else {
                         if ($_entry && !empty($_entry->jpegphoto)) {
                             $contact->jpegphoto = '';
                             if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                                 Tinebase_Core::getLogger()->INFO(__METHOD__ . '::' . __LINE__ . ' Deleting contact photo on device request (contact id: ' . $contact->getId() . ')');
                             }
                         }
                     }
                 }
                 break;
             case 'bday':
                 if (isset($xmlData->{$fieldName})) {
                     $isoDate = (string) $xmlData->{$fieldName};
                     $contact->bday = new Tinebase_DateTime($isoDate);
                     if ($this->_device->devicetype == Syncope_Model_Device::TYPE_IPHONE && $this->_device->getMajorVersion() < 800 || preg_match("/^\\d{4}-\\d{2}-\\d{2}\$/", $isoDate)) {
                         // iOS < 4 & webow < 2.1 send birthdays to the entered date, but the time the birthday got entered on the device
                         // acutally iOS < 4 somtimes sends the bday at noon but the timezone is not clear
                         // -> we don't trust the time part and set the birthdays timezone to the timezone the user has set in tine
                         $userTimezone = Tinebase_Core::get(Tinebase_Core::USERTIMEZONE);
                         $contact->bday = new Tinebase_DateTime($contact->bday->setTime(0, 0, 0)->format(Tinebase_Record_Abstract::ISO8601LONG), $userTimezone);
                         $contact->bday->setTimezone('UTC');
                     }
                 } else {
                     $contact->bday = null;
                 }
                 break;
             case 'adr_one_countryname':
             case 'adr_two_countryname':
                 $contact->{$value} = Tinebase_Translation::getRegionCodeByCountryName((string) $xmlData->{$fieldName});
                 break;
             case 'adr_one_street':
                 if (strtolower($this->_device->devicetype) == 'palm') {
                     // palm pre sends the whole address in the <Contacts:BusinessStreet> tag
                     unset($contact->adr_one_street);
                 } else {
                     // default handling for all other devices
                     if (isset($xmlData->{$fieldName})) {
                         $contact->{$value} = (string) $xmlData->{$fieldName};
                     } else {
                         $contact->{$value} = null;
                     }
                 }
                 break;
             case 'email':
             case 'email_home':
                 // android send email address as
                 // Lars Kneschke <*****@*****.**>
                 if (preg_match('/(.*)<(.+@[^@]+)>/', (string) $xmlData->{$fieldName}, $matches)) {
                     $contact->{$value} = trim($matches[2]);
                 } else {
                     $contact->{$value} = (string) $xmlData->{$fieldName};
                 }
                 break;
             default:
                 if (isset($xmlData->{$fieldName})) {
                     $contact->{$value} = (string) $xmlData->{$fieldName};
                 } else {
                     $contact->{$value} = null;
                 }
                 break;
         }
     }
     // get body
     if (version_compare($this->_device->acsversion, '12.0', '>=') === true) {
         $contact->note = isset($airSyncBase->Body) ? (string) $airSyncBase->Body->Data : null;
     } else {
         $contact->note = isset($xmlData->Body) ? (string) $xmlData->Body : null;
     }
     // force update of n_fileas and n_fn
     $contact->setFromArray(array('n_given' => $contact->n_given, 'n_family' => $contact->n_family, 'org_name' => $contact->org_name));
     // contact should be valid now
     $contact->isValid();
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . " contactData " . print_r($contact->toArray(), true));
     }
     return $contact;
 }
 /**
  * downloads an image/thumbnail at a given size
  *
  * @param unknown_type $application
  * @param string $id
  * @param string $location
  * @param int $width
  * @param int $height
  * @param int $ratiomode
  */
 public function getImage($application, $id, $location, $width, $height, $ratiomode)
 {
     $this->checkAuth();
     // close session to allow other requests
     Tinebase_Session::writeClose(true);
     $clientETag = null;
     $ifModifiedSince = null;
     if (isset($_SERVER['If_None_Match'])) {
         $clientETag = trim($_SERVER['If_None_Match'], '"');
         $ifModifiedSince = trim($_SERVER['If_Modified_Since'], '"');
     } elseif (isset($_SERVER['HTTP_IF_NONE_MATCH']) && isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
         $clientETag = trim($_SERVER['HTTP_IF_NONE_MATCH'], '"');
         $ifModifiedSince = trim($_SERVER['HTTP_IF_MODIFIED_SINCE'], '"');
     }
     if ($application == 'Tinebase' && $location == 'tempFile') {
         $tempFile = Tinebase_TempFile::getInstance()->getTempFile($id);
         $imgInfo = Tinebase_ImageHelper::getImageInfoFromBlob(file_get_contents($tempFile->path));
         $image = new Tinebase_Model_Image($imgInfo + array('application' => $application, 'id' => $id, 'location' => $location));
     } else {
         $image = Tinebase_Controller::getInstance()->getImage($application, $id, $location);
     }
     $serverETag = sha1($image->blob . $width . $height . $ratiomode);
     // cache for 3600 seconds
     $maxAge = 3600;
     header('Cache-Control: private, max-age=' . $maxAge);
     header("Expires: " . gmdate('D, d M Y H:i:s', Tinebase_DateTime::now()->addSecond($maxAge)->getTimestamp()) . " GMT");
     // overwrite Pragma header from session
     header("Pragma: cache");
     // if the cache id is still valid
     if ($clientETag == $serverETag) {
         header("Last-Modified: " . $ifModifiedSince);
         header("HTTP/1.0 304 Not Modified");
         header('Content-Length: 0');
     } else {
         #$cache = Tinebase_Core::getCache();
         #if ($cache->test($serverETag) === true) {
         #    $image = $cache->load($serverETag);
         #} else {
         if ($width != -1 && $height != -1) {
             Tinebase_ImageHelper::resize($image, $width, $height, $ratiomode);
         }
         #    $cache->save($image, $serverETag);
         #}
         header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
         header('Content-Type: ' . $image->mime);
         header('Etag: "' . $serverETag . '"');
         flush();
         die($image->blob);
     }
 }
 /**
  * returns image from imageURL
  * 
  * @param  string imageURL
  * @return Tinebase_Model_Image
  */
 public static function getImageFromImageURL($_imageURL)
 {
     $params = self::parseImageURL($_imageURL);
     $image = Tinebase_Controller::getInstance()->getImage($params['application'], $params['id'], $params['location']);
     return $image;
 }
Пример #18
0
 /**
  * converts Addressbook_Model_Contact to vcard
  * 
  * @param  Addressbook_Model_Contact  $_record
  * @return string
  */
 public function fromTine20Model(Tinebase_Record_Abstract $_record)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' contact ' . print_r($_record->toArray(), true));
     }
     $card = new Sabre_VObject_Component('VCARD');
     // required vcard fields
     $card->add(new Sabre_VObject_Property('VERSION', '3.0'));
     $card->add(new Sabre_VObject_Property('FN', $_record->n_fileas));
     $card->add(new Sabre_VObject_Element_MultiValue('N', array($_record->n_family, $_record->n_given)));
     $card->add(new Sabre_VObject_Property('PRODID', '-//tine20.org//Tine 2.0//EN'));
     $card->add(new Sabre_VObject_Property('UID', $_record->getId()));
     // optional fields
     $card->add(new Sabre_VObject_Element_MultiValue('ORG', array($_record->org_name, $_record->org_unit)));
     $card->add(new Sabre_VObject_Property('TITLE', $_record->title));
     $tel = new Sabre_VObject_Property('TEL', $_record->tel_work);
     $tel->add('TYPE', 'WORK');
     $card->add($tel);
     $tel = new Sabre_VObject_Property('TEL', $_record->tel_home);
     $tel->add('TYPE', 'HOME');
     $card->add($tel);
     $tel = new Sabre_VObject_Property('TEL', $_record->tel_cell);
     $tel->add('TYPE', 'CELL');
     $card->add($tel);
     $tel = new Sabre_VObject_Property('TEL', $_record->tel_pager);
     $tel->add('TYPE', 'PAGER');
     $card->add($tel);
     $tel = new Sabre_VObject_Property('TEL', $_record->tel_fax);
     $tel->add('TYPE', 'FAX');
     $card->add($tel);
     #$tel = new Sabre_VObject_Property('TEL', $_record->tel_fax_home);
     #$tel->add('TYPE', 'FAX');
     #$tel->add('TYPE', 'HOME');
     #$card->add($tel);
     $adr = new Sabre_VObject_Element_MultiValue('ADR', array(null, $_record->adr_one_street2, $_record->adr_one_street, $_record->adr_one_locality, $_record->adr_one_region, $_record->adr_one_postalcode, $_record->adr_one_countryname));
     $adr->add('TYPE', 'WORK');
     $card->add($adr);
     $adr = new Sabre_VObject_Element_MultiValue('ADR', array(null, $_record->adr_two_street2, $_record->adr_two_street, $_record->adr_two_locality, $_record->adr_two_region, $_record->adr_two_postalcode, $_record->adr_two_countryname));
     $adr->add('TYPE', 'HOME');
     $card->add($adr);
     $card->add(new Sabre_VObject_Property('EMAIL;TYPE=work', $_record->email));
     $card->add(new Sabre_VObject_Property('EMAIL;TYPE=home', $_record->email_home));
     $card->add(new Sabre_VObject_Property('URL;TYPE=work', $_record->url));
     $card->add(new Sabre_VObject_Property('URL;TYPE=home', $_record->url_home));
     $card->add(new Sabre_VObject_Property('NOTE', $_record->note));
     if (!empty($_record->jpegphoto)) {
         try {
             $image = Tinebase_Controller::getInstance()->getImage('Addressbook', $_record->getId());
             $jpegData = $image->getBlob('image/jpeg');
             $photo = new Sabre_VObject_Property('PHOTO', $jpegData);
             $photo->add('ENCODING', 'b');
             $photo->add('TYPE', 'JPEG');
             $card->add($photo);
         } catch (Exception $e) {
             Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " Image for contact {$_record->getId()} not found or invalid");
         }
     }
     if (isset($_record->tags) && count($_record->tags) > 0) {
         $card->add(new Sabre_VObject_Property('CATEGORIES', Sabre_VObject_Element_List((array) $_record->tags->name)));
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' card ' . $card->serialize());
     }
     return $card;
 }
 /**
  * testChangeUserAccount
  * 
  * @see 0009984: allow to change user role
  */
 public function testChangeUserAccount()
 {
     // allow test user to sign in as sclever
     Tinebase_Config::getInstance()->set(Tinebase_Config::ROLE_CHANGE_ALLOWED, new Tinebase_Config_Struct(array(Tinebase_Core::getUser()->accountLoginName => array('sclever'))));
     $sclever = $this->_personas['sclever'];
     $result = $this->_instance->changeUserAccount('sclever');
     $this->assertEquals(array('success' => true), $result);
     // make sure, we are sclever
     $this->assertEquals('sclever', Tinebase_Core::getUser()->accountLoginName);
     $this->assertEquals('sclever', Tinebase_Session::getSessionNamespace()->currentAccount->accountLoginName);
     // reset to original user
     Tinebase_Controller::getInstance()->initUser($this->_originalTestUser, false);
     Tinebase_Session::getSessionNamespace()->userAccountChanged = false;
 }
Пример #20
0
 /**
  * destroy session
  *
  * @return array
  */
 public function logout()
 {
     Tinebase_Controller::getInstance()->logout($_SERVER['REMOTE_ADDR']);
     Tinebase_Auth_CredentialCache::getInstance()->getCacheAdapter()->resetCache();
     $result = array('success' => true);
     return $result;
 }
 /**
  * authenticate user
  *
  * @param string $_username
  * @param string $_password
  * @param string $_ipAddress
  * @return bool
  */
 protected function _authenticate($_username, $_password, \Zend\Http\Request $request)
 {
     $pos = strrchr($_username, '\\');
     if ($pos !== false) {
         $username = substr(strrchr($_username, '\\'), 1);
     } else {
         $username = $_username;
     }
     return Tinebase_Controller::getInstance()->login($username, $_password, $request, self::REQUEST_TYPE);
 }