/** * convert objects with user data to ldap data array * * @param Tinebase_Model_FullUser $_user * @param array $_ldapData the data to be written to ldap */ protected function _group2ldap(Tinebase_Model_Group $_group, array &$_ldapData) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ENCRYPT ' . print_r($_ldapData, true)); } if (isset($_ldapData['objectclass'])) { $_ldapData['objectclass'] = array_unique(array_merge($_ldapData['objectclass'], $this->_requiredObjectClass)); } if (isset($_ldapData['gidnumber'])) { $gidNumber = $_ldapData['gidnumber']; } else { $gidNumber = $this->_getGidNumber($_group->getId()); } // when we try to add a group, $_group has no id which leads to Tinebase_Exception_InvalidArgument in $this->_getGroupMetaData try { $metaData = $this->_getGroupMetaData($_group); } catch (Tinebase_Exception_InvalidArgument $teia) { $metaData = array(); } if (!isset($metaData['sambasid'])) { $_ldapData['sambasid'] = $this->_options[Tinebase_Group_Ldap::PLUGIN_SAMBA]['sid'] . '-' . (2 * $gidNumber + 1001); $_ldapData['sambagrouptype'] = 2; } $_ldapData['displayname'] = $_group->name; }
/** * update foreign key values * * @param string $_mode create|update * @param Tinebase_Record_Interface $_record * * @todo support update mode */ protected function _updateForeignKeys($_mode, Tinebase_Record_Interface $_record) { if ($_mode == 'create') { foreach ($this->_foreignTables as $key => $foreign) { if (!isset($_record->{$key}) || empty($_record->{$key})) { continue; } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $key . ': ' . print_r($_record->{$key}, TRUE)); } foreach ($_record->{$key} as $data) { if ($key == 'flags') { $data = array('flag' => $data, 'folder_id' => $_record->folder_id); } else { // need to filter input as 'name' could contain invalid chars (emojis, ...) here foreach ($data as $field => $value) { $data[$field] = Tinebase_Core::filterInputForDatabase($data[$field]); } } $data['message_id'] = $_record->getId(); $this->_db->insert($this->_tablePrefix . $foreign['table'], $data); } } } }
/** * Constructor * * @param array $options An array of arrays of IMAP options * @param string $username * @param string $password */ public function __construct(array $options = array(), $username = null, $password = null) { if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($options, true)); } parent::__construct($options, $username, $password); }
/** * factory function to return a selected account/imap backend class * * @param string|Felamimail_Model_Account $_accountId * @return Felamimail_Backend_ImapProxy * @throws Felamimail_Exception_IMAPInvalidCredentials */ public static function factory($_accountId) { $accountId = $_accountId instanceof Felamimail_Model_Account ? $_accountId->getId() : $_accountId; if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Getting IMAP backend for account id ' . $accountId); } if (!isset(self::$_backends[$accountId])) { // get imap config from account $account = $_accountId instanceof Felamimail_Model_Account ? $_accountId : Felamimail_Controller_Account::getInstance()->get($_accountId); $imapConfig = $account->getImapConfig(); // we need to instantiate a new imap backend if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Connecting to server ' . $imapConfig['host'] . ':' . $imapConfig['port'] . ' (' . (array_key_exists('ssl', $imapConfig) ? $imapConfig['ssl'] : 'none') . ')' . ' with username ' . $imapConfig['user']); } try { self::$_backends[$accountId] = new Felamimail_Backend_ImapProxy($imapConfig); Felamimail_Controller_Account::getInstance()->updateCapabilities($account, self::$_backends[$accountId]); } catch (Felamimail_Exception_IMAPInvalidCredentials $feiic) { // add account and username to Felamimail_Exception_IMAPInvalidCredentials $feiic->setAccount($account)->setUsername($imapConfig['user']); throw $feiic; } } return self::$_backends[$accountId]; }
/** * converts an array of tags names to a recordSet of Tinebase_Model_Tag * * @param iteratable $tagNames * @param bool $implicitAddMissingTags * @return Tinebase_Record_RecordSet */ public static function resolveTagNameToTag($tagNames, $applicationName, $implicitAddMissingTags = true) { if (empty($tagNames)) { return new Tinebase_Record_RecordSet('Tinebase_Model_Tag'); } $resolvedTags = array(); foreach ((array) $tagNames as $tagName) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Trying to allocate tag ' . $tagName); } $tagName = trim($tagName); if (empty($tagName)) { continue; } $existingTags = Tinebase_Tags::getInstance()->searchTags(new Tinebase_Model_TagFilter(array('name' => $tagName, 'application' => $applicationName)), new Tinebase_Model_Pagination(array('sort' => 'type', 'dir' => 'DESC', 'limit' => 1))); if (count($existingTags) === 1) { //var_dump($existingTags->toArray()); $resolvedTags[] = $existingTags->getFirstRecord(); } elseif ($implicitAddMissingTags === true) { // No tag found, lets create a personal tag $resolvedTag = Tinebase_Tags::GetInstance()->createTag(new Tinebase_Model_Tag(array('type' => Tinebase_Model_Tag::TYPE_PERSONAL, 'name' => $tagName))); $resolvedTags[] = $resolvedTag; } } return new Tinebase_Record_RecordSet('Tinebase_Model_Tag', $resolvedTags); }
/** * download file * * @param string $path */ public function downloadNode($path) { try { $splittedPath = explode('/', trim($path, '/')); $downloadId = array_shift($splittedPath); $download = $this->_getDownloadLink($downloadId); $this->_setDownloadLinkOwnerAsUser($download); $node = Filemanager_Controller_DownloadLink::getInstance()->getNode($download, $splittedPath); if ($node->type === Tinebase_Model_Tree_Node::TYPE_FILE) { $nodeController = Filemanager_Controller_Node::getInstance(); $nodeController->resolveMultipleTreeNodesPath($node); $pathRecord = Tinebase_Model_Tree_Node_Path::createFromPath($nodeController->addBasePath($node->path)); Filemanager_Controller_DownloadLink::getInstance()->increaseAccessCount($download); $this->_downloadFileNode($node, $pathRecord->streamwrapperpath); } } catch (Exception $e) { if (Tinebase_Core::isLogLevel(Zend_Log::CRIT)) { Tinebase_Core::getLogger()->crit(__METHOD__ . '::' . __LINE__ . ' exception: ' . $e->getMessage()); } if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' exception: ' . $e->getTraceAsString()); } header('HTTP/1.0 404 Not found'); $view = new Zend_View(); $view->setScriptPath('Filemanager/views'); header('Content-Type: text/html; charset=utf-8'); die($view->render('notfound.phtml')); } exit; }
/** * handler for JSON api requests * * @return JSON */ public function handle() { try { // init server and request first $server = new Zend_Json_Server(); $server->setClass('Setup_Frontend_Json', 'Setup'); $server->setClass('Tinebase_Frontend_Json', 'Tinebase'); $server->setAutoHandleExceptions(false); $server->setAutoEmitResponse(false); $request = new Zend_Json_Server_Request_Http(); Setup_Core::initFramework(); $method = $request->getMethod(); $jsonKey = isset($_SERVER['HTTP_X_TINE20_JSONKEY']) ? $_SERVER['HTTP_X_TINE20_JSONKEY'] : ''; Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' is JSON request. method: ' . $method); $anonymnousMethods = array('Setup.getAllRegistryData', 'Setup.login', 'Tinebase.getAvailableTranslations', 'Tinebase.getTranslations', 'Tinebase.setLocale'); if (!Setup_Core::configFileExists()) { $anonymnousMethods = array_merge($anonymnousMethods, array('Setup.envCheck')); } // check json key for all methods but some exceptoins if (!in_array($method, $anonymnousMethods) && Setup_Core::configFileExists() && (empty($jsonKey) || $jsonKey != Setup_Core::get('jsonKey') || !Setup_Core::isRegistered(Setup_Core::USER))) { if (!Setup_Core::isRegistered(Setup_Core::USER)) { Setup_Core::getLogger()->INFO(__METHOD__ . '::' . __LINE__ . ' Attempt to request a privileged Json-API method without authorisation from "' . $_SERVER['REMOTE_ADDR'] . '". (session timeout?)'); throw new Tinebase_Exception_AccessDenied('Not Authorised', 401); } else { Setup_Core::getLogger()->WARN(__METHOD__ . '::' . __LINE__ . ' Fatal: got wrong json key! (' . $jsonKey . ') Possible CSRF attempt!' . ' affected account: ' . print_r(Setup_Core::getUser(), true) . ' request: ' . print_r($_REQUEST, true)); throw new Tinebase_Exception_AccessDenied('Not Authorised', 401); } } $response = $server->handle($request); } catch (Exception $exception) { $response = $this->_handleException($server, $request, $exception); } echo $response; }
public function validate($username, $password) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Options: ' . print_r($this->_options, true)); } $url = isset($this->_options['url']) ? $this->_options['url'] : 'https://localhost/validate/check'; $adapter = new Zend_Http_Client_Adapter_Socket(); $adapter->setStreamContext($this->_options = array('ssl' => array('verify_peer' => isset($this->_options['ignorePeerName']) ? false : true, 'allow_self_signed' => isset($this->_options['allowSelfSigned']) ? true : false))); $client = new Zend_Http_Client($url, array('maxredirects' => 0, 'timeout' => 30)); $client->setAdapter($adapter); $params = array('user' => $username, 'pass' => $password); $client->setParameterPost($params); try { $response = $client->request(Zend_Http_Client::POST); } catch (Zend_Http_Client_Adapter_Exception $zhcae) { Tinebase_Exception::log($zhcae); return Tinebase_Auth::FAILURE; } $body = $response->getBody(); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Request: ' . $client->getLastRequest()); } if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Response: ' . $body); } if ($response->getStatus() !== 200) { return Tinebase_Auth::FAILURE; } $result = Tinebase_Helper::jsonDecode($body); if (isset($result['result']) && $result['result']['status'] === true && $result['result']['value'] === true) { return Tinebase_Auth::SUCCESS; } else { return Tinebase_Auth::FAILURE; } }
/** * handler for command line scripts * * @return boolean */ public function handle() { try { $opts = new Zend_Console_Getopt(array('help|h' => 'Display this help Message', 'verbose|v' => 'Output messages', 'config|c=s' => 'Path to config.inc.php file', 'setconfig' => 'Update config. To specify the key and value, append \' -- configKey="your_key" configValue="your config value"\' Examples: setup.php --setconfig -- configkey=sample1 configvalue=value11 setup.php --setconfig -- configkey=sample2 configvalue=arrayKey1:Value1,arrayKey2:value2', 'check_requirements' => 'Check if all requirements are met to install and run tine20', 'create_admin' => 'Create new admin user (or reactivate if already exists)', 'install-s' => 'Install applications [All] or comma separated list;' . ' To specify the login name and login password of the admin user that is created during installation, append \' -- adminLoginName="admin" adminPassword="******"\'' . ' To add imap or smtp settings, append (for example) \' -- imap="host:mail.example.org,port:143,dbmail_host:localhost" smtp="ssl:tls"\'', 'update-s' => 'Update applications [All] or comma separated list', 'uninstall-s' => 'Uninstall application [All] or comma separated list', 'list-s' => 'List installed applications', 'sync_accounts_from_ldap' => 'Import user and groups from ldap', 'egw14import' => 'Import user and groups from egw14 Examples: setup.php --egw14import egwdbhost egwdbuser egwdbpass egwdbname latin1 setup.php --egw14import egwdbhost egwdbuser egwdbpass egwdbname utf8')); $opts->parse(); } catch (Zend_Console_Getopt_Exception $e) { echo "Invalid usage: {$e->getMessage()}\n\n"; echo $e->getUsageMessage(); exit; } if (count($opts->toArray()) === 0 || $opts->h || empty($opts->install) && empty($opts->update) && empty($opts->uninstall) && empty($opts->list) && empty($opts->sync_accounts_from_ldap) && empty($opts->egw14import) && empty($opts->check_requirements) && empty($opts->create_admin) && empty($opts->setconfig)) { echo $opts->getUsageMessage(); exit; } if ($opts->config) { // add path to config.inc.php to include path $path = strstr($opts->config, 'config.inc.php') !== false ? dirname($opts->config) : $opts->config; set_include_path($path . PATH_SEPARATOR . get_include_path()); } Setup_Core::initFramework(); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Is cli request. method: ' . (isset($opts->mode) ? $opts->mode : 'EMPTY')); } $setupServer = new Setup_Frontend_Cli(); #$setupServer->authenticate($opts->username, $opts->password); return $setupServer->handle($opts); }
/** * repair groups * * * add missing lists * * checks if list container has been deleted (and hides groups if that's the case) * * @see 0010401: add repair script for groups without list_ids */ public function repairGroups() { $count = 0; $be = new Tinebase_Group_Sql(); $listBackend = new Addressbook_Backend_List(); $groups = $be->getGroups(); foreach ($groups as $group) { if ($group->list_id == null) { $list = Addressbook_Controller_List::getInstance()->createByGroup($group); $group->list_id = $list->getId(); $group->visibility = Tinebase_Model_Group::VISIBILITY_DISPLAYED; if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Add missing list for group ' . $group->name); } $be->updateGroupInSqlBackend($group); $count++; } else { if ($group->visibility === Tinebase_Model_Group::VISIBILITY_DISPLAYED) { try { $list = $listBackend->get($group->list_id); $listContainer = Tinebase_Container::getInstance()->get($list->container_id); } catch (Tinebase_Exception_NotFound $tenf) { if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Hide group ' . $group->name . ' without list / list container.'); } $group->visibility = Tinebase_Model_Group::VISIBILITY_HIDDEN; $be->updateGroupInSqlBackend($group); $count++; } } } } echo $count . " groups repaired!\n"; }
protected function _importRecord($_recordData, &$_result) { //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . print_r($_recordData, true)); $record = new $this->_modelName($_recordData, TRUE); if ($record->isValid()) { if (!$this->_options['dryrun']) { if ($record->__get('change_sign') == 'A') { $record = call_user_func(array($this->_controller, $this->_createMethod), $record); } else { try { $record = $this->_controller->getByRecordNumber((int) trim($record->__get('record_number'))); $record->setFromArray($_recordData); $record = $this->_controller->update($record); } catch (Tinebase_Exception_NotFound $e) { $record = call_user_func(array($this->_controller, $this->_createMethod), $record); } if ($record->__get('change_sign') == 'D') { $this->_controller->delete($record->getId()); } } } else { $_result['results']->addRecord($record); } $_result['totalcount']++; } else { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . print_r($record->toArray(), true)); } throw new Tinebase_Exception_Record_Validation('Imported record is invalid.'); } }
/** * adds a new relation * * @param Tinebase_Model_Relation $_relation * @return Tinebase_Model_Relation the new relation * * @todo move check existance and update / modlog to controller? */ public function addRelation($_relation) { if ($_relation->getId()) { throw new Tinebase_Exception_Record_NotAllowed('Could not add existing relation'); } $relId = $_relation->generateUID(); $_relation->setId($relId); // check if relation is already set (with is_deleted=1) if ($deletedRelId = $this->_checkExistance($_relation)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Removing existing relation (rel_id): ' . $deletedRelId); $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('rel_id') . ' = ?', $deletedRelId)); $this->_dbTable->delete($where); } $data = $_relation->toArray(); $data['rel_id'] = $data['id']; $data['id'] = $_relation->generateUID(); unset($data['related_record']); if (isset($data['remark']) && is_array($data['remark'])) { $data['remark'] = Zend_Json::encode($data['remark']); } $this->_dbTable->insert($data); $swappedData = $this->_swapRoles($data); $swappedData['id'] = $_relation->generateUID(); $this->_dbTable->insert($swappedData); return $this->getRelation($relId, $_relation['own_model'], $_relation['own_backend'], $_relation['own_id']); }
/** * appends sql to given select statement * * @param Zend_Db_Select $_select * @param Tinebase_Backend_Sql_Abstract $_backend */ public function appendFilterSql($_select, $_backend) { $db = $_backend->getAdapter(); // prepare value $value = $this->_value ? 1 : 0; if ($value) { // nothing to do -> show all contacts! if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Query all account contacts.'); } } else { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Only query visible and enabled account contacts.'); } if (Tinebase_Core::getUser() instanceof Tinebase_Model_FullUser) { $where = '/* is no user */ ' . Tinebase_Backend_Sql_Command::getIfIsNull($db, $db->quoteIdentifier('accounts.id'), 'true', 'false') . ' OR /* is user */ (' . Tinebase_Backend_Sql_Command::getIfIsNull($db, $db->quoteIdentifier('accounts.id'), 'false', 'true') . ' AND ' . $db->quoteInto($db->quoteIdentifier('accounts.status') . ' = ?', 'enabled') . " AND " . '(' . $db->quoteInto($db->quoteIdentifier('accounts.visibility') . ' = ?', 'displayed') . ' OR ' . $db->quoteInto($db->quoteIdentifier('accounts.id') . ' = ?', Tinebase_Core::getUser()->getId()) . ')' . ")"; } else { $where = '/* is no user */ ' . Tinebase_Backend_Sql_Command::getIfIsNull($db, $db->quoteIdentifier('accounts.id'), 'true', 'false') . ' OR /* is user */ (' . Tinebase_Backend_Sql_Command::getIfIsNull($db, $db->quoteIdentifier('accounts.id'), 'false', 'true') . ' AND ' . $db->quoteInto($db->quoteIdentifier('accounts.status') . ' = ?', 'enabled') . " AND " . $db->quoteInto($db->quoteIdentifier('accounts.visibility') . ' = ?', 'displayed') . ")"; } $_select->where($where); $select = $_select instanceof Zend_Db_Select ? $_select : $_select->getSelect(); $select = Tinebase_Backend_Sql_Abstract::traitGroup($db, $_backend->getTablePrefix(), $select); $_select instanceof Zend_Db_Select ? $_select = $select : $_select->setSelect($select); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' contacts query ' . $_select->assemble()); } } }
/** * get grants for records * * @param Tinebase_Record_RecordSet $records */ public function getGrantsForRecords(Tinebase_Record_RecordSet $records) { $recordIds = $records->getArrayOfIds(); if (empty($recordIds)) { return; } $select = $this->_getAclSelectByRecordIds($recordIds)->group(array('record_id', 'account_type', 'account_id')); Tinebase_Backend_Sql_Abstract::traitGroup($select); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $select); } $stmt = $this->_db->query($select); $grantsData = $stmt->fetchAll(Zend_Db::FETCH_ASSOC); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' grantsData: ' . print_r($grantsData, true)); } foreach ($grantsData as $grantData) { $givenGrants = explode(',', $grantData['account_grants']); foreach ($givenGrants as $grant) { $grantData[$grant] = TRUE; } $recordGrant = new $this->_modelName($grantData, true); unset($recordGrant->account_grant); $record = $records->getById($recordGrant->record_id); if (!$record->grants instanceof Tinebase_Record_RecordSet) { $record->grants = new Tinebase_Record_RecordSet($this->_modelName); } $record->grants->addRecord($recordGrant); } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Records with grants: ' . print_r($records->toArray(), true)); } }
/** * appends sql to given select statement * * @param Zend_Db_Select $_select * @param Tinebase_Backend_Sql_Abstract $_backend * @throws Tinebase_Exception_UnexpectedValue */ public function appendFilterSql($_select, $_backend) { // don't take empty filter into account if (empty($this->_value) || !is_array($this->_value) || !isset($this->_value['cfId']) || empty($this->_value['cfId']) || !isset($this->_value['value'])) { return; } else { if ($this->_operator == 'in') { throw new Tinebase_Exception_UnexpectedValue('Operator "in" not supported.'); } } // make sure $correlationName is a string $correlationName = Tinebase_Record_Abstract::generateUID() . $this->_value['cfId'] . 'cf'; if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Adding custom field filter: ' . print_r($this->_value, true)); } $db = Tinebase_Core::getDb(); $idProperty = $db->quoteIdentifier($this->_options['idProperty']); // per left join we add a customfield column named as the customfield and filter this joined column // NOTE: we name the column we join like the customfield, to be able to join multiple customfield criteria (multiple invocations of this function) $what = array($correlationName => SQL_TABLE_PREFIX . 'customfield'); $on = $db->quoteIdentifier("{$correlationName}.record_id") . " = {$idProperty} AND " . $db->quoteIdentifier("{$correlationName}.customfield_id") . " = " . $db->quote($this->_value['cfId']); $_select->joinLeft($what, $on, array()); $valueIdentifier = $db->quoteIdentifier("{$correlationName}.value"); if ($this->_value['value'] === '') { $where = $db->quoteInto($valueIdentifier . ' IS NULL OR ' . $valueIdentifier . ' = ?', $this->_value['value']); } else { $value = $this->_replaceWildcards($this->_value['value']); $where = $db->quoteInto($valueIdentifier . $this->_opSqlMap[$this->_operator]['sqlop'], $value); } $_select->where($where . ' /* add cf filter */'); }
/** * send notifications to a list a recipients * * @param Tinebase_Model_FullUser $_updater * @param array $_recipients array of int|Addressbook_Model_Contact * @param string $_subject * @param string $_messagePlain * @param string $_messageHtml * @param string|array $_attachments * @throws Tinebase_Exception * * @todo improve exception handling: collect all messages / exceptions / failed email addresses / ... */ public function send($_updater, $_recipients, $_subject, $_messagePlain, $_messageHtml = NULL, $_attachments = NULL) { $contactsBackend = Addressbook_Backend_Factory::factory(Addressbook_Backend_Factory::SQL); $exception = NULL; $sentContactIds = array(); foreach ($_recipients as $recipient) { try { if (!$recipient instanceof Addressbook_Model_Contact) { $recipient = $contactsBackend->get($recipient); } if (!in_array($recipient->getId(), $sentContactIds)) { $this->_smtpBackend->send($_updater, $recipient, $_subject, $_messagePlain, $_messageHtml, $_attachments); $sentContactIds[] = $recipient->getId(); } } catch (Exception $e) { $exception = $e; if (Tinebase_Core::isLogLevel(Zend_Log::NOTICE)) { Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' Failed to send notification message (recipient: ' . ($recipient instanceof Addressbook_Model_Contact ? $recipient->email : $recipient) . '. Exception: ' . $e); } } } if ($exception !== NULL) { // throw exception in the end when all recipients have been processed throw $exception; } }
/** * 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 '); } } }
/** * run multiple async jobs parallel */ public static function triggerAsyncEvents($numOfParallels = 5) { $cmd = realpath(__DIR__ . "/../../../tine20/tine20.php") . ' --method Tinebase.triggerAsyncEvents'; $cmd = TestServer::assembleCliCommand($cmd); // start multiple cronruns at the same time // NOTE: we don't use pnctl as we don't need it here and it's not always available for ($i = 0; $i < 5; $i++) { $tempNames[] = $fileName = tempnam(Tinebase_Core::getTempDir(), 'asynctest'); Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Starting async job: ' . $cmd); $result = exec("{$cmd} > {$fileName} 2> /dev/null &"); } // wait for processes to complete for ($i = 0; $i < count($tempNames) * 5; $i++) { sleep(1); $allJobsDone = TRUE; foreach ($tempNames as $fileName) { $output = file_get_contents($fileName); $allJobsDone &= (bool) preg_match('/complete.$/m', $output); } if ($allJobsDone) { break; } } // cleanup foreach ($tempNames as $fileName) { //echo 'removing ' . $fileName . "\n"; unlink($fileName); } if (!$allJobsDone) { throw new Exception('jobs did not complete'); } }
/** * resetCache() - resets the cache */ public function resetCache() { setcookie(self::COOKIE_KEY, '', time() - 3600); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Reset credential cache cookie.'); } }
/** * parse iseragent and return backend and version * * @return array */ public static function parseUserAgent($_userAgent) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' user agent: ' . $_userAgent); // MacOS X if (preg_match(Addressbook_Convert_Contact_VCard_MacOSX::HEADER_MATCH, $_userAgent, $matches)) { $backend = Addressbook_Convert_Contact_VCard_Factory::CLIENT_MACOSX; $version = $matches['version']; // Thunderbird with Sogo Connector } elseif (preg_match(Addressbook_Convert_Contact_VCard_Sogo::HEADER_MATCH, $_userAgent, $matches)) { $backend = Addressbook_Convert_Contact_VCard_Factory::CLIENT_SOGO; $version = $matches['version']; // iOS addressbook } elseif (preg_match(Addressbook_Convert_Contact_VCard_IOS::HEADER_MATCH, $_userAgent, $matches)) { $backend = Addressbook_Convert_Contact_VCard_Factory::CLIENT_IOS; $version = $matches['version']; // KDE addressbook } elseif (preg_match(Addressbook_Convert_Contact_VCard_KDE::HEADER_MATCH, $_userAgent, $matches)) { $backend = Addressbook_Convert_Contact_VCard_Factory::CLIENT_KDE; $version = $matches['version']; // generic client } else { $backend = Addressbook_Convert_Contact_VCard_Factory::CLIENT_GENERIC; $version = null; } return array($backend, $version); }
/** * resolves all virtual fields for the address * * @param array $address * @return array with property => value */ public function resolveVirtualFields($address) { if (!isset($address['type'])) { if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) { Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Invalid address for resolving: ' . print_r($address, true)); } return $address; } $ft = ''; $i18n = Tinebase_Translation::getTranslation($this->_applicationName)->getAdapter(); $type = $address['type']; $ft .= !empty($address['prefix1']) ? $address['prefix1'] : ''; $ft .= !empty($address['prefix1']) && !empty($address['prefix2']) ? ' ' : ''; $ft .= !empty($address['prefix2']) ? $address['prefix2'] : ''; $ft .= !empty($address['prefix1']) || !empty($address['prefix2']) ? ', ' : ''; $ft .= !empty($address['postbox']) ? $address['postbox'] : (!empty($address['street']) ? $address['street'] : ''); $ft .= !empty($address['postbox']) || !empty($address['street']) ? ', ' : ''; $ft .= !empty($address['postalcode']) ? $address['postalcode'] . ' ' : ''; $ft .= !empty($address['locality']) ? $address['locality'] : ''; $ft .= ' ('; $ft .= $i18n->_($type); if ($type == 'billing') { $ft .= ' - ' . $address['custom1']; } $ft .= ')'; $address['fulltext'] = $ft; return $address; }
/** * inspect set password * * @param string $_userId * @param string $_password * @param boolean $_encrypt * @param boolean $_mustChange * @param array $_ldapData the data to be written to ldap */ public function inspectSetPassword($_userId, $_password, $_encrypt, $_mustChange, array &$_ldapData) { if ($_encrypt !== true) { Tinebase_Core::getLogger()->crit(__METHOD__ . '::' . __LINE__ . ' can not transform crypted password into nt/lm samba password. Make sure to reset password for user ' . $_userId); } else { $_ldapData['sambantpassword'] = Tinebase_User_Abstract::encryptPassword($_password, Tinebase_User_Abstract::ENCRYPT_NTPASSWORD); $_ldapData['sambalmpassword'] = array(); if ($_mustChange === true) { $_ldapData['sambapwdmustchange'] = '1'; $_ldapData['sambapwdcanchange'] = '1'; $_ldapData['sambapwdlastset'] = array(); } else { if ($_mustChange === false) { $_ldapData['sambapwdmustchange'] = '2147483647'; $_ldapData['sambapwdcanchange'] = '1'; $_ldapData['sambapwdlastset'] = Tinebase_DateTime::now()->getTimestamp(); } else { if ($_mustChange === null && $_userId instanceof Tinebase_Model_FullUser && isset($_userId->sambaSAM) && isset($_userId->sambaSAM->pwdMustChange) && isset($_userId->sambaSAM->pwdCanChange)) { $_ldapData['sambapwdmustchange'] = $_userId->sambaSAM->pwdMustChange->getTimestamp(); $_ldapData['sambapwdcanchange'] = $_userId->sambaSAM->pwdCanChange->getTimestamp(); $_ldapData['sambapwdlastset'] = array(); } } } } }
/** * * @param Tinebase_Record_Interface $_observable * @param Tinebase_Event_Abstract $_event */ public function fireEvent($_observable, $_event) { $observers = $this->getObserversByEvent($_observable, $_event); foreach ($observers as $observer) { $controllerName = $observer->observer_application . '_Controller'; if (!class_exists($controllerName)) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " No such application controller: '{$controllerName}'"); } continue; } if (!class_exists($_event)) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " No such event: '{$_event}'"); } continue; } try { $controller = call_user_func(array($controllerName, 'getInstance')); } catch (Exception $e) { // application has no controller or is not useable at all if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " Can't get instance of {$controllerName} : {$e}"); } continue; } $eventObject = new $_event(); // Tinebase_Model_PersistentObserver holds observer and observable $eventObject->observable = $observer; $controller->handleEvent($eventObject); } }
/** * event handler function * * all events get routed through this function * * @param Tinebase_Event_Abstract $_eventObject the eventObject * * @todo write test */ protected function _handleEvent(Tinebase_Event_Abstract $_eventObject) { if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . ' (' . __LINE__ . ') handle event of type ' . get_class($_eventObject)); } switch (get_class($_eventObject)) { case 'Admin_Event_AddAccount': $this->createPersonalFolder($_eventObject->account); break; case 'Tinebase_Event_User_DeleteAccount': /** * @var Tinebase_Event_User_DeleteAccount $_eventObject */ if ($_eventObject->deletePersonalContainers()) { $this->deletePersonalFolder($_eventObject->account); } //make to be deleted accounts (user) contact a normal contact if ($_eventObject->keepAsContact()) { $contact = Addressbook_Controller_Contact::getInstance()->get($_eventObject->account->contact_id); $contact->type = Addressbook_Model_Contact::CONTACTTYPE_CONTACT; Addressbook_Controller_Contact::getInstance()->update($contact); } else { //or just delete it $contactsBackend = Addressbook_Backend_Factory::factory(Addressbook_Backend_Factory::SQL); $contactsBackend->delete($_eventObject->account->contact_id); } break; } }
/** * converts Addressbook_Model_Contact to vcard * * @param Addressbook_Model_Contact $_record * @return \Sabre\VObject\Component\VCard */ 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)); } // initialize vcard object $card = $this->_fromTine20ModelRequiredFields($_record); $card->add('TEL', $_record->tel_work, array('TYPE' => array('WORK', 'VOICE'))); $card->add('TEL', $_record->tel_home, array('TYPE' => array('HOME', 'VOICE'))); $card->add('TEL', $_record->tel_cell, array('TYPE' => 'CELL')); $card->add('TEL', $_record->tel_cell_private, array('TYPE' => 'OTHER')); $card->add('TEL', $_record->tel_fax, array('TYPE' => array('FAX', 'WORK'))); $card->add('TEL', $_record->tel_fax_home, array('TYPE' => array('FAX', 'HOME'))); $card->add('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), array('TYPE' => 'WORK')); $card->add('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), array('TYPE' => 'HOME')); $card->add('EMAIL', $_record->email, array('TYPE' => 'PREF')); $card->add('EMAIL', $_record->email_home); $card->add('URL', $_record->url, array('TYPE' => 'WORK')); $card->add('URL', $_record->url_home, array('TYPE' => 'HOME')); $card->add('NOTE', $_record->note); $this->_fromTine20ModelAddBirthday($_record, $card); $this->_fromTine20ModelAddPhoto($_record, $card); $this->_fromTine20ModelAddGeoData($_record, $card); $this->_fromTine20ModelAddCategories($_record, $card); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' card ' . $card->serialize()); } return $card; }
/** * the constructor */ public function __construct() { if (Sales_Config::getInstance()->featureEnabled(Sales_Config::FEATURE_INVOICES_MODULE)) { $this->_relatableModels[] = 'Sales_Model_Invoice'; $this->_configuredModels[] = 'InvoicePosition'; $this->_configuredModels[] = 'Invoice'; } else { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Invoices module disabled'); } } if (Sales_Config::getInstance()->featureEnabled(Sales_Config::FEATURE_OFFERS_MODULE)) { $this->_relatableModels[] = 'Sales_Model_Offer'; $this->_configuredModels[] = 'Offer'; } if (Sales_Config::getInstance()->featureEnabled(Sales_Config::FEATURE_SUPPLIERS_MODULE)) { $this->_relatableModels[] = 'Sales_Model_Supplier'; $this->_configuredModels[] = 'Supplier'; } if (Sales_Config::getInstance()->featureEnabled(Sales_Config::FEATURE_PURCHASE_INVOICES_MODULE)) { $this->_relatableModels[] = 'Sales_Model_PurchaseInvoice'; $this->_configuredModels[] = 'PurchaseInvoice'; } if (Sales_Config::getInstance()->featureEnabled(Sales_Config::FEATURE_ORDERCONFIRMATIONS_MODULE)) { $this->_relatableModels[] = 'Sales_Model_OrderConfirmation'; $this->_configuredModels[] = 'OrderConfirmation'; } }
/** * update to 5.1 * - move task status to key field config */ public function update_0() { $tasksAppId = Tinebase_Application::getInstance()->getApplicationByName('Tasks')->getId(); // remove status_id keys $this->_backend->dropForeignKey('tasks', 'tasks::status_id--tasks_status::id'); $this->_backend->dropIndex('tasks', 'status_id'); // need to replace all NULL values first $this->_db->update(SQL_TABLE_PREFIX . 'tasks', array('status_id' => 1), "`status_id` IS NULL"); // alter status_id -> status $declaration = new Setup_Backend_Schema_Field_Xml(' <field> <name>status</name> <type>text</type> <length>40</length> <default>NEEDS-ACTION</default> <notnull>true</notnull> </field>'); $this->_backend->alterCol('tasks', $declaration, 'status_id'); // get all current status datas and drop old status table $stmt = $this->_db->query("SELECT * FROM `" . SQL_TABLE_PREFIX . "tasks_status`"); $statusDatas = $stmt->fetchAll(Zend_Db::FETCH_ASSOC); $this->_backend->dropTable('tasks_status', $tasksAppId); // update task table $statusMap = array(); // oldId => newId foreach ($statusDatas as $statusData) { $statusMap[$statusData['id']] = $statusData['status_name']; $this->_db->update(SQL_TABLE_PREFIX . 'tasks', array('status' => $statusData['status_name']), "`status` = '{$statusData['id']}'"); } // create status config $cb = new Tinebase_Backend_Sql(array('modelName' => 'Tinebase_Model_Config', 'tableName' => 'config')); $tasksStatusConfig = array('name' => Tasks_Config::TASK_STATUS, 'records' => array(array('id' => 'NEEDS-ACTION', 'value' => 'No response', 'is_open' => 1, 'icon' => 'images/oxygen/16x16/actions/mail-mark-unread-new.png', 'system' => true), array('id' => 'COMPLETED', 'value' => 'Completed', 'is_open' => 0, 'icon' => 'images/oxygen/16x16/actions/ok.png', 'system' => true), array('id' => 'CANCELLED', 'value' => 'Cancelled', 'is_open' => 0, 'icon' => 'images/oxygen/16x16/actions/dialog-cancel.png', 'system' => true), array('id' => 'IN-PROCESS', 'value' => 'In process', 'is_open' => 1, 'icon' => 'images/oxygen/16x16/actions/view-refresh.png', 'system' => true))); // add non system custom status foreach ($statusDatas as $statusData) { if (!in_array($statusData['status_name'], array('NEEDS-ACTION', 'COMPLETED', 'CANCELLED', 'IN-PROCESS'))) { $tasksStatusConfig['records'][] = array('id' => $statusData['status_name'], 'value' => $statusData['status_name'], 'is_open' => $statusData['status_is_open'], 'icon' => $statusData['status_icon']); } } $cb->create(new Tinebase_Model_Config(array('application_id' => $tasksAppId, 'name' => Tasks_Config::TASK_STATUS, 'value' => json_encode($tasksStatusConfig)))); // update persistent filters $stmt = $this->_db->query("SELECT * FROM `" . SQL_TABLE_PREFIX . "filter` WHERE " . "`application_id` = '" . $tasksAppId . "' AND " . "`model` = 'Tasks_Model_TaskFilter'"); $pfiltersDatas = $stmt->fetchAll(Zend_Db::FETCH_ASSOC); foreach ($pfiltersDatas as $pfilterData) { $filtersData = Zend_Json::decode($pfilterData['filters']); foreach ($filtersData as &$filterData) { if (array_key_exists('field', $filterData) && $filterData['field'] == 'status_id') { $filterData['field'] = 'status'; $newStatusIds = array(); foreach ((array) $filterData['value'] as $oldStatusId) { $newStatusIds[] = $statusMap[$oldStatusId]; } $filterData['value'] = is_array($filterData['value']) ? $newStatusIds : $newStatusIds[0]; Tinebase_Core::getLogger()->ERR(print_r($filterData, TRUE)); } } $this->_db->update(SQL_TABLE_PREFIX . 'filter', array('filters' => Zend_Json::encode($filtersData)), "`id` LIKE '{$pfilterData['id']}'"); } $this->setTableVersion('tasks', '4'); $this->setApplicationVersion('Tasks', '5.1'); }
/** * (non-PHPdoc) * @see Tinebase_Server_Interface::handle() */ public function handle(\Zend\Http\Request $request = null, $body = null) { $method = $this->getRequestMethod(); if (!in_array($method, array('Tinebase.monitoringCheckDB', 'Tinebase.monitoringCheckConfig'))) { Tinebase_Core::initFramework(); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Is cli request. method: ' . $method); } } // prevents problems with missing request uri (@see Sabre\HTTP\Request->getUri()) if (!isset($_SERVER['REQUEST_URI'])) { $_SERVER['REQUEST_URI'] = ''; } $tinebaseServer = new Tinebase_Frontend_Cli(); $opts = Tinebase_Core::get('opts'); if (!in_array($method, self::getAnonymousMethods($method))) { $tinebaseServer->authenticate($opts->username, $opts->password); } $result = $tinebaseServer->handle($opts); //@todo remove cli session path // convert function result to shell return code if ($result === NULL || $result === TRUE || !is_int($result)) { $result = 0; } else { if ($result === FALSE) { $result = 1; } } // finish profiling here - we won't run in Tinebase_Core again Tinebase_Core::finishProfiling(); Tinebase_Core::getDbProfiling(); exit($result); }
/** * parse iseragent and return backend and version * * @return array */ public static function parseUserAgent($_userAgent) { // MacOS X if (preg_match(Calendar_Convert_Event_VCalendar_MacOSX::HEADER_MATCH, $_userAgent, $matches)) { $backend = Calendar_Convert_Event_VCalendar_Factory::CLIENT_MACOSX; $version = $matches['version']; // iPhone } elseif (preg_match(Calendar_Convert_Event_VCalendar_Iphone::HEADER_MATCH, $_userAgent, $matches)) { $backend = Calendar_Convert_Event_VCalendar_Factory::CLIENT_IPHONE; $version = $matches['version']; // KDE } elseif (preg_match(Calendar_Convert_Event_VCalendar_KDE::HEADER_MATCH, $_userAgent, $matches)) { $backend = Calendar_Convert_Event_VCalendar_Factory::CLIENT_KDE; $version = $matches['version']; // Thunderbird } elseif (preg_match(Calendar_Convert_Event_VCalendar_Thunderbird::HEADER_MATCH, $_userAgent, $matches)) { $backend = Calendar_Convert_Event_VCalendar_Factory::CLIENT_THUNDERBIRD; $version = $matches['version']; } else { $backend = Calendar_Convert_Event_VCalendar_Factory::CLIENT_GENERIC; $version = null; } if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " backend: {$backend} version: {$version}"); } return array($backend, $version); }
/** * delete all stored contentId's for given device and class * * @param ActiveSync_Model_Device $_deviceId * @param string $_class */ public function resetState(ActiveSync_Model_Device $_deviceId, $_class, $_collectionId) { $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('device_id') . ' = ?', $_deviceId->getId()), $this->_db->quoteInto($this->_db->quoteIdentifier('class') . ' = ?', $_class), $this->_db->quoteInto($this->_db->quoteIdentifier('collectionid') . ' = ?', $_collectionId)); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " reset content state"); } $this->_db->delete(SQL_TABLE_PREFIX . $this->_tableName, $where); }