/** * add attachments to mail * * @param Tinebase_Mail $_mail * @param Felamimail_Model_Message $_message * @throws Felamimail_Exception_IMAP */ protected function _addAttachments(Tinebase_Mail $_mail, Felamimail_Model_Message $_message) { if (!isset($_message->attachments) || empty($_message->attachments)) { return; } $maxAttachmentSize = $this->_getMaxAttachmentSize(); $size = 0; $tempFileBackend = Tinebase_TempFile::getInstance(); foreach ($_message->attachments as $attachment) { if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Adding attachment: ' . (is_object($attachment) ? print_r($attachment->toArray(), TRUE) : print_r($attachment, TRUE))); } if (isset($attachment['type']) && $attachment['type'] == Felamimail_Model_Message::CONTENT_TYPE_MESSAGE_RFC822 && $_message->original_id instanceof Felamimail_Model_Message) { $part = $this->getMessagePart($_message->original_id, $_message->original_part_id ? $_message->original_part_id : NULL); $part->decodeContent(); $name = $attachment['name'] . '.eml'; $type = $attachment['type']; if (!empty($attachment['size'])) { $size += $attachment['size']; } } else { $tempFile = $attachment instanceof Tinebase_Model_TempFile ? $attachment : (isset($attachment['tempFile']) || array_key_exists('tempFile', $attachment) ? $tempFileBackend->get($attachment['tempFile']['id']) : NULL); if ($tempFile === NULL) { continue; } if (!$tempFile->path) { Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' Could not find attachment.'); continue; } // get contents from uploaded file $stream = fopen($tempFile->path, 'r'); $part = new Zend_Mime_Part($stream); // RFC822 attachments are not encoded, set all others to ENCODING_BASE64 $part->encoding = $tempFile->type == Felamimail_Model_Message::CONTENT_TYPE_MESSAGE_RFC822 ? null : Zend_Mime::ENCODING_BASE64; $name = $tempFile->name; $type = $tempFile->type; if (!empty($tempFile->size)) { $size += $tempFile->size; } } $part->setTypeAndDispositionForAttachment($type, $name); if ($size > $maxAttachmentSize) { if (Tinebase_Core::isLogLevel(Zend_Log::NOTICE)) { Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' Current attachment size: ' . Tinebase_Helper::convertToMegabytes($size) . ' MB / allowed size: ' . Tinebase_Helper::convertToMegabytes($maxAttachmentSize) . ' MB'); } throw new Felamimail_Exception_IMAP('Maximum attachment size exceeded. Please remove one or more attachments.'); } if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Adding attachment ' . $part->type); } $_mail->addAttachment($part); } }
/** * copy tempfile data to file path * * @param mixed $tempFile Tinebase_Model_Tree_Node with property hash, tempfile or stream Tinebase_Model_Tempfile tempfile string with tempFile id array with [id] => tempFile id (this is odd IMHO) stream stream ressource NULL create empty file * @param string $path * @throws Tinebase_Exception_AccessDenied */ public function copyTempfile($tempFile, $path) { if ($tempFile === NULL) { $tempStream = fopen('php://memory', 'r'); } else { if (is_resource($tempFile)) { $tempStream = $tempFile; } else { if (is_string($tempFile) || is_array($tempFile)) { $tempFile = Tinebase_TempFile::getInstance()->getTempFile($tempFile); return $this->copyTempfile($tempFile, $path); } else { if ($tempFile instanceof Tinebase_Model_Tree_Node) { if (isset($tempFile->hash)) { $hashFile = $this->_basePath . '/' . substr($tempFile->hash, 0, 3) . '/' . substr($tempFile->hash, 3); $tempStream = fopen($hashFile, 'r'); } else { if (is_resource($tempFile->stream)) { $tempStream = $tempFile->stream; } else { return $this->copyTempfile($tempFile->tempFile, $path); } } } else { if ($tempFile instanceof Tinebase_Model_TempFile) { $tempStream = fopen($tempFile->path, 'r'); } else { throw new Tinebase_Exception_UnexpectedValue('unexpected tempfile value'); } } } } } return $this->copyStream($tempStream, $path); }
/** * add attachments to mail * * @param Expressomail_mail $_mail * @param Expressomail_Model_Message $_message */ protected function _addAttachments(Expressomail_mail $_mail, Expressomail_Model_Message $_message) { if (!isset($_message->attachments) || empty($_message->attachments)) { return; } $size = 0; $tempFileBackend = Tinebase_TempFile::getInstance(); foreach ($_message->attachments as $attachment) { if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Adding attachment: ' . (is_object($attachment) ? print_r($attachment->toArray(), TRUE) : print_r($attachment, TRUE))); } if ($attachment['partId'] && $_message->original_id instanceof Expressomail_Model_Message) { $originlPart = $this->getMessagePart($_message->original_id, $attachment['partId']); switch ($originlPart->encoding) { case Zend_Mime::ENCODING_BASE64: $part = new Zend_Mime_Part(base64_decode(stream_get_contents($originlPart->getRawStream()))); $part->encoding = Zend_Mime::ENCODING_BASE64; break; case Zend_Mime::ENCODING_QUOTEDPRINTABLE: $part = new Zend_Mime_Part(quoted_printable_decode(stream_get_contents($originlPart->getRawStream()))); $part->encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE; break; default: $part = new Zend_Mime_Part(stream_get_contents($originlPart->getRawStream())); $part->encoding = null; break; } $name = $attachment['name']; $type = $attachment['type']; } else { $tempFile = $attachment instanceof Tinebase_Model_TempFile ? $attachment : (array_key_exists('tempFile', $attachment) ? $tempFileBackend->get($attachment['tempFile']['id']) : NULL); if ($tempFile === NULL) { continue; } if (!$tempFile->path) { Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' Could not find attachment.'); continue; } // get contents from uploaded file $stream = fopen($tempFile->path, 'r'); $part = new Zend_Mime_Part($stream); // RFC822 attachments are not encoded, set all others to ENCODING_BASE64 $part->encoding = $tempFile->type == Expressomail_Model_Message::CONTENT_TYPE_MESSAGE_RFC822 ? null : Zend_Mime::ENCODING_BASE64; $name = $tempFile->name; $type = $tempFile->type; // try to detect the correct file type, on error fallback to the default application/octet-stream if ($tempFile->type == "undefined" || $tempFile->type == "unknown") { try { $finfo = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_file($finfo, $tempFile->path); } catch (Exception $e) { $type = "application/octet-stream"; } try { finfo_close($finfo); } catch (Exception $e) { } } } $part->disposition = Zend_Mime::DISPOSITION_ATTACHMENT; $name = Zend_Mime::encodeQuotedPrintableHeader(addslashes($name), 'utf-8'); $partTypeString = $type . '; name="' . $name . '"'; $part->type = $partTypeString; if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Adding attachment ' . $partTypeString); } $_mail->addAttachment($part); } }
/** * 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 $this->_longRunningRequest(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'; return $importResult; }
/** * handle chunked upload * * @param string $name Name of the file * @param resource $data payload, passed as a readable stream resource. * @throws \Sabre\DAV\Exception\BadRequest * @return boolean|Tinebase_Model_TempFile */ public static function handleOwnCloudChunkedFileUpload($name, $data) { if (!isset($_SERVER['CONTENT_LENGTH'])) { throw new \Sabre\DAV\Exception\BadRequest('CONTENT_LENGTH header missing!'); } $matched = preg_match('/(?P<name>.*)-chunking-(?P<tempId>\\d+)-(?P<totalCount>\\d+)-(?P<chunkId>\\d+)/', $name, $chunkInfo); if (!$matched) { throw new \Sabre\DAV\Exception\BadRequest('bad filename provided: ' . $name); } // copy chunk to temp file $path = Tinebase_TempFile::getTempPath(); $tempfileHandle = fopen($path, "w"); if (!$tempfileHandle) { throw new \Sabre\DAV\Exception\BadRequest('Could not open tempfile while uploading! '); } do { stream_copy_to_stream($data, $tempfileHandle); } while (!feof($data)); $stat = fstat($tempfileHandle); if ($_SERVER['CONTENT_LENGTH'] != $stat['size']) { throw new \Sabre\DAV\Exception\BadRequest('uploaded part incomplete! expected size of: ' . $_SERVER['CONTENT_LENGTH'] . ' got: ' . $stat['size']); } fclose($tempfileHandle); $tempFileName = sha1(Tinebase_Core::getUser()->accountId . $chunkInfo['name'] . $chunkInfo['tempId']); Tinebase_TempFile::getInstance()->createTempFile($path, $tempFileName, $chunkInfo['chunkId'] + 1); // check if the client sent all chunks $uploadedChunks = Tinebase_TempFile::getInstance()->search(new Tinebase_Model_TempFileFilter(array(array('field' => 'name', 'operator' => 'equals', 'value' => $tempFileName))), new Tinebase_Model_Pagination(array('sort' => 'type', 'dir' => 'ASC'))); if ($uploadedChunks->count() != $chunkInfo['totalCount']) { return false; } // combine all chunks to one file $joinedFile = Tinebase_TempFile::getInstance()->joinTempFiles($uploadedChunks); $joinedFile->name = $chunkInfo['name']; foreach ($uploadedChunks as $chunk) { unlink($chunk->path); } return $joinedFile; }
/** * 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; }
/** * import course members * * @param string $tempFileId * @param string $courseId * @return array */ public function importMembers($tempFileId, $courseId) { $this->checkRight(Courses_Acl_Rights::ADD_NEW_USER); $tempFile = Tinebase_TempFile::getInstance()->getTempFile($tempFileId); // get definition and start import with admin user import csv plugin $definitionName = $this->_config->get(Courses_Config::STUDENTS_IMPORT_DEFINITION, 'admin_user_import_csv'); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Using import definition: ' . $definitionName); } $definition = Tinebase_ImportExportDefinition::getInstance()->getByName($definitionName); $course = $this->get($courseId); // check if group exists, too $group = $this->_groupController->get($course->group_id); $importer = Admin_Import_User_Csv::createFromDefinition($definition, $this->_getNewUserConfig($course)); $result = $importer->importFile($tempFile->path); $groupMembers = $this->_groupController->getGroupMembers($course->group_id); $this->_manageAccessGroups($groupMembers, $course); $this->_addToStudentGroup($groupMembers); $this->_addToUserDefaultGroup($groupMembers); return $result; }
/** * Sets up the fixture. * This method is called before a test is executed. * * @access protected */ protected function setUp() { $this->_instance = Tinebase_TempFile::getInstance(); parent::setUp(); }
/** * saveRecordWithImage */ public function testSaveRecordWithImage() { // create TEMPFILE and save in inv item $imageFile = dirname(dirname(dirname(dirname(__FILE__)))) . '/tine20/images/cancel.gif'; $tempImage = Tinebase_TempFile::getInstance()->createTempFile($imageFile); $imageUrl = Tinebase_Model_Image::getImageUrl('Tinebase', $tempImage->getId(), 'tempFile'); $invItem = $this->_getInventoryItem()->toArray(); $invItem['image'] = $imageUrl; $savedInvItem = $this->_json->saveInventoryItem($invItem); //$savedInvItem = $this->_json->getInventoryItem($savedInvItem['id']); $this->assertTrue(!empty($savedInvItem['image']), 'image url is empty'); $this->assertTrue(preg_match('/location=vfs&id=([a-z0-9]*)/', $savedInvItem['image']) == 1, print_r($savedInvItem, true)); // check if favicon is delivered $image = Tinebase_Model_Image::getImageFromImageURL($savedInvItem['image']); $this->assertEquals(52, $image->width); }
/** * import course members * * @param string $tempFileId * @param string $groupId * @param string $courseName * * @todo write test!! */ public function importMembers($tempFileId, $groupId, $courseId) { $tempFile = Tinebase_TempFile::getInstance()->getTempFile($tempFileId); $course = $this->_controller->get($courseId); $schoolName = strtolower(Tinebase_Department::getInstance()->get($course->type)->name); // get definition and start import with admin user import csv plugin $definitionName = $this->_config->get('import_definition', 'admin_user_import_csv'); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Using import definition: ' . $definitionName); } $definition = Tinebase_ImportExportDefinition::getInstance()->getByName($definitionName); $importer = Admin_Import_Csv::createFromDefinition($definition, array('group_id' => $groupId, 'accountEmailDomain' => isset($this->_config->domain) ? $this->_config->domain : '', 'accountHomeDirectoryPrefix' => isset($this->_config->basehomedir) ? $this->_config->basehomedir . $schoolName . '/' . $course->name . '/' : '', 'password' => strtolower($course->name), 'course' => $course, 'samba' => isset($this->_config->samba) ? array('homePath' => $this->_config->samba->basehomepath, 'homeDrive' => $this->_config->samba->homedrive, 'logonScript' => $course->name . $this->_config->samba->logonscript_postfix_member, 'profilePath' => $this->_config->samba->baseprofilepath . $schoolName . '\\' . $course->name . '\\', 'pwdCanChange' => new Tinebase_DateTime('@1'), 'pwdMustChange' => new Tinebase_DateTime('@1')) : array())); $importer->importFile($tempFile->path); // return members to update members grid and add to student group $members = $this->_getCourseMembers($groupId); // add to student group if available if (isset($this->_config->students_group) && !empty($this->_config->students_group)) { $groupController = Admin_Controller_Group::getInstance(); foreach ($members as $member) { $groupController->addGroupMember($this->_config->students_group, $member['id']); } } return array('results' => $members, 'status' => 'success'); }
/** * clear table as defined in arguments * can clear the following tables: * - credential_cache * - access_log * - async_job * - temp_files * * if param date is given (date=2010-09-17), all records before this date are deleted (if the table has a date field) * * @param $_opts * @return boolean success */ public function clearTable(Zend_Console_Getopt $_opts) { if (!$this->_checkAdminRight()) { return FALSE; } $args = $this->_parseArgs($_opts, array('tables'), 'tables'); $dateString = array_key_exists('date', $args) ? $args['date'] : NULL; $db = Tinebase_Core::getDb(); foreach ($args['tables'] as $table) { switch ($table) { case 'access_log': if ($dateString) { echo "\nRemoving all access log entries before {$dateString} ..."; $where = array($db->quoteInto($db->quoteIdentifier('li') . ' < ?', $dateString)); $db->delete(SQL_TABLE_PREFIX . $table, $where); } else { $db->query('TRUNCATE ' . SQL_TABLE_PREFIX . $table); } break; case 'async_job': $db->query('delete FROM ' . SQL_TABLE_PREFIX . 'async_job' . " WHERE status='success'"); break; case 'credential_cache': Tinebase_Auth_CredentialCache::getInstance()->clearCacheTable($dateString); break; case 'temp_files': Tinebase_TempFile::getInstance()->clearTable($dateString); break; default: echo 'Table ' . $table . " not supported or argument missing.\n"; } echo "\nCleared table {$table}."; } echo "\n\n"; return TRUE; }
/** * get attachment defined by temp file * * @param $attachment * @return null|Zend_Mime_Part * @throws Tinebase_Exception_NotFound */ protected function _getTempFileAttachment(&$attachment) { $tempFileBackend = Tinebase_TempFile::getInstance(); $tempFile = $attachment instanceof Tinebase_Model_TempFile ? $attachment : (isset($attachment['tempFile']) || array_key_exists('tempFile', $attachment) ? $tempFileBackend->get($attachment['tempFile']['id']) : NULL); if ($tempFile === null) { return null; } if (!$tempFile->path) { Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' Could not find attachment.'); return null; } // get contents from uploaded file $stream = fopen($tempFile->path, 'r'); $part = new Zend_Mime_Part($stream); // RFC822 attachments are not encoded, set all others to ENCODING_BASE64 $part->encoding = $tempFile->type == Felamimail_Model_Message::CONTENT_TYPE_MESSAGE_RFC822 ? null : Zend_Mime::ENCODING_BASE64; $attachment['name'] = $tempFile->name; $attachment['type'] = $tempFile->type; if (!empty($tempFile->size)) { $attachment['size'] = $tempFile->size; } return $part; }
/** * create node in backend * * @param string $_statpath * @param type * @param string $_tempFileId * @return Tinebase_Model_Tree_Node */ protected function _createNodeInBackend($_statpath, $_type, $_tempFileId = NULL) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Creating new path ' . $_statpath . ' of type ' . $_type); } $backend = $this->getAdapterBackend($_statpath); switch ($_type) { case Tinebase_Model_Tree_Node::TYPE_FILE: if ($_tempFileId !== NULL) { $tempFile = $_tempFileId instanceof Tinebase_Model_TempFile ? $_tempFileId : Tinebase_TempFile::getInstance()->getTempFile($_tempFileId); $backend->uploadFile($tempFile->path, $this->removeUserBasePath($_statpath)); } break; case Tinebase_Model_Tree_Node::TYPE_FOLDER: $backend->mkdir($this->removeUserBasePath($_statpath)); break; } return $this->stat($_statpath); }
/** * add attachement to record * * @param Tinebase_Record_Abstract $record * @param string $name * @param mixed $attachment @see Tinebase_FileSystem::copyTempfile * @return null|Tinebase_Model_Tree_Node */ public function addRecordAttachment(Tinebase_Record_Abstract $record, $name, $attachment) { // only occurs via unittests if (!$name && isset($attachment->tempFile) && !is_resource($attachment->tempFile)) { $attachment = Tinebase_TempFile::getInstance()->getTempFile($attachment->tempFile); $name = $attachment->name; } if ($attachment instanceof Tinebase_Model_Tree_Node && empty($name)) { $name = $attachment->name; } if (empty($name)) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Could not evaluate attachment name.'); } return null; } $attachmentsDir = $this->getRecordAttachmentPath($record, TRUE); $attachmentPath = $attachmentsDir . '/' . $name; if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Creating new record attachment ' . $attachmentPath); } if ($this->_fsController->fileExists($attachmentPath)) { throw new Tinebase_Exception_InvalidArgument('File already exists'); } $this->_fsController->copyTempfile($attachment, $attachmentPath); $node = $this->_fsController->stat($attachmentPath); return $node; }
/** * 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)); }
/** * downloads an image/thumbnail at a given size * * @param unknown_type $application * @param string $id * @param string $location * @param int $width * @param int $height * @param int $ratiomode */ public function getImage($application, $id, $location, $width, $height, $ratiomode) { $this->checkAuth(); // close session to allow other requests Zend_Session::writeClose(true); $clientETag = null; $ifModifiedSince = null; if (isset($_SERVER['If_None_Match'])) { $clientETag = trim($_SERVER['If_None_Match'], '"'); $ifModifiedSince = trim($_SERVER['If_Modified_Since'], '"'); } elseif (isset($_SERVER['HTTP_IF_NONE_MATCH']) && isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { $clientETag = trim($_SERVER['HTTP_IF_NONE_MATCH'], '"'); $ifModifiedSince = trim($_SERVER['HTTP_IF_MODIFIED_SINCE'], '"'); } if ($application == 'Tinebase' && $location == 'tempFile') { $tempFile = Tinebase_TempFile::getInstance()->getTempFile($id); $imgInfo = Tinebase_ImageHelper::getImageInfoFromBlob(file_get_contents($tempFile->path)); $image = new Tinebase_Model_Image($imgInfo + array('application' => $application, 'id' => $id, 'location' => $location)); } else { $image = Tinebase_Controller::getInstance()->getImage($application, $id, $location); } $serverETag = sha1($image->blob . $width . $height . $ratiomode); // cache for 3600 seconds $maxAge = 3600; header('Cache-Control: private, max-age=' . $maxAge); header("Expires: " . gmdate('D, d M Y H:i:s', Tinebase_DateTime::now()->addSecond($maxAge)->getTimestamp()) . " GMT"); // overwrite Pragma header from session header("Pragma: cache"); // if the cache id is still valid if ($clientETag == $serverETag) { header("Last-Modified: " . $ifModifiedSince); header("HTTP/1.0 304 Not Modified"); header('Content-Length: 0'); } else { #$cache = Tinebase_Core::getCache(); #if ($cache->test($serverETag) === true) { # $image = $cache->load($serverETag); #} else { if ($width != -1 && $height != -1) { Tinebase_ImageHelper::resize($image, $width, $height, $ratiomode); } # $cache->save($image, $serverETag); #} header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header('Content-Type: ' . $image->mime); header('Etag: "' . $serverETag . '"'); flush(); die($image->blob); } }
/** * view attachment * * @param string $Id */ public function viewAttachment($Id, $partId = NULL) { //$this->checkAuth(); $tempFile = Tinebase_TempFile::getInstance()->getTempFile($Id); if ($tempFile) { // todo: change to use PECL FileInfo library $fileData = file_get_contents($tempFile->path); // 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("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header('Content-Type: ' . $tempFile->type); header('Content-Disposition: attachment; filename="' . $tempFile->name . '"'); header('Etag: "' . $serverETag . '"'); flush(); die($fileData); return; } $this->_downloadMessagePart(explode(',', $Id), $partId); }
/** * copy tempfile data to file handle * * @param string $_tempFileId * @param resource $_fileHandle * @throws Filemanager_Exception */ protected function _copyTempfile($_tempFileId, $_fileHandle) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Reading data from tempfile ...'); } $tempFile = Tinebase_TempFile::getInstance()->getTempFile($_tempFileId); $tempData = fopen($tempFile->path, 'r'); if ($tempData) { stream_copy_to_stream($tempData, $_fileHandle); fclose($tempData); } else { throw new Filemanager_Exception('Could not read tempfile ' . $tempFile->path); } }
/** * Download temp file to review * * @param $tmpfileId */ public function downloadTempfile($tmpfileId) { $tmpFile = Tinebase_TempFile::getInstance()->getTempFile($tmpfileId); $this->_downloadFileNode($tmpFile, $tmpFile->path); exit; }
/** * returns binary image data from a image identified by a imagelink * * @param array $imageParams * @return string binary data * @throws Tinebase_Exception_UnexpectedValue */ public static function getImageData($imageParams) { $tempFile = Tinebase_TempFile::getInstance()->getTempFile($imageParams['id']); if (!Tinebase_ImageHelper::isImageFile($tempFile->path)) { throw new Tinebase_Exception_UnexpectedValue('Given file is not an image.'); } return file_get_contents($tempFile->path); }
/** * clear table as defined in arguments * can clear the following tables: * - credential_cache * - access_log * - async_job * - temp_files * * if param date is given (date=2010-09-17), all records before this date are deleted (if the table has a date field) * * @param $_opts * @return boolean success */ public function clearTable(Zend_Console_Getopt $_opts) { if (!$this->_checkAdminRight()) { return FALSE; } $args = $this->_parseArgs($_opts, array('tables'), 'tables'); $dateString = isset($args['date']) || array_key_exists('date', $args) ? $args['date'] : NULL; $db = Tinebase_Core::getDb(); foreach ($args['tables'] as $table) { switch ($table) { case 'access_log': $date = $dateString ? new Tinebase_DateTime($dateString) : NULL; Tinebase_AccessLog::getInstance()->clearTable($date); break; case 'async_job': $where = $dateString ? array($db->quoteInto($db->quoteIdentifier('end_time') . ' < ?', $dateString)) : array(); $where[] = $db->quoteInto($db->quoteIdentifier('status') . ' < ?', 'success'); echo "\nRemoving all successful async_job entries " . ($dateString ? "before {$dateString} " : "") . "..."; $deleteCount = $db->delete(SQL_TABLE_PREFIX . $table, $where); echo "\nRemoved {$deleteCount} records."; break; case 'credential_cache': Tinebase_Auth_CredentialCache::getInstance()->clearCacheTable($dateString); break; case 'temp_files': Tinebase_TempFile::getInstance()->clearTableAndTempdir($dateString); break; default: echo 'Table ' . $table . " not supported or argument missing.\n"; } echo "\nCleared table {$table}."; } echo "\n\n"; return TRUE; }
/** * gets image info and data * * @param string $application application which manages the image * @param string $identifier identifier of image/record * @param string $location optional additional identifier * @return Tinebase_Model_Image * @throws Tinebase_Exception_NotFound * @throws Tinebase_Exception_UnexpectedValue */ public function getImage($application, $identifier, $location = '') { if ($location === 'vfs') { $node = Tinebase_FileSystem::getInstance()->get($identifier); $path = Tinebase_Model_Tree_Node_Path::STREAMWRAPPERPREFIX . Tinebase_FileSystem::getInstance()->getPathOfNode($node, true); $image = Tinebase_ImageHelper::getImageInfoFromBlob(file_get_contents($path)); } else { if ($application == 'Tinebase' && $location == 'tempFile') { $tempFile = Tinebase_TempFile::getInstance()->getTempFile($identifier); $image = Tinebase_ImageHelper::getImageInfoFromBlob(file_get_contents($tempFile->path)); } else { $appController = Tinebase_Core::getApplicationInstance($application); if (!method_exists($appController, 'getImage')) { throw new Tinebase_Exception_NotFound("{$application} has no getImage function."); } $image = $appController->getImage($identifier, $location); } } if (!$image instanceof Tinebase_Model_Image) { if (is_array($image)) { $image = new Tinebase_Model_Image($image + array('application' => $application, 'id' => $identifier, 'location' => $location)); } else { throw new Tinebase_Exception_UnexpectedValue('broken image'); } } return $image; }
/** * joins all given tempfiles in given order to a single new tempFile * * @param array of tempfiles arrays $tempFiles * @return array new tempFile */ public function joinTempFiles($tempFilesData) { $tempFileRecords = new Tinebase_Record_RecordSet('Tinebase_Model_TempFile'); foreach ($tempFilesData as $tempFileData) { $record = new Tinebase_Model_TempFile(array(), TRUE); $record->setFromJsonInUsersTimezone($tempFileData); $tempFileRecords->addRecord($record); } $joinedTempFile = Tinebase_TempFile::getInstance()->joinTempFiles($tempFileRecords); return $joinedTempFile->toArray(); }
/** * add attachments to mail * * @param Tinebase_Mail $_mail * @param Felamimail_Model_Message $_message */ protected function _addAttachments(Tinebase_Mail $_mail, Felamimail_Model_Message $_message) { if (isset($_message->attachments)) { $size = 0; $tempFileBackend = Tinebase_TempFile::getInstance(); foreach ($_message->attachments as $attachment) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Adding attachment: ' . print_r($attachment, TRUE)); } if ($attachment['type'] == Felamimail_Model_Message::CONTENT_TYPE_MESSAGE_RFC822 && $_message->original_id instanceof Felamimail_Model_Message) { $part = $this->getMessagePart($_message->original_id, $_message->original_part_id ? $_message->original_part_id : NULL); $part->decodeContent(); $name = $attachment['name'] . '.eml'; $type = $attachment['type']; } else { $tempFile = $attachment instanceof Tinebase_Model_TempFile ? $attachment : (array_key_exists('tempFile', $attachment) ? $tempFileBackend->get($attachment['tempFile']['id']) : NULL); if ($tempFile === NULL) { continue; } if (!$tempFile->path) { Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' Could not find attachment.'); continue; } // get contents from uploaded file $stream = fopen($tempFile->path, 'r'); $part = new Zend_Mime_Part($stream); // RFC822 attachments are not encoded, set all others to ENCODING_BASE64 $part->encoding = $tempFile->type == Felamimail_Model_Message::CONTENT_TYPE_MESSAGE_RFC822 ? null : Zend_Mime::ENCODING_BASE64; $name = $tempFile->name; $type = $tempFile->type; } $part->disposition = Zend_Mime::DISPOSITION_ATTACHMENT; $part->filename = $name; $part->type = $type . '; name="' . $name . '"'; $_mail->addAttachment($part); } } }