/** * testCreateTempFileWithNonUTF8Filename * * @see 0008184: files with umlauts in filename cannot be attached with safari */ public function testCreateTempFileWithNonUTF8Filename() { $filename = file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . 'brokenname.txt'); $path = tempnam(Tinebase_Core::getTempDir(), 'tine_tempfile_test_'); $tempFile = $this->_instance->createTempFile($path, $filename); $this->assertEquals("_tüt", $tempFile->name); }
/** * 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'); } }
public function testExportLetter() { $filter = new Addressbook_Model_ContactFilter(array(array('field' => 'n_given', 'operator' => 'equals', 'value' => 'Robert'))); $doc = new Addressbook_Export_Doc($filter); $doc->generate(); $tempfile = tempnam(Tinebase_Core::getTempDir(), __METHOD__ . '_') . '.docx'; $doc->save($tempfile); $this->assertGreaterThan(0, filesize($tempfile)); }
public function _testReadWriteCycleSucks() { PhpWord\Settings::setTempDir(Tinebase_Core::getTempDir()); $source = str_replace('tests/tine20', 'tine20', __DIR__) . '/templates/addressbook_contact_letter.docx'; $phpWord = PhpWord\IOFactory::load($source); $tempfile = tempnam(Tinebase_Core::getTempDir(), __METHOD__ . '_') . '.docx'; $writer = $phpWord->save($tempfile); `open {$tempfile}`; }
/** * 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; }
/** * initializes the config * - overwrite session_save_path */ public function _setupCliConfig() { $configData = @(include 'config.inc.php'); if ($configData === false) { echo 'UNKNOWN STATUS / CONFIG FILE NOT FOUND (include path: ' . get_include_path() . ")\n"; exit(3); } $configData['sessiondir'] = Tinebase_Core::getTempDir(); $config = new Zend_Config($configData); Tinebase_Core::set(Tinebase_Core::CONFIG, $config); }
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(); }
public function testExportXls() { $filter = new Addressbook_Model_ContactFilter(array(array('field' => 'n_given', 'operator' => 'equals', 'value' => 'Robert'))); $export = new Addressbook_Export_Xls($filter); $xls = $export->generate(); $tempfile = tempnam(Tinebase_Core::getTempDir(), __METHOD__ . '_') . '.xlsx'; // TODO add a save() fn to Tinebase_Export_Spreadsheet_Xls $xlswriter = PHPExcel_IOFactory::createWriter($xls, 'Excel5'); $xlswriter->setPreCalculateFormulas(FALSE); $xlswriter->save($tempfile); $this->assertGreaterThan(0, filesize($tempfile)); }
/** * download config as config file * * @param array $data */ public function downloadConfig($data) { if (!Setup_Core::configFileExists() || Setup_Core::isRegistered(Setup_Core::USER)) { $data = Zend_Json::decode($data, Zend_Json::TYPE_ARRAY); $tmpFile = tempnam(Tinebase_Core::getTempDir(), 'tine20_'); Setup_Controller::getInstance()->writeConfigToFile($data, TRUE, $tmpFile); $configData = file_get_contents($tmpFile); unlink($tmpFile); header("Pragma: public"); header("Cache-Control: max-age=0"); header("Content-Disposition: attachment; filename=config.inc.php"); header("Content-Description: PHP File"); header("Content-type: text/plain"); die($configData); } }
/** * returns image metadata * * @param blob $_blob * @return array * @throws Tinebase_Exception_UnexpectedValue */ public static function getImageInfoFromBlob($_blob) { $tmpPath = tempnam(Tinebase_Core::getTempDir(), 'tine20_tmp_gd'); if ($tmpPath === FALSE) { throw new Tinebase_Exception('Could not generate temporary file.'); } file_put_contents($tmpPath, $_blob); $imgInfo = getimagesize($tmpPath); unlink($tmpPath); if (!in_array($imgInfo['mime'], array('image/png', 'image/jpeg', 'image/gif'))) { throw new Tinebase_Exception_UnexpectedValue('given blob does not contain valid image data.'); } if (!array_key_exists('channels', $imgInfo)) { Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' Uploaded ' . $imgInfo['mime'] . ' image had no channel information. Setting channels to 3.'); $imgInfo['channels'] = 3; } return array('width' => $imgInfo[0], 'height' => $imgInfo[1], 'bits' => $imgInfo['bits'], 'channels' => $imgInfo['channels'], 'mime' => $imgInfo['mime'], 'blob' => $_blob); }
public function testExportSimpleDocSheet() { // skip tests for php7 // ERROR: PHP Fatal error: Cannot use PhpOffice\PhpWord\Shared\String as String because 'String' is a special // class name in /usr/local/share/tine20.git/tine20/vendor/phpoffice/phpword/src/PhpWord/TemplateProcessor.php // on line 23 if (PHP_VERSION_ID >= 70000) { $this->markTestSkipped('FIXME 0011730: fix doc export for php7'); } // make sure definition is imported $definitionFile = __DIR__ . '/../../../../tine20/Calendar/Export/definitions/cal_default_doc_sheet.xml'; $calendarApp = Tinebase_Application::getInstance()->getApplicationByName('Calendar'); Tinebase_ImportExportDefinition::getInstance()->updateOrCreateFromFilename($definitionFile, $calendarApp, 'cal_default_doc_sheet'); // Tinebase_TransactionManager::getInstance()->commitTransaction($this->_transactionId); // @TODO have some demodata to export here $filter = new Calendar_Model_EventFilter(array()); $doc = new Calendar_Export_DocSheet($filter); $doc->generate(); $tempfile = tempnam(Tinebase_Core::getTempDir(), __METHOD__ . '_') . '.docx'; $doc->save($tempfile); $this->assertGreaterThan(0, filesize($tempfile)); // `open $tempfile`; }
/** * test pw replacements */ public function testPWReplacements() { $config = Tinebase_Core::getConfig(); $logfile = tempnam(Tinebase_Core::getTempDir(), 'testlog'); $writer = new Zend_Log_Writer_Stream($logfile); $formatter = new Tinebase_Log_Formatter(); $formatter->addReplacement($config->database->password); $writer->setFormatter($formatter); $this->_logger->addWriter($writer); $filter = new Zend_Log_Filter_Priority(5); $this->_logger->addFilter($filter); $this->_logger->notice($config->database->password); $loggerFile = file_get_contents($logfile); $writer->shutdown(); unlink($logfile); $this->assertFalse(strpos($loggerFile, $config->database->password), 'pw found!'); $this->assertContains('********', $loggerFile); if ($config->logger->logruntime || $config->logger->logdifftime) { $this->assertTrue(preg_match('/' . Tinebase_Core::getUser()->accountLoginName . ' \\d/', $loggerFile) === 1); } else { $this->assertContains(Tinebase_Core::getUser()->accountLoginName . ' - ', $loggerFile); } }
/** * 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; }
/** * set mail body * * @param Expressomail_mail $_mail * @param Expressomail_Model_Message $_message */ protected function _setMailBody(Expressomail_mail $_mail, Expressomail_Model_Message $_message) { if ($_message->content_type == Expressomail_Model_Message::CONTENT_TYPE_HTML) { // checking embedded images $embeddedImages = $this->processEmbeddedImagesInHtmlBody($_message->body); // now checking embedded signature base64 image $base64Images = $this->processEmbeddedImageSignatureInHtmlBody($_message->body); //now checking embed images for reply/forward $embeddedImagesReply = $this->processEmbeddedImagesInHtmlBodyForReply($_message->body); $cid = array(); if (count($embeddedImagesReply) > 0) { foreach ($embeddedImagesReply as $index => $embeddedImage) { $cid[$index] = $_mail->createCid($embeddedImage['messageId']); $_message->body = str_replace($embeddedImage['match'], 'src="cid:' . $cid[$index] . '"', $_message->body); } } if (count($embeddedImages) > 0) { $_message->body = str_ireplace('src="index.php?method=Expressomail.showTempImage&tempImageId=', 'src="cid:', $_message->body); } if (count($base64Images) > 0) { // there should be only one image in the signature $signature_cid = $_mail->createCid($base64Images[0][1]); $_message->body = preg_replace('/<img id="?user-signature-image-?[0-9]*"? alt="?[^\\"]+"? src="data:image\\/jpeg;base64,[^"]+">/', '<img id="user-signature-image" src="cid:' . $signature_cid . '"/>', $_message->body); } $_mail->setBodyHtml(Expressomail_Message::addHtmlMarkup($_message->body)); if (count($embeddedImages) > 0) { foreach ($embeddedImages as $embeddedImage) { $file = Tinebase_Core::getTempDir() . '/' . $embeddedImage[1]; $image = file_get_contents($file); $_mail->createHtmlRelatedAttachment($image, $embeddedImage[1], 'image/jpg', Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_BASE64, $embeddedImage[0]); } } if (count($base64Images) > 0) { // again, there should be only one image in the signature $image = base64_decode($base64Images[0][1]); $_mail->createHtmlRelatedAttachment($image, $signature_cid, 'image/jpg', Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_BASE64, $base64Images[0][0]); } if (count($embeddedImagesReply) > 0) { foreach ($embeddedImagesReply as $index => $embeddedImage) { try { $part = Expressomail_Controller_Message::getInstance()->getMessagePart($embeddedImage['messageId'], $embeddedImage['messagePart']); $image = base64_decode(stream_get_contents($part->getRawStream())); $_mail->createHtmlRelatedAttachment($image, $cid[$index], $part->type, Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_BASE64, $part->filename); } catch (Exception $exc) { } } } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $_mail->getBodyHtml(TRUE)); } } $plainBodyText = $_message->getPlainTextBody(); $_mail->setBodyText($plainBodyText); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $_mail->getBodyText(TRUE)); } }
/** * testSendMessageWithAttachmentWithoutExtension * * @see 0008328: email attachment without file extension is not sent properly */ public function testSendMessageWithAttachmentWithoutExtension() { $subject = 'attachment test'; $messageToSend = $this->_getMessageData('unittestalias@' . $this->_mailDomain, $subject); $tempfileName = 'jsontest' . Tinebase_Record_Abstract::generateUID(10); $tempfilePath = Tinebase_Core::getTempDir() . DIRECTORY_SEPARATOR . $tempfileName; file_put_contents($tempfilePath, 'some content'); $tempFile = Tinebase_TempFile::getInstance()->createTempFile($tempfilePath, $tempfileName); $messageToSend['attachments'] = array(array('tempFile' => array('id' => $tempFile->getId()))); $this->_json->saveMessage($messageToSend); $forwardMessage = $this->_searchForMessageBySubject($subject); $this->_foldersToClear = array('INBOX', $this->_account->sent_folder); $fullMessage = $this->_json->getMessage($forwardMessage['id']); $this->assertTrue(count($fullMessage['attachments']) === 1); $attachment = $fullMessage['attachments'][0]; $this->assertContains($tempfileName, $attachment['filename'], 'wrong attachment filename: ' . print_r($attachment, TRUE)); $this->assertEquals(16, $attachment['size'], 'wrong attachment size: ' . print_r($attachment, TRUE)); }
/** * (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')); }
/** * create contact pdf * * @param Addressbook_Model_Contact $_contact contact data * * @return string the contact pdf */ public function generate(Addressbook_Model_Contact $_contact) { $locale = Tinebase_Core::get('locale'); $translate = Tinebase_Translation::getTranslation('Addressbook'); // set user timezone $_contact->setTimezone(Tinebase_Core::getUserTimezone()); $contactFields = array(array('label' => $translate->_('Business Contact Data'), 'type' => 'separator'), array('label' => $translate->_('Organisation / Unit'), 'type' => 'singleRow', 'value' => array(array('org_name', 'org_unit')), 'glue' => ' / '), array('label' => $translate->_('Business Address'), 'type' => 'multiRow', 'value' => array('adr_one_street', 'adr_one_street2', array('adr_one_postalcode', 'adr_one_locality'), array('adr_one_region', 'adr_one_countryname'))), array('label' => $translate->_('Email'), 'value' => array('email')), array('label' => $translate->_('Telephone Work'), 'value' => array('tel_work')), array('label' => $translate->_('Telephone Cellphone'), 'value' => array('tel_cell')), array('label' => $translate->_('Telephone Car'), 'value' => array('tel_car')), array('label' => $translate->_('Telephone Fax'), 'value' => array('tel_fax')), array('label' => $translate->_('Telephone Page'), 'value' => array('tel_pager')), array('label' => $translate->_('URL'), 'value' => array('url')), array('label' => $translate->_('Role'), 'value' => array('role')), array('label' => $translate->_('Room'), 'value' => array('room')), array('label' => $translate->_('Assistant'), 'value' => array('assistent')), array('label' => $translate->_('Assistant Telephone'), 'value' => array('tel_assistent')), array('label' => $translate->_('Private Contact Data'), 'type' => 'separator'), array('label' => $translate->_('Private Address'), 'type' => 'multiRow', 'value' => array('adr_two_street', 'adr_two_street2', array('adr_two_postalcode', 'adr_two_locality'), array('adr_two_region', 'adr_two_countryname'))), array('label' => $translate->_('Email Home'), 'value' => array('email_home')), array('label' => $translate->_('Telephone Home'), 'value' => array('tel_home')), array('label' => $translate->_('Telephone Cellphone Private'), 'value' => array('tel_cell_private')), array('label' => $translate->_('Telephone Fax Home'), 'value' => array('tel_fax_home')), array('label' => $translate->_('URL Home'), 'value' => array('url_home')), array('label' => $translate->_('Other Data'), 'type' => 'separator'), array('label' => $translate->_('Birthday'), 'value' => array('bday')), array('label' => $translate->_('Job Title'), 'value' => array('title'))); try { $tineImage = Addressbook_Controller::getInstance()->getImage($_contact->getId()); Tinebase_ImageHelper::resize($tineImage, 160, 240, Tinebase_ImageHelper::RATIOMODE_PRESERVANDCROP); $tmpPath = tempnam(Tinebase_Core::getTempDir(), 'tine20_tmp_gd'); $tmpPath .= $tineImage->getImageExtension(); file_put_contents($tmpPath, $tineImage->blob); $contactPhoto = Zend_Pdf_Image::imageWithPath($tmpPath); unlink($tmpPath); } catch (Exception $e) { // gif images are not supported yet by zf (or some other error) if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $e->__toString()); } $contactPhoto = NULL; } // build title (name) + subtitle + icon $nameFields = array('n_prefix', 'n_given', 'n_middle', 'n_family', 'n_suffix'); $titleArray = array(); foreach ($nameFields as $nameField) { if (!empty($_contact[$nameField])) { $titleArray[] = $_contact[$nameField]; } } $title = implode(' ', $titleArray); $subtitle = $_contact->org_name; $titleIcon = "/images/oxygen/32x32/apps/system-users.png"; // add data to array $record = array(); foreach ($contactFields as $fieldArray) { if (!isset($fieldArray['type']) || $fieldArray['type'] !== 'separator') { $values = array(); foreach ($fieldArray['value'] as $valueFields) { $content = array(); if (is_array($valueFields)) { $keys = $valueFields; } else { $keys = array($valueFields); } foreach ($keys as $key) { if ($_contact->{$key} instanceof Tinebase_DateTime) { $content[] = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_contact->{$key}, NULL, NULL, 'date'); } elseif (!empty($_contact->{$key})) { if (preg_match("/countryname/", $key)) { $content[] = Zend_Locale::getTranslation($_contact->{$key}, 'country', $locale); } else { $content[] = $_contact->{$key}; } } } if (!empty($content)) { $glue = isset($fieldArray['glue']) ? $fieldArray['glue'] : " "; $values[] = implode($glue, $content); } } if (!empty($values)) { $record[] = array('label' => $fieldArray['label'], 'type' => isset($fieldArray['type']) ? $fieldArray['type'] : 'singleRow', 'value' => sizeof($values) === 1 ? $values[0] : $values); } } elseif (isset($fieldArray['type']) && $fieldArray['type'] === 'separator') { $record[] = $fieldArray; } } // add notes $record = $this->_addActivities($record, $_contact->notes); //print_r($record); // tags $tags = isset($_contact['tags']) ? $_contact['tags'] : array(); // generate pdf $this->generatePdf($record, $title, $subtitle, $tags, $_contact->note, $titleIcon, $contactPhoto, array(), FALSE); }
/** * @param string $partId * @param string $messageId * * @return array */ public function extractWinMailDat($messageId, $partId = NULL) { $path = Tinebase_Core::getTempDir() . '/winmail/'; // create base path if (!is_dir($path)) { mkdir($path); } // create path for this message id if (!is_dir($path . $messageId)) { mkdir($path . $messageId); $part = $this->getMessagePart($messageId, $partId); $path = $path . $messageId . '/'; $datFile = $path . 'winmail.dat'; $stream = $part->getDecodedStream(); $tmpFile = fopen($datFile, 'w'); stream_copy_to_stream($stream, $tmpFile); fclose($tmpFile); // find out filenames $files = array(); $fileString = explode(chr(10), Tinebase_Core::callSystemCommand('tnef -t ' . $datFile)); foreach ($fileString as $line) { $split = explode('|', $line); $clean = trim($split[0]); if (!empty($clean)) { $files[] = $clean; } } // extract files Tinebase_Core::callSystemCommand('tnef -C ' . $path . ' ' . $datFile); } else { // temp files still existing $dir = new DirectoryIterator($path . $messageId); $files = array(); foreach ($dir as $file) { if ($file->isFile() && $file->getFilename() != 'winmail.dat') { $files[] = $file->getFilename(); } } } asort($files); return $files; }
/** * create new PhpWord document * * @return void */ protected function _createDocument() { \PhpOffice\PhpWord\Settings::setTempDir(Tinebase_Core::getTempDir()); $templateFile = $this->_getTemplateFilename(); $this->_docObject = new \PhpOffice\PhpWord\PhpWord(); if ($templateFile !== NULL) { $this->_docTemplate = new \PhpOffice\PhpWord\TemplateProcessor($templateFile); } }
/** * returns binary string in given format * * @param string $_mime * @param int $_maxSize in bytes * @return string */ public function getBlob($_mime = 'image/jpeg', $_maxSize = 0) { if ($this->mime != $_mime) { $img = @imagecreatefromstring($this->blob); $tmpPath = tempnam(Tinebase_Core::getTempDir(), 'tine20_tmp_gd'); switch ($_mime) { case 'image/png': imagepng($img, $tmpPath, 0); break; case 'image/jpeg': imagejpeg($img, $tmpPath, 100); break; case 'image/gif': imagegif($img, $tmpPath); break; default: throw new Tinebase_Exception_InvalidArgument("Unsupported image type: " . $_mime); break; } $blob = file_get_contents($tmpPath); unlink($tmpPath); } else { $blob = $this->blob; } if ($_maxSize) { $originalSize = strlen($blob); if ($originalSize > $_maxSize) { $cacheId = Tinebase_Helper::convertCacheId(__METHOD__ . $this->id . $_mime . $_maxSize); if (Tinebase_Core::getCache()->test($cacheId)) { $blob = Tinebase_Core::getCache()->load($cacheId); return $blob; } // NOTE: resampling 1:1 through GD changes images size so // we always to through GD before furthor calculations $qS = $_maxSize / strlen($blob); $qD = $_mime != $this->mime ? sqrt($qS) : 1; $qF = 1; $i = 0; do { // feedback fault $qD = $qD * $qF; $clone = clone $this; $clone->resize(floor($this->width * $qD), floor($this->height * $qD), self::RATIOMODE_PRESERVANDCROP); $blob = $clone->getBlob(); $size = strlen($blob); // size factor achieved; $qSA = $size / $originalSize; // size fault factor $qF = sqrt($qS / $qSA); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " resized {$this->id}: qS: {$qS} qD: {$qD} qSA: {$qSA} sizeA: {$size} qF: {$qF} "); } // feedback size fault factor if we are still to big or more than 1% to small per attempt } while ($qF > 1 + $i++ * 0.01 || $qF < 1); Tinebase_Core::getCache()->save($blob, $cacheId, array(), null); } } return $blob; }
/** * get config options as Zend_Config_Xml object * * @param Tinebase_Model_ImportExportDefinition $_definition * @param array $_additionalOptions additional options * @return Zend_Config_Xml */ public static function getOptionsAsZendConfigXml(Tinebase_Model_ImportExportDefinition $_definition, $_additionalOptions = array()) { $tmpfname = tempnam(Tinebase_Core::getTempDir(), "tine_tempfile_"); if (!$tmpfname) { throw new Tinebase_Exception_AccessDenied('Could not create temporary file.'); } $handle = fopen($tmpfname, "w"); fwrite($handle, $_definition->plugin_options); fclose($handle); // read file with Zend_Config_Xml $config = new Zend_Config_Xml($tmpfname, null, TRUE); $config->merge(new Zend_Config($_additionalOptions)); unlink($tmpfname); return $config; }
/** * testCreateFileCountTempDir * * @see 0007370: Unable to upload files */ public function testCreateFileCountTempDir() { $tmp = Tinebase_Core::getTempDir(); $filecountInTmpBefore = count(scandir($tmp)); $this->testCreateFileNodeWithTempfile(); // check if tempfile has been created in tine20 tempdir $filecountInTmpAfter = count(scandir($tmp)); $this->assertEquals($filecountInTmpBefore + 2, $filecountInTmpAfter, '2 tempfiles should have been created'); }
private static function pullCertificateFromMessage($msgTempFile) { $return = false; $path = Tinebase_Core::getTempDir(); // if(!$msg) // { // return $return; // } $w = ''; $output = array(); $w = exec('cat ' . $msgTempFile . ' | openssl smime -pk7out | openssl pkcs7 -print_certs', $output); if (!$w == '') { return $return; } $aux1 = ''; // string with output from command... foreach ($output as $line) { $aux1 .= $line . chr(0xa); } // certificates array.. $aux2 = explode('-----BEGIN CERTIFICATE-----', $aux1); array_shift($aux2); // fix certificates.. $aux5 = array(); foreach ($aux2 as $item) { $aux3 = explode('-----END CERTIFICATE-----', $item); $aux4 = '-----BEGIN CERTIFICATE-----' . $aux3[0] . '-----END CERTIFICATE-----'; $aux5[] = $aux4; } // only one no CA certificate .... foreach ($aux5 as $item) { $Data_cert = Custom_Auth_ModSsl_Certificate_Factory::buildCertificate($item, FALSE); if (!$Data_cert->isCA()) { $return = $Data_cert; break; } } return $return; }
protected function _validityCheck() { $cdError = Tinebase_Translation::getTranslation('Tinebase')->_('Couldn\'t verify if certificate was revoked.'); if (!is_file($this->casfile)) { $this->status['errors'][] = 'Invalid Certificate .(CA-01)'; //'CAs file not found.'; $this->status['isValid'] = false; return; } $temporary_files = array(); $certTempFile = self::generateTempFilename($temporary_files, Tinebase_Core::getTempDir()); self::writeTo($certTempFile, $this->certificate); // Get serialnumber by comand line ... $out = array(); $w = exec('openssl x509 -inform PEM -in ' . $certTempFile . ' -noout -serial', $out); $aux = explode('serial=', $out[0]); if (isset($aux[1])) { $this->serialNumber = $aux[1]; } else { $this->serialNumber = null; } $out = array(); // certificate verify ... $w = exec('openssl verify -CAfile ' . $this->casfile . ' ' . $certTempFile, $out); self::removeTempFiles($temporary_files); $aux = explode(' ', $w); if (isset($aux[1])) { if ($aux[1] != 'OK') { foreach ($out as $item) { $aux = explode(':', $item); if (isset($aux[1])) { $this->status['errors'][] = Tinebase_Translation::getTranslation('Tinebase')->_(trim($aux[1])); $this->status['isValid'] = false; } } return; } } else { $this->status['errors'][] = isset($aux[1]) ? trim($aux[1]) : $cdError . '(CD-01)'; $this->status['isValid'] = false; } }
/** * zip message(s) * * @param array $msgIds * @return Object */ public function zipMessages($msgIds) { $zipArchive = new ZipArchive(); $tmpFile = tempnam(Tinebase_Core::getTempDir(), 'tine20_'); if ($zipArchive->open($tmpFile) === TRUE) { foreach ($msgIds as $msgId) { $part = Expressomail_Controller_Message::getInstance()->getRawMessage($msgId); $filename = $msgId . '.eml'; $zipArchive->addFromString($filename, $part); } $zipArchive->close(); } $zipFile = Tinebase_TempFile::getInstance()->createTempFile($tmpFile, "mensagem.zip"); return $zipFile; }
/** * create new open document document * * @return void */ protected function _createDocument() { // check for template file $templateFile = $this->_getTemplateFilename(); $this->_openDocumentObject = new OpenDocument_Document(OpenDocument_Document::SPREADSHEET, $templateFile, Tinebase_Core::getTempDir(), $this->_userStyles); }
/** * setup the cache and add it to zend registry * * @param bool $_enabled disabled cache regardless what's configured in config.inc.php * * @todo use the same config keys as Zend_Cache (backend + frontend) to simplify this */ public static function setupCache($_enabled = true) { if (self::$cacheStatus !== NULL && self::$cacheStatus === $_enabled) { return; } $config = self::getConfig(); if ($config->caching && $config->caching->active) { if (isset($config->caching->shared) && $config->caching->shared === true) { self::set(self::SHAREDCACHE, true); } else { self::set(self::SHAREDCACHE, false); } } // create zend cache if ($_enabled === true && $config->caching && $config->caching->active) { $logging = $config->caching->logging ? $config->caching->logging : false; $logger = self::getLogger(); $frontendOptions = array('lifetime' => $config->caching->lifetime ? $config->caching->lifetime : 7200, 'automatic_serialization' => true, 'caching' => true, 'automatic_cleaning_factor' => 0, 'write_control' => false, 'logging' => $logging, 'logger' => $logger); $backendType = $config->caching->backend ? ucfirst($config->caching->backend) : 'File'; $backendOptions = $config->caching->backendOptions ? $config->caching->backendOptions->toArray() : false; if (!$backendOptions) { switch ($backendType) { case 'File': $backendOptions = array('cache_dir' => $config->caching->path ? $config->caching->path : Tinebase_Core::getTempDir(), 'hashed_directory_level' => $config->caching->dirlevel ? $config->caching->dirlevel : 4, 'logging' => $logging, 'logger' => $logger); break; case 'Memcached': $host = $config->caching->host ? $config->caching->host : (isset($config->caching->memcached->host) ? $config->caching->memcached->host : 'localhost'); $port = $config->caching->port ? $config->caching->port : (isset($config->caching->memcached->port) ? $config->caching->memcached->port : 11211); $backendOptions = array('servers' => array('host' => $host, 'port' => $port, 'persistent' => TRUE)); break; case 'Redis': $host = $config->caching->host ? $config->caching->host : ($config->caching->redis->host ? $config->caching->redis->host : 'localhost'); $port = $config->caching->port ? $config->caching->port : ($config->caching->redis->port ? $config->caching->redis->port : 6379); if ($config->caching && $config->caching->prefix) { $prefix = $config->caching->prefix; } else { if ($config->caching && $config->caching->redis && $config->caching->redis->prefix) { $prefix = $config->caching->redis->prefix; } else { $prefix = $config->database && $config->database->tableprefix ? $config->database->tableprefix : 'tine20'; } } $prefix .= '_CACHE_'; $backendOptions = array('servers' => array('host' => $host, 'port' => $port, 'prefix' => $prefix)); break; default: $backendOptions = array(); break; } } Tinebase_Core::getLogger()->INFO(__METHOD__ . '::' . __LINE__ . " cache of backend type '{$backendType}' enabled"); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { // logger is an object, that makes ugly traces :) $backendOptionsWithoutLogger = $backendOptions; if (isset($backendOptionsWithoutLogger['logger'])) { unset($backendOptionsWithoutLogger['logger']); } Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . " backend options: " . print_r($backendOptionsWithoutLogger, TRUE)); } } else { Tinebase_Core::getLogger()->INFO(__METHOD__ . '::' . __LINE__ . ' Cache disabled'); $backendType = 'Test'; $frontendOptions = array('caching' => false); $backendOptions = array(); } // getting a Zend_Cache_Core object try { $cache = Zend_Cache::factory('Core', $backendType, $frontendOptions, $backendOptions); } catch (Exception $e) { Tinebase_Exception::log($e); $enabled = false; if ('File' === $backendType && !is_dir($backendOptions['cache_dir'])) { Tinebase_Core::getLogger()->INFO(__METHOD__ . '::' . __LINE__ . ' Create cache directory and re-try'); if (mkdir($backendOptions['cache_dir'], 0770, true)) { $enabled = $_enabled; } } self::setupCache($enabled); return; } // some important caches Zend_Locale::setCache($cache); Zend_Translate::setCache($cache); Zend_Db_Table_Abstract::setDefaultMetadataCache($cache); self::set(self::CACHE, $cache); self::$cacheStatus = $_enabled; }
/** * joins all given tempfiles in given order to a single new tempFile * * @param Tinebase_Record_RecordSet $_tempFiles * @return Tinebase_Model_TempFile */ public function joinTempFiles($_tempFiles) { $path = tempnam(Tinebase_Core::getTempDir(), 'tine_tempfile_'); $name = preg_replace('/\\.\\d+\\.chunk$/', '', $_tempFiles->getFirstRecord()->name); $type = $_tempFiles->getFirstRecord()->type; $size = 0.0; $fJoin = fopen($path, 'w+b'); foreach ($_tempFiles as $tempFile) { $fChunk = @fopen($tempFile->path, "rb"); if (!$fChunk) { throw new Tinebase_Exception_UnexpectedValue("Can not open chunk {$tempFile->id}"); } // NOTE: stream_copy_to_stream is about 15% slower while (!feof($fChunk)) { $bytesWritten = fwrite($fJoin, fread($fChunk, 2097152)); $size += (double) $bytesWritten; } fclose($fChunk); } fclose($fJoin); return $this->createTempFile($path, $name, $type, $size); }
public function testCustomTranslations() { $lang = 'en_GB'; $translationPath = Tinebase_Core::getTempDir() . "/tine20/translations"; Tinebase_Config::getInstance()->translations = $translationPath; $translationDir = "{$translationPath}/{$lang}/Tinebase/translations"; @mkdir($translationDir, 0777, TRUE); $poFile = "{$translationDir}/{$lang}.po"; $poData = 'msgid "" msgstr "" "Project-Id-Version: Tine 2.0 - Tinebase\\n" "POT-Creation-Date: 2008-05-17 22:12+0100\\n" "PO-Revision-Date: 2008-07-29 21:14+0100\\n" "Last-Translator: Cornelius Weiss <*****@*****.**>\\n" "Language-Team: Tine 2.0 Translators\\n" "MIME-Version: 1.0\\n" "Content-Type: text/plain; charset=UTF-8\\n" "Content-Transfer-Encoding: 8bit\\n" "X-Poedit-Language: en\\n" "X-Poedit-Country: US\\n" "X-Poedit-SourceCharset: utf-8\\n" "Plural-Forms: nplurals=2; plural=n != 1;\\n" "X-Tine20-Language: My Language\\n" "X-Tine20-Country: MY REGION\\n" #: Acl/Rights/Abstract.php:75 msgid "run" msgstr "изпълни" '; file_put_contents($poFile, $poData); $availableTranslations = Tinebase_Translation::getAvailableTranslations(); foreach ($availableTranslations as $langInfo) { if ($langInfo['locale'] == $lang) { $customInfo = $langInfo; } } // assert cutom lang is available $this->assertTrue(isset($customInfo), 'custom translation not in list of available translations'); $this->assertEquals('My Language', $customInfo['language'], 'custom language param missing'); $this->assertEquals('MY REGION', $customInfo['region'], 'custom region param missing'); // test the translation $translation = Tinebase_Translation::getTranslation('Tinebase', new Zend_Locale($lang)); // NOTE: Zent_Translate does not work with .po files //$this->assertEquals("изпълни", $translation->_('run')); $jsTranslations = Tinebase_Translation::getJsTranslations($lang, 'Tinebase'); $this->assertEquals(1, preg_match('/изпълни/', $jsTranslations)); Tinebase_Core::setupUserLocale(); }
/** * returns binary string in given format * * @param string $_mime * @param int $_maxSize in bytes * @return string */ public function getBlob($_mime = 'image/jpeg', $_maxSize = 0) { if ($this->mime != $_mime) { $img = @imagecreatefromstring($this->blob); $tmpPath = tempnam(Tinebase_Core::getTempDir(), 'tine20_tmp_gd'); switch ($_mime) { case 'image/png': imagepng($img, $tmpPath, 0); break; case 'image/jpeg': imagejpeg($img, $tmpPath, 100); break; case 'image/gif': imagegif($img, $tmpPath); break; default: throw new Tinebase_Exception_InvalidArgument("Unsupported image type: " . $_mime); break; } $blob = file_get_contents($tmpPath); unlink($tmpPath); } else { $blob = $this->blob; } if ($_maxSize && strlen($blob) > $_maxSize) { $q = $_maxSize / strlen($blob); $width = floor(sqrt(pow($this->width, 2) * $q)); $height = floor(sqrt(pow($this->height, 2) * $q)); $this->resize($width, $height, self::RATIOMODE_PRESERVANDCROP); return $this->getBlob($_mime, $_maxSize); } return $blob; }