/**
  * init the test framework
  */
 public function initFramework()
 {
     $this->setWhiteAndBlacklists();
     // get config
     $configData = @(include 'phpunitconfig.inc.php');
     if ($configData === false) {
         $configData = (include 'config.inc.php');
     }
     if ($configData === false) {
         die('central configuration file config.inc.php not found in includepath: ' . get_include_path());
     }
     $config = new Zend_Config($configData);
     Zend_Registry::set('testConfig', $config);
     $_SERVER['DOCUMENT_ROOT'] = $config->docroot;
     $_SERVER['REQUEST_URI'] = '';
     Tinebase_Core::startCoreSession();
     Tinebase_Core::initFramework();
     // set default test mailer
     Tinebase_Smtp::setDefaultTransport(new Zend_Mail_Transport_Array());
     // set max execution time
     Tinebase_Core::setExecutionLifeTime(1200);
     if ($config->locale) {
         Tinebase_Core::setupUserLocale($config->locale);
     }
     // this is needed for session handling in unittests (deactivate Zend_Session::writeClose and others)
     Zend_Session::$_unitTestEnabled = TRUE;
 }
 /**
  * do the import 
  */
 public function import()
 {
     $this->_log->NOTICE(__METHOD__ . '::' . __LINE__ . ' starting egw import for Adressbook');
     $this->_migrationStartTime = Tinebase_DateTime::now();
     $this->_tineRecordBackend = Addressbook_Backend_Factory::factory(Addressbook_Backend_Factory::SQL);
     $estimate = $this->_getEgwRecordEstimate();
     $this->_log->NOTICE(__METHOD__ . '::' . __LINE__ . " found {$estimate} contacts for migration");
     $pageSize = 100;
     $numPages = ceil($estimate / $pageSize);
     for ($page = 1; $page <= $numPages; $page++) {
         $this->_log->info(__METHOD__ . '::' . __LINE__ . " starting migration page {$page} of {$numPages}");
         Tinebase_Core::setExecutionLifeTime($pageSize * 10);
         $recordPage = $this->_getRawEgwRecordPage($page, $pageSize);
         $this->_migrateEgwRecordPage($recordPage);
     }
     $this->_log->NOTICE(__METHOD__ . '::' . __LINE__ . ' ' . ($this->_importResult['totalcount'] - $this->_importResult['failcount']) . ' contacts imported sucessfully ' . ($this->_importResult['failcount'] ? " {$this->_importResult['failcount']} contacts skipped with failures" : ""));
 }
Пример #3
0
 /**
  * do the import 
  */
 public function import()
 {
     $this->_migrationStartTime = Tinebase_DateTime::now();
     $this->_calEventBackend = new Calendar_Backend_Sql();
     /*
     $tineDb = Tinebase_Core::getDb();
     Tinebase_TransactionManager::getInstance()->startTransaction($tineDb);
     */
     $estimate = $this->_getEgwEventsCount();
     $this->_log->info("found {$estimate} events for migration");
     $pageSize = 100;
     $numPages = ceil($estimate / $pageSize);
     for ($page = 1; $page <= $numPages; $page++) {
         $this->_log->info("starting migration page {$page} of {$numPages}");
         // NOTE: recur events with lots of exceptions might consume LOTS of time!
         Tinebase_Core::setExecutionLifeTime($pageSize * 10);
         $eventPage = $this->_getRawEgwEventPage($page, $pageSize);
         $this->_migrateEventPage($eventPage);
     }
 }
 /**
  * init the test framework
  */
 public function initFramework()
 {
     $this->setWhiteAndBlacklists();
     $config = $this->getConfig();
     // set some server vars. sabredav complains if REQUEST_URI is not set
     $_SERVER['DOCUMENT_ROOT'] = $config->docroot;
     $_SERVER['REQUEST_URI'] = '';
     Tinebase_Core::startCoreSession();
     Tinebase_Core::initFramework();
     // set default test mailer
     Tinebase_Smtp::setDefaultTransport(new Zend_Mail_Transport_Array());
     // set max execution time
     Tinebase_Core::setExecutionLifeTime(1200);
     if ($config->locale) {
         Tinebase_Core::setupUserLocale($config->locale);
     }
     // this is needed for session handling in unittests (deactivate Zend_Session::writeClose and others)
     Zend_Session::$_unitTestEnabled = TRUE;
     Tinebase_Core::set('frameworkInitialized', true);
 }
Пример #5
0
 /**
  * download file
  * 
  * @param string $_path
  * 
  * @todo allow to download a folder as ZIP file
  */
 public function downloadFile($path)
 {
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(0);
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . ' Download file ' . $path);
     }
     $pathRecord = Tinebase_Model_Tree_Node_Path::createFromPath(Filemanager_Controller_Node::getInstance()->addBasePath($path));
     $node = Filemanager_Controller_Node::getInstance()->getFileNode($pathRecord);
     // 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");
     header('Content-Disposition: attachment; filename="' . $node->name . '"');
     header("Content-Type: " . $node->contenttype);
     $handle = fopen($pathRecord->streamwrapperpath, 'r');
     fpassthru($handle);
     fclose($handle);
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     exit;
 }
Пример #6
0
 /**
  * init the test framework
  *
  */
 public function initFramework()
 {
     // get config
     $configData = @(include 'phpunitconfig.inc.php');
     if ($configData === false) {
         $configData = (include 'config.inc.php');
     }
     if ($configData === false) {
         die('central configuration file config.inc.php not found in includepath: ' . get_include_path());
     }
     $config = new Zend_Config($configData);
     Zend_Registry::set('testConfig', $config);
     $_SERVER['DOCUMENT_ROOT'] = $config->docroot;
     Tinebase_Core::initFramework();
     // set default test mailer
     Tinebase_Smtp::setDefaultTransport(new Zend_Mail_Transport_Array());
     // set max execution time
     Tinebase_Core::setExecutionLifeTime(1200);
     // set default internal encoding
     iconv_set_encoding("internal_encoding", "UTF-8");
     Zend_Registry::set('locale', new Zend_Locale($config->locale));
 }
 /**
  * do the import 
  */
 public function import()
 {
     $this->_log->NOTICE(__METHOD__ . '::' . __LINE__ . ' starting egw import for Calendar');
     $this->_migrationStartTime = Tinebase_DateTime::now();
     $this->_tineRecordBackend = new Calendar_Backend_Sql();
     /*
     $tineDb = Tinebase_Core::getDb();
     Tinebase_TransactionManager::getInstance()->startTransaction($tineDb);
     */
     $estimate = $this->_getEgwRecordEstimate();
     $this->_log->NOTICE(__METHOD__ . '::' . __LINE__ . " found {$estimate} events for migration");
     $pageSize = 100;
     $numPages = ceil($estimate / $pageSize);
     for ($page = 1; $page <= $numPages; $page++) {
         $this->_log->INFO(__METHOD__ . '::' . __LINE__ . " starting migration page {$page} of {$numPages}");
         // NOTE: recur events with lots of exceptions might consume LOTS of time!
         Tinebase_Core::setExecutionLifeTime($pageSize * 10);
         $eventPage = $this->_getRawEgwEventPage($page, $pageSize);
         $this->_migrateEventPage($eventPage);
     }
     $this->_log->NOTICE(__METHOD__ . '::' . __LINE__ . ' ' . ($this->_importResult['totalcount'] - $this->_importResult['failcount']) . ' events imported sucessfully' . ($this->_importResult['failcount'] ? " {$this->_importResult['failcount']} events skipped with failures" : ""));
 }
 /**
  * send Zend_Mail message via smtp
  * 
  * @param  mixed      $accountId
  * @param  Zend_Mail  $mail
  * @param  boolean    $saveInSent
  * @param  Felamimail_Model_Message $originalMessage
  * @return Zend_Mail
  */
 public function sendZendMail($accountId, Zend_Mail $mail, $saveInSent = false, $originalMessage = NULL)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Sending message with subject ' . $mail->getSubject());
     }
     if ($originalMessage !== NULL) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Original Message subject: ' . $originalMessage->subject . ' / Flag to set: ' . var_export($originalMessage->flags, TRUE));
         }
         // this is required for adding the reply/forward flag in _sendMailViaTransport()
         $originalMessage->original_id = $originalMessage;
     }
     // increase execution time (sending message with attachments can take a long time)
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(300);
     // 5 minutes
     // get account
     $account = $accountId instanceof Felamimail_Model_Account ? $accountId : Felamimail_Controller_Account::getInstance()->get($accountId);
     $this->_setMailFrom($mail, $account);
     $this->_setMailHeaders($mail, $account);
     $this->_sendMailViaTransport($mail, $account, $originalMessage, $saveInSent);
     // reset max execution time to old value
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     return $mail;
 }
Пример #9
0
 /**
  * process the XML file and add, change, delete or fetches data 
  *
  * @todo can we get rid of LIBXML_NOWARNING
  * @todo we need to stored the initial data for folders and lifetime as the phone is sending them only when they change
  * @return resource
  */
 public function handle()
 {
     $controller = ActiveSync_Controller::getInstance();
     $intervalStart = time();
     $status = self::STATUS_NO_CHANGES_FOUND;
     // the client does not send a wbxml document, if the Ping parameters did not change compared with the last request
     if ($this->_inputDom instanceof DOMDocument) {
         #$xml = simplexml_load_string($this->_inputDom->saveXML());
         $xml = new SimpleXMLElement($this->_inputDom->saveXML(), LIBXML_NOWARNING);
         $xml->registerXPathNamespace('Ping', 'Ping');
         if (isset($xml->HeartBeatInterval)) {
             $this->_device->pinglifetime = $xml->HeartBeatInterval;
         }
         if (isset($xml->Folders->Folder)) {
             foreach ($xml->Folders->Folder as $folderXml) {
                 #Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " folderType: " . print_r($folderXml, true));
                 #$folderBackend = $this->_backend->factory((string)$folderXml->Class);
                 try {
                     // does the folder exist?
                     #            $folderBackend->getFolder($folderXml->Id);
                     $folder = array('serverEntryId' => (string) $folderXml->Id, 'folderType' => (string) $folderXml->Class);
                     $folders[] = $folder;
                 } catch (Exception $e) {
                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " " . $e->getMessage());
                     }
                     $status = self::STATUS_FOLDER_NOT_FOUND;
                     break;
                 }
             }
             $this->_device->pingfolder = serialize($folders);
         }
         $this->_device = $controller->updateDevice($this->_device);
     }
     $lifeTime = $this->_device->pinglifetime;
     Tinebase_Core::setExecutionLifeTime($lifeTime);
     $intervalEnd = $intervalStart + $lifeTime;
     $secondsLeft = $intervalEnd;
     $folders = unserialize($this->_device->pingfolder);
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " Folders to monitor({$lifeTime} / {$intervalStart} / {$intervalEnd} / {$status}): " . print_r($folders, true));
     }
     if ($status === self::STATUS_NO_CHANGES_FOUND) {
         $folderWithChanges = array();
         do {
             foreach ((array) $folders as $folder) {
                 $dataController = ActiveSync_Controller::dataFactory($folder['folderType'], $this->_device, $this->_syncTimeStamp);
                 #if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " " . print_r($folder, true));
                 try {
                     $syncState = $controller->getSyncState($this->_device, $folder['folderType'], $folder['serverEntryId']);
                     $count = $this->_getItemEstimate($dataController, $folder, $syncState->lastsync);
                 } catch (ActiveSync_Exception_SyncStateNotFound $e) {
                     // folder got never synchronized to client
                     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . " " . $e->getMessage());
                     }
                     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' syncstate not found. enforce sync for folder: ' . $folder['serverEntryId']);
                     }
                     $count = 1;
                 }
                 if ($count > 0) {
                     $folderWithChanges[] = array('serverEntryId' => $folder['serverEntryId'], 'folderType' => $folder['folderType']);
                     $status = self::STATUS_CHANGES_FOUND;
                 }
             }
             if ($status === self::STATUS_CHANGES_FOUND) {
                 break;
             }
             // another process synchronized data already
             if (isset($syncState) && $syncState->lastsync > $this->_syncTimeStamp) {
                 Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " terminate ping process. Some other process updated data already.");
                 break;
             }
             sleep(self::PING_TIMEOUT);
             $secondsLeft = $intervalEnd - time();
             //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " DeviceId: " . $this->_device->deviceid . " seconds left: " . $secondsLeft);
         } while ($secondsLeft > 0);
     }
     Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " DeviceId: " . $this->_device->deviceid . " Lifetime: {$lifeTime} SecondsLeft: {$secondsLeft} Status: {$status})");
     $ping = $this->_outputDom->documentElement;
     $ping->appendChild($this->_outputDom->createElementNS('uri:Ping', 'Status', $status));
     if ($status === self::STATUS_CHANGES_FOUND) {
         $folders = $ping->appendChild($this->_outputDom->createElementNS('uri:Ping', 'Folders'));
         foreach ($folderWithChanges as $changedFolder) {
             $folder = $folders->appendChild($this->_outputDom->createElementNS('uri:Ping', 'Folder', $changedFolder['serverEntryId']));
             #$folder->appendChild($this->_outputDom->createElementNS('uri:Ping', 'Id', $changedFolder['serverEntryId']));
             Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " DeviceId: " . $this->_device->deviceid . " changes in folder: " . $changedFolder['serverEntryId']);
         }
     }
 }
 /**
  * update message cache
  * 
  * @param string $_folder
  * @param integer $_time in seconds
  * @param integer $_updateFlagFactor 1 = update flags every time, x = update flags roughly each xth run (10 by default)
  * @return Felamimail_Model_Folder folder status (in cache)
  * @throws Felamimail_Exception
  */
 public function updateCache($_folder, $_time = 10, $_updateFlagFactor = 10)
 {
     Tinebase_Core::setExecutionLifeTime(300);
     // 5 minutes
     // always read folder from database
     $folder = Felamimail_Controller_Folder::getInstance()->get($_folder);
     if ($this->_doNotUpdateCache($folder)) {
         return $folder;
     }
     $imap = Felamimail_Backend_ImapFactory::factory($folder->account_id);
     $this->_availableUpdateTime = $_time;
     try {
         $this->_expungeCacheFolder($folder, $imap);
     } catch (Felamimail_Exception_IMAPFolderNotFound $feifnf) {
         return $folder;
     }
     $this->_initUpdate($folder);
     $this->_updateMessageSequence($folder, $imap);
     $this->_deleteMessagesInCache($folder, $imap);
     $this->_addMessagesToCache($folder, $imap);
     $this->_checkForMissingMessages($folder, $imap);
     $this->_updateFolderStatus($folder);
     if ($folder->supports_condstore || rand(1, $_updateFlagFactor) == 1) {
         $folder = $this->updateFlags($folder);
     }
     $this->_updateFolderQuota($folder, $imap);
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Folder status of ' . $folder->globalname . ' after updateCache(): ' . $folder->cache_status);
     }
     return $folder;
 }
 /**
  * delete records by filter
  *
  * @param Tinebase_Model_Filter_FilterGroup $_filter
  * @return  Tinebase_Record_RecordSet
  */
 public function deleteByFilter(Tinebase_Model_Filter_FilterGroup $_filter)
 {
     $oldMaxExcecutionTime = ini_get('max_execution_time');
     Tinebase_Core::setExecutionLifeTime(300);
     // 5 minutes
     $ids = $this->search($_filter, NULL, FALSE, TRUE);
     $deletedRecords = $this->delete($ids);
     // reset max execution time to old value
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     return $deletedRecords;
 }
Пример #12
0
 /**
  * import records
  *
  * @param string $_tempFileId to import
  * @param string $_importDefinitionId
  * @param array $_options additional import options
  * @param array $_clientRecordData
  * @return array
  * @throws Tinebase_Exception_NotFound
  */
 protected function _import($_tempFileId, $_importDefinitionId, $_options = array(), $_clientRecordData = array())
 {
     $definition = Tinebase_ImportExportDefinition::getInstance()->get($_importDefinitionId);
     $importer = call_user_func($definition->plugin . '::createFromDefinition', $definition, $_options);
     if (!is_object($importer)) {
         throw new Tinebase_Exception_NotFound('No importer found for ' . $definition->name);
     }
     // extend execution time to 30 minutes
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(1800);
     $file = Tinebase_TempFile::getInstance()->getTempFile($_tempFileId);
     $importResult = $importer->importFile($file->path, $_clientRecordData);
     $importResult['results'] = $importResult['results']->toArray();
     $importResult['exceptions'] = $importResult['exceptions']->toArray();
     $importResult['status'] = 'success';
     // reset max execution time to old value
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     return $importResult;
 }
Пример #13
0
 /**
  * delete records by filter
  *
  * @param Tinebase_Model_Filter_FilterGroup $_filter
  * @return  Tinebase_Record_RecordSet
  */
 public function deleteByFilter(Tinebase_Model_Filter_FilterGroup $_filter)
 {
     $oldMaxExcecutionTime = ini_get('max_execution_time');
     Tinebase_Core::setExecutionLifeTime(300);
     // 5 minutes
     $ids = $this->search($_filter, NULL, FALSE, TRUE);
     Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Deleting ' . count($ids) . ' records ...');
     //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . print_r($ids, true));
     // reset max execution time to old value
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     return $this->delete($ids);
 }
 /**
  * creates missing accounts
  * 
  * * optional params:
  *   - day=YYYY-MM-DD
  *   - remove_unbilled=1
  *   - contract=CONTRACT_ID or contract=NUMBER
  *
  * @param Zend_Console_Getopt $_opts
  * @return boolean
  */
 public function create_auto_invoices($_opts)
 {
     if (!Sales_Config::getInstance()->featureEnabled(Sales_Config::FEATURE_INVOICES_MODULE)) {
         Tinebase_Core::getLogger()->crit(__METHOD__ . '::' . __LINE__ . ' create_auto_invoices ran allthoug feature ' . Sales_Config::FEATURE_INVOICES_MODULE . ' is disabled');
         return false;
     }
     $executionLifeTime = Tinebase_Core::setExecutionLifeTime(3600 * 8);
     $this->_addOutputLogWriter();
     $freeLock = $this->_aquireMultiServerLock(__CLASS__ . '::' . __FUNCTION__);
     if (!$freeLock) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Job already running - ' . __CLASS__ . '::' . __FUNCTION__);
         }
         return false;
     }
     $date = NULL;
     $args = $this->_parseArgs($_opts, array());
     // if day argument is given, validate
     if (array_key_exists('day', $args)) {
         $split = explode('-', $args['day']);
         if (!count($split == 3)) {
             // failure
         } else {
             if (strlen($split[0]) != 4 || strlen($split[1]) != 2 || strlen($split[2]) != 2) {
                 // failure
             } elseif (intval($split[1]) == 0 || intval($split[2]) == 0) {
                 // failure
             } else {
                 // other errors are caught by datetime
                 try {
                     $date = new Tinebase_DateTime();
                     // use usertimezone
                     $date->setTimezone(Tinebase_Core::getUserTimezone());
                     // if a date is given, set hour to 3
                     $date->setDate($split[0], $split[1], $split[2])->setTime(3, 0, 0);
                 } catch (Exception $e) {
                     Tinebase_Exception::log($e);
                 }
             }
         }
         if (!$date) {
             die('The day must have the following format: YYYY-MM-DD!' . PHP_EOL);
         }
     }
     if (!$date) {
         $date = Tinebase_DateTime::now();
         $date->setTimezone(Tinebase_Core::getUserTimezone());
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Creating invoices for ' . $date->toString());
     }
     $contract = NULL;
     if (array_key_exists('contract', $args)) {
         try {
             $contract = Sales_Controller_Contract::getInstance()->get($args['contract']);
         } catch (Tinebase_Exception_NotFound $e) {
             $filter = new Sales_Model_ContractFilter(array(array('field' => 'number', 'operator' => 'equals', 'value' => $args['contract'])));
             $contract = Sales_Controller_Contract::getInstance()->search($filter, NULL, TRUE);
             if ($contract->count() == 1) {
                 $contract = $contract->getFirstRecord();
             } elseif ($contract->count() > 1) {
                 die('The number you have given is not unique! Please use the ID instead!' . PHP_EOL);
             } else {
                 die('A contract could not be found!' . PHP_EOL);
             }
         }
     }
     if (array_key_exists('remove_unbilled', $args) && $args['remove_unbilled'] == 1) {
         $this->removeUnbilledAutoInvoices($contract);
     }
     if (array_key_exists('check_updates', $args) && $args['check_updates'] == 1) {
         Sales_Controller_Invoice::getInstance()->checkForContractOrInvoiceUpdates($contract);
     }
     $result = Sales_Controller_Invoice::getInstance()->createAutoInvoices($date, $contract);
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         unset($result['created']);
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' ' . print_r($result, true));
     }
     Tinebase_Core::setExecutionLifeTime($executionLifeTime);
     return true;
 }
Пример #15
0
 /**
  * download message part
  * 
  * @param string $_messageId
  * @param string $_partId
  */
 protected function _downloadMessagePart($_messageId, $_partId = NULL)
 {
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(0);
     try {
         if (count($_messageId) == 1) {
             $part = Felamimail_Controller_Message::getInstance()->getMessagePart($_messageId[0], $_partId);
             if ($part instanceof Zend_Mime_Part) {
                 $filename = !empty($part->filename) ? $part->filename : $_messageId[0] . '.eml';
                 $contentType = $_partId === NULL ? Felamimail_Model_Message::CONTENT_TYPE_MESSAGE_RFC822 : $part->type;
                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . ' filename: ' . $filename . ' content type' . $contentType);
                 }
                 // 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");
                 header('Content-Disposition: attachment; filename="' . $filename . '"');
                 header("Content-Type: " . $contentType);
                 $stream = $_partId === NULL ? $part->getRawStream() : $part->getDecodedStream();
                 fpassthru($stream);
                 fclose($stream);
             }
         } else {
             $ZIPfile = new ZipArchive();
             $tmpFile = tempnam(Tinebase_Core::getTempDir(), 'tine20_');
             if ($ZIPfile->open($tmpFile) === TRUE) {
                 foreach ($_messageId as $messageID) {
                     $part = Felamimail_Controller_Message::getInstance()->getRawMessage($messageID);
                     $filename = $messageID . '.eml';
                     $ZIPfile->addFromString($filename, $part);
                 }
                 $ZIPfile->close();
             }
             $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");
             header('Content-Disposition: attachment; filename="menssagem.zip"');
             header("Content-Type: application/zip");
             $stream = fopen($tmpFile, 'r');
             fpassthru($stream);
             fclose($stream);
             unlink($tmpFile);
         }
     } catch (Exception $e) {
         Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Failed to get message part: ' . $e->getMessage());
     }
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     exit;
 }
 /**
  * Used for updating multiple records
  * 
  * @param string $appName
  * @param string $modelName
  * @param array $changes
  * @param array $filter
  */
 public function updateMultipleRecords($appName, $modelName, $changes, $filter)
 {
     // increase execution time to 30 minutes
     Tinebase_Core::setExecutionLifeTime(1800);
     $filterModel = $appName . '_Model_' . $modelName . 'Filter';
     $data = array();
     foreach ($changes as $f) {
         $data[preg_replace('/^customfield_/', '#', $f['name'])] = $f['value'];
     }
     return $this->_updateMultiple($filter, $data, Tinebase_Core::getApplicationInstance($appName, $modelName), $filterModel);
 }
 /**
  * download all attachments
  *
  * @param string $_messageId
  */
 protected function _downloadAllAtachements($_messageId)
 {
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(0);
     $ZIPfile = new ZipArchive();
     $tmpFile = tempnam(Tinebase_Core::getTempDir(), 'tine20_');
     if (strpos($_messageId, '_') !== false) {
         list($messageId, $partId) = explode('_', $_messageId);
     } else {
         $messageId = $_messageId;
         $partId = null;
     }
     if ($ZIPfile->open($tmpFile) === TRUE) {
         $attachments = Expressomail_Controller_Message::getInstance()->getAttachments($messageId, $partId);
         foreach ($attachments as $attachment) {
             $part = Expressomail_Controller_Message::getInstance()->getMessagePart($messageId, $attachment['partId']);
             $filename = is_null($part->filename) ? $attachment['filename'] : $part->filename;
             if ($part->encoding == Zend_Mime::ENCODING_BASE64) {
                 $ZIPfile->addFromString(iconv("UTF-8", "ASCII//TRANSLIT", $filename), base64_decode(stream_get_contents($part->getRawStream())));
             } else {
                 $ZIPfile->addFromString(iconv("UTF-8", "ASCII//TRANSLIT", $filename), stream_get_contents($part->getRawStream()));
             }
         }
         $ZIPfile->close();
     }
     $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");
     header('Content-Disposition: attachment; filename="mensagens.zip"');
     header("Content-Type: application/zip");
     $stream = fopen($tmpFile, 'r');
     fpassthru($stream);
     fclose($stream);
     unlink($tmpFile);
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     exit;
 }
 /**
  * save group data from edit form
  *
  * @param   array $groupData        group data
  * @param   array $groupMembers     group members
  * 
  * @return  array
  */
 public function saveGroup($groupData, $groupMembers)
 {
     // unset if empty
     if (empty($groupData['id'])) {
         unset($groupData['id']);
     }
     $group = new Tinebase_Model_Group($groupData);
     $group->members = $groupMembers;
     // this needs long execution time because cache invalidation may take long
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(60);
     // 1 minute
     if (empty($group->id)) {
         $group = Admin_Controller_Group::getInstance()->create($group);
     } else {
         $group = Admin_Controller_Group::getInstance()->update($group);
     }
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     return $this->getGroup($group->getId());
 }
 /**
  * download (fpassthru) file node
  * 
  * @param Tinebase_Model_Tree_Node $node
  * @param string $filesystemPath
  */
 protected function _downloadFileNode($node, $filesystemPath)
 {
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(0);
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Download file node ' . print_r($node->toArray(), TRUE));
     }
     // 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");
     header('Content-Disposition: attachment; filename="' . $node->name . '"');
     header("Content-Type: " . $node->contenttype);
     $handle = fopen($filesystemPath, 'r');
     fpassthru($handle);
     fclose($handle);
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
 }
Пример #20
0
 /**
  * 
  * Enter description here ...
  * @param unknown_type $_files
  * @param unknown_type $_options
  */
 public function importMT940Files($_files, $_options = array())
 {
     // extend execution time and close session
     Tinebase_Core::setExecutionLifeTime(7200);
     // 2 hours
     //Zend_Session::writeClose(true);
     // TODO importer is da TD importer
     $importer = null;
     // import files
     $result = array('results' => array(), 'totalcount' => 0, 'failcount' => 0, 'duplicatecount' => 0, 'status' => 'success');
     foreach ($_files as $file) {
         $importResult = Billing_Import_MT940::import($file['path']);
         $result['results'] = array();
         $result['totalcount'] += $importResult['totalcount'];
         $result['failcount'] += $importResult['failcount'];
         $result['duplicatecount'] += $importResult['duplicatecount'];
     }
     $result['totalcount'] = Billing_Controller_MT940Payment::getInstance()->getCountPayments();
     $result['status'] = $importResult['status'];
     //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . print_r($result, true));
     return $importResult;
 }
Пример #21
0
 /**
  * update message cache
  * 
  * @param string $_folder
  * @param integer $_time in seconds
  * @param integer $_updateFlagFactor 1 = update flags every time, x = update flags roughly each xth run (10 by default)
  * @return Felamimail_Model_Folder folder status (in cache)
  * @throws Felamimail_Exception
  */
 public function updateCache($_folder, $_time = 10, $_updateFlagFactor = 10)
 {
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(300);
     // 5 minutes
     // always read folder from database
     $folder = Felamimail_Controller_Folder::getInstance()->get($_folder);
     if ($this->_doNotUpdateCache($folder)) {
         return $folder;
     }
     $imap = Felamimail_Backend_ImapFactory::factory($folder->account_id);
     $this->_availableUpdateTime = $_time;
     $this->_expungeCacheFolder($folder, $imap);
     $this->_initUpdate($folder);
     $this->_updateMessageSequence($folder, $imap);
     $this->_deleteMessagesInCache($folder, $imap);
     $this->_addMessagesToCache($folder, $imap);
     $this->_checkForMissingMessages($folder, $imap);
     $this->_updateFolderStatus($folder);
     if (rand(1, $_updateFlagFactor) == 1) {
         $folder = $this->updateFlags($folder);
     }
     $this->_updateFolderQuota($folder, $imap);
     // reset max execution time to old value
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     return $folder;
 }
Пример #22
0
 /**
  * generic export function
  * 
  * @param Tinebase_Model_Filter_FilterGroup $_filter
  * @param array $_options format/definition id
  * @param Tinebase_Controller_Record_Abstract $_controller
  * @return void
  * 
  * @todo support single ids as filter?
  * @todo use stream here instead of temp file?
  */
 protected function _export(Tinebase_Model_Filter_FilterGroup $_filter, $_options, Tinebase_Controller_Record_Abstract $_controller = NULL)
 {
     // extend execution time to 30 minutes
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(1800);
     // get export object
     $export = Tinebase_Export::factory($_filter, $_options, $_controller);
     $format = $export->getFormat();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Exporting ' . $_filter->getModelName() . ' in format ' . $format);
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($_options, TRUE));
     }
     switch ($format) {
         case 'pdf':
             $ids = $_controller->search($_filter, NULL, FALSE, TRUE, 'export');
             // loop records
             foreach ($ids as $id) {
                 if (!empty($id)) {
                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Creating pdf for ' . $_filter->getModelName() . '  id ' . $id);
                     }
                     $record = $_controller->get($id);
                     $export->generate($record);
                 } else {
                     Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' ' . $_filter->getModelName() . ' id empty!');
                 }
             }
             // render pdf
             try {
                 $pdfOutput = $export->render();
             } catch (Zend_Pdf_Exception $e) {
                 Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' error creating pdf: ' . $e->__toString());
                 exit;
             }
             break;
         case 'ods':
             $result = $export->generate();
             break;
         default:
             if (in_array($format, array('csv', 'xls'))) {
                 $result = $export->generate($_filter);
             } else {
                 throw new Tinebase_Exception_UnexpectedValue('Format ' . $format . ' not supported.');
             }
     }
     // write headers
     $contentType = $export->getDownloadContentType();
     $filename = $export->getDownloadFilename($_filter->getApplicationName(), $format);
     header("Pragma: public");
     header("Cache-Control: max-age=0");
     header("Content-Disposition: " . ($format == 'pdf' ? 'inline' : 'attachment') . '; filename=' . $filename);
     header("Content-Description: {$format} File");
     header("Content-type: {$contentType}");
     // output export file
     switch ($format) {
         case 'pdf':
             echo $pdfOutput;
             break;
         case 'xls':
             // redirect output to client browser
             $export->write($result);
             break;
         default:
             readfile($result);
             unlink($result);
     }
     // reset max execution time to old value
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
 }
 /**
  * download message part
  * 
  * @param string $_messageId
  * @param string $_partId
  * @param string $disposition
  * @param boolean $validateImage
  */
 protected function _outputMessagePart($_messageId, $_partId = NULL, $disposition = 'attachment', $validateImage = FALSE)
 {
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(0);
     try {
         // fetch extracted winmail dat contents
         if (strstr($_partId, 'winmail-')) {
             $partIndex = explode('winmail-', $_partId);
             $partIndex = intval($partIndex[1]);
             $files = Felamimail_Controller_Message::getInstance()->extractWinMailDat($_messageId);
             $file = $files[$partIndex];
             $part = NULL;
             $path = Tinebase_Core::getTempDir() . '/winmail/';
             $path = $path . $_messageId . '/';
             $contentType = mime_content_type($path . $file);
             $this->_prepareHeader($file, $contentType);
             $stream = fopen($path . $file, 'r');
         } else {
             // fetch normal attachment
             $part = Felamimail_Controller_Message::getInstance()->getMessagePart($_messageId, $_partId);
             $contentType = $_partId === NULL ? Felamimail_Model_Message::CONTENT_TYPE_MESSAGE_RFC822 : $part->type;
             $filename = $this->_getDownloadFilename($part, $_messageId, $contentType);
             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . ' filename: ' . $filename . ' content type ' . $contentType);
             }
             if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                 Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($part, TRUE));
             }
             $this->_prepareHeader($filename, $contentType);
             $stream = $_partId === NULL ? $part->getRawStream() : $part->getDecodedStream();
         }
         if ($validateImage) {
             $tmpPath = tempnam(Tinebase_Core::getTempDir(), 'tine20_tmp_imgdata');
             $tmpFile = fopen($tmpPath, 'w');
             stream_copy_to_stream($stream, $tmpFile);
             fclose($tmpFile);
             // @todo check given mimetype or all images types?
             if (!Tinebase_ImageHelper::isImageFile($tmpPath)) {
                 if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) {
                     Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Resource is no image file: ' . $filename);
                 }
             } else {
                 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                     Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Verified ' . $contentType . ' image.');
                 }
                 readfile($tmpPath);
             }
         } else {
             fpassthru($stream);
         }
         fclose($stream);
     } catch (Exception $e) {
         Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Failed to get message part: ' . $e->getMessage());
     }
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     exit;
 }
 /**
  * prepare long running request
  * - execution time
  * - session write close
  *
  * @param integer $executionTime
  * @return integer old max execution time
  */
 protected function _longRunningRequest($executionTime = 0)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Close session to allow other requests and set max execution time to ' . $executionTime);
     }
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime($executionTime);
     Tinebase_Session::writeClose(true);
     return $oldMaxExcecutionTime;
 }
Пример #25
0
 /**
  * send Zend_Mail message via smtp
  * 
  * @param  mixed      $_accountId
  * @param  Zend_Mail  $_message
  * @param  bool       $_saveInSent
  * @return Zend_Mail
  */
 public function sendZendMail($_accountId, Zend_Mail $_mail, $_saveInSent = false)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Sending message with subject ' . $_mail->getSubject());
     }
     // increase execution time (sending message with attachments can take a long time)
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(300);
     // 5 minutes
     // get account
     $account = $_accountId instanceof Felamimail_Model_Account ? $_accountId : Felamimail_Controller_Account::getInstance()->get($_accountId);
     $this->_setMailFrom($_mail, $account);
     $this->_setMailHeaders($_mail, $account);
     $this->_sendMailViaTransport($_mail, $account, NULL, $_saveInSent);
     // reset max execution time to old value
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     return $_mail;
 }