/** * @see 0011156: big files can't be uploaded */ public function testCreateTempFileWithBigSize() { $size = (double) (3.8 * 1024.0 * 1024.0 * 1024.0); $tempFile = new Tinebase_Model_TempFile(array('id' => '123', 'session_id' => 'abc', 'time' => Tinebase_DateTime::now()->get(Tinebase_Record_Abstract::ISO8601LONG), 'path' => '/tmp/tmpfile', 'name' => 'tmpfile', 'type' => 'unknown', 'error' => 0, 'size' => $size)); $createdTempFile = $this->_instance->create($tempFile); $this->assertEquals(4080218931.0, $createdTempFile->size); }
/** * the singleton pattern * * @return Tinebase_TempFile */ public static function getInstance() { if (self::$_instance === NULL) { self::$_instance = new Tinebase_TempFile(); } return self::$_instance; }
/** * 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 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'); }
/** * import file * * @param string $_filename * @param Tinebase_Model_ImportExportDefinition $_definition * @param boolean $_useJsonImportFn * @param boolean $removeGroupList * @return array course data */ protected function _importHelper($_filename, Tinebase_Model_ImportExportDefinition $_definition = NULL, $_useJsonImportFn = FALSE, $removeGroupList = FALSE) { $definition = $_definition !== NULL ? $_definition : $this->_getCourseImportDefinition(); $course = $this->_getCourseData(); $courseData = $this->_json->saveCourse($course); $this->_groupsToDelete->addRecord(Tinebase_Group::getInstance()->getGroupById($courseData['group_id'])); if ($removeGroupList) { $group = Admin_Controller_Group::getInstance()->get($courseData['group_id']); Addressbook_Controller_List::getInstance()->delete($group->list_id); } if ($_useJsonImportFn) { $tempFileBackend = new Tinebase_TempFile(); $tempFile = $tempFileBackend->createTempFile($_filename); Courses_Config::getInstance()->set(Courses_Config::STUDENTS_IMPORT_DEFINITION, $definition->name); $result = $this->_json->importMembers($tempFile->getId(), $courseData['group_id'], $courseData['id']); $this->assertGreaterThan(0, $result['results']); } else { $maildomain = TestServer::getPrimaryMailDomain(); $importer = call_user_func($definition->plugin . '::createFromDefinition', $definition, array('group_id' => $courseData['group_id'], 'accountHomeDirectoryPrefix' => '//base/school/' . $courseData['name'] . '/', 'accountEmailDomain' => $maildomain, 'password' => $courseData['name'], 'samba' => array('homePath' => '//basehome/', 'homeDrive' => 'H:', 'logonScript' => 'logon.bat', 'profilePath' => '\\\\profile\\'))); $tempFilename = TestServer::replaceEmailDomainInFile($_filename); $importer->importFile($tempFilename); } $courseData = $this->_json->getCourse($courseData['id']); return $courseData; }
/** * testCreateLeadWithAttachment * * @see 0005024: allow to attach external files to records */ public function testCreateLeadWithAttachment() { $tempFileBackend = new Tinebase_TempFile(); $tempFile = $tempFileBackend->createTempFile(dirname(dirname(__FILE__)) . '/Filemanager/files/test.txt'); $lead = $this->_getLead()->toArray(); $lead['attachments'] = array(array('tempFile' => $tempFile->toArray())); $savedLead = $this->_instance->saveLead($lead); // add path to files to remove $this->_objects['paths'][] = Tinebase_FileSystem_RecordAttachments::getInstance()->getRecordAttachmentPath(new Crm_Model_Lead($savedLead, TRUE)) . '/' . $tempFile->name; $this->assertTrue(isset($savedLead['attachments']), 'no attachments found'); $this->assertEquals(1, count($savedLead['attachments'])); $attachment = $savedLead['attachments'][0]; $this->assertEquals('text/plain', $attachment['contenttype'], print_r($attachment, TRUE)); $this->assertEquals(17, $attachment['size']); $this->assertTrue(is_array($attachment['created_by']), 'user not resolved: ' . print_r($attachment['created_by'], TRUE)); $this->assertEquals(Tinebase_Core::getUser()->accountFullName, $attachment['created_by']['accountFullName'], 'user not resolved: ' . print_r($attachment['created_by'], TRUE)); return $savedLead; }
/** * 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; }
/** * 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; }
/** * 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; }
/** * replace maildomain in input file * * @param string $filename * @return string filename */ public static function replaceEmailDomainInFile($filename) { $config = TestServer::getInstance()->getConfig(); $maildomain = $config->maildomain ? $config->maildomain : 'tine20.org'; $tempPath = Tinebase_TempFile::getTempPath(); $contents = file_get_contents($filename); $contents = preg_replace('/tine20.org/', $maildomain, $contents); file_put_contents($tempPath, $contents); return $tempPath; }
/** * 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); }
/** * tests the recursive filter */ public function testSearchRecursiveFilter() { $fixtures = array(array('/' . Tinebase_Model_Container::TYPE_PERSONAL . '/' . Tinebase_Core::getUser()->accountLoginName . '/testa', 'color-red.gif'), array('/' . Tinebase_Model_Container::TYPE_PERSONAL . '/' . Tinebase_Core::getUser()->accountLoginName . '/testb', 'color-green.gif'), array('/' . Tinebase_Model_Container::TYPE_PERSONAL . '/' . Tinebase_Core::getUser()->accountLoginName . '/testc', 'color-blue.gif')); $tempFileBackend = new Tinebase_TempFile(); foreach ($fixtures as $path) { $node = $this->_json->createNode($path[0], Tinebase_Model_Tree_Node::TYPE_FOLDER, NULL, FALSE); $this->_objects['containerids'][] = $node['name']['id']; $this->assertTrue(is_array($node['name'])); $this->assertEquals(str_replace('/' . Tinebase_Model_Container::TYPE_PERSONAL . '/' . Tinebase_Core::getUser()->accountLoginName . '/', '', $path[0]), $node['name']['name']); $this->assertEquals($path[0], $node['path']); $this->_objects['paths'][] = Filemanager_Controller_Node::getInstance()->addBasePath($node['path']); $filepath = $node['path'] . '/' . $path[1]; // create empty file first (like the js frontend does) $result = $this->_json->createNode($filepath, Tinebase_Model_Tree_Node::TYPE_FILE, array(), FALSE); $tempFile = $tempFileBackend->createTempFile(dirname(dirname(__FILE__)) . '/files/' . $path[1]); $result = $this->_json->createNode($filepath, Tinebase_Model_Tree_Node::TYPE_FILE, $tempFile->getId(), TRUE); } $filter = array(array('field' => 'recursive', 'operator' => 'equals', 'value' => 1), array('field' => 'path', 'operator' => 'equals', 'value' => '/'), array('field' => 'query', 'operator' => 'contains', 'value' => 'color'), 'AND'); $result = $this->_json->searchNodes($filter, array('sort' => 'name', 'start' => 0, 'limit' => 0)); $this->assertEquals(3, count($result), '3 files should have been found!'); }
/** * 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); } }
/** * import file * * @param string $_filename * @param Tinebase_Model_ImportExportDefinition $_definition * @return array course data */ protected function _importHelper($_filename, Tinebase_Model_ImportExportDefinition $_definition = NULL, $_useJsonImportFn = FALSE) { $definition = $_definition !== NULL ? $_definition : $this->_getCourseImportDefinition(); $course = $this->_getCourseData(); $courseData = $this->_json->saveCourse($course); $this->_coursesToDelete[] = $courseData['id']; if ($_useJsonImportFn) { $tempFileBackend = new Tinebase_TempFile(); $tempFile = $tempFileBackend->createTempFile($_filename); $this->_json->setConfig(array('import_definition' => 'course_user_import_csv')); $result = $this->_json->importMembers($tempFile->getId(), $courseData['group_id'], $courseData['id']); $this->assertGreaterThan(0, $result['results']); } else { $testConfig = Zend_Registry::get('testConfig'); $maildomain = $testConfig->maildomain ? $testConfig->maildomain : 'school.org'; $importer = call_user_func($definition->plugin . '::createFromDefinition', $definition, array('group_id' => $courseData['group_id'], 'accountHomeDirectoryPrefix' => '//base/school/' . $courseData['name'] . '/', 'accountEmailDomain' => $maildomain, 'password' => $courseData['name'], 'samba' => array('homePath' => '//basehome/', 'homeDrive' => 'H:', 'logonScript' => 'logon.bat', 'profilePath' => '\\\\profile\\'))); $importer->importFile($_filename); } $courseData = $this->_json->getCourse($courseData['id']); return $courseData; }
/** * replace maildomain in input file * * @param string $filename * @return string filename */ public static function replaceEmailDomainInFile($filename) { $maildomain = self::getPrimaryMailDomain(); $tempPath = Tinebase_TempFile::getTempPath(); $contents = file_get_contents($filename); $contents = preg_replace('/tine20.org/', $maildomain, $contents); file_put_contents($tempPath, $contents); return $tempPath; }
/** * 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); }
/** * 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); } }
/** * 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; }
/** * 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)); }
/** * testCreateFileNodeWithTempfile * * @return array node */ public function testCreateFileNodeWithTempfile() { $sharedContainerNode = $this->testCreateContainerNodeInSharedFolder(); $this->_objects['paths'][] = Filemanager_Controller_Node::getInstance()->addBasePath($sharedContainerNode['path']); $filepath = $sharedContainerNode['path'] . '/test.txt'; // create empty file first (like the js frontend does) $result = $this->_json->createNode($filepath, Tinebase_Model_Tree_Node::TYPE_FILE, array(), FALSE); $tempFileBackend = new Tinebase_TempFile(); $tempFile = $tempFileBackend->createTempFile(dirname(dirname(__FILE__)) . '/files/test.txt'); $result = $this->_json->createNode($filepath, Tinebase_Model_Tree_Node::TYPE_FILE, $tempFile->getId(), TRUE); $this->assertEquals('text/plain', $result['contenttype'], print_r($result, TRUE)); $this->assertEquals(17, $result['size']); return $result; }
/** * import helper * * @param array $additionalOptions * @param array $clientRecords * @param string $filename * @return array */ protected function _importHelper($additionalOptions = array('dryrun' => 1), $clientRecords = array(), $filename = NULL) { $definition = Tinebase_ImportExportDefinition::getInstance()->getByName('adb_tine_import_csv'); $definitionOptions = Tinebase_ImportExportDefinition::getOptionsAsZendConfigXml($definition); $tempFileBackend = new Tinebase_TempFile(); $importFile = $filename ? $filename : dirname(dirname(dirname(dirname(__FILE__)))) . '/tine20/' . $definitionOptions->example; $tempFile = $tempFileBackend->createTempFile($importFile); $options = array_merge($additionalOptions, array('container_id' => $this->container->getId())); $result = $this->_uit->importContacts($tempFile->getId(), $definition->getId(), $options, $clientRecords); if (isset($additionalOptions['dryrun']) && $additionalOptions['dryrun'] === 0) { foreach ($result['results'] as $contact) { $this->_contactIdsToDelete[] = $contact['id']; } } return $result; }
/** * 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; }
/** * get test temp file * * @return Tinebase_TempFile */ protected function _getTempFile() { $tempFileBackend = new Tinebase_TempFile(); $tempFile = $tempFileBackend->createTempFile(dirname(__FILE__) . '/Filemanager/files/test.txt'); return $tempFile; }
/** * testInvitationWithAttachment * * @see 0008592: append event file attachments to invitation mail * @see 0009246: Mail address of organizer is broken in invite mails */ public function testInvitationWithAttachment() { $event = $this->_getEvent(TRUE); $event->attendee = $this->_getPersonaAttendee('pwulf'); $tempFileBackend = new Tinebase_TempFile(); $tempFile = $tempFileBackend->createTempFile(dirname(dirname(dirname(__FILE__))) . '/Filemanager/files/test.txt'); $event->attachments = array(array('tempFile' => array('id' => $tempFile->getId()))); self::flushMailer(); $persistentEvent = $this->_eventController->create($event); $messages = self::getMessages(); $this->assertEquals(1, count($messages)); $parts = $messages[0]->getParts(); $this->assertEquals(2, count($parts)); $fileAttachment = $parts[1]; $this->assertEquals('text/plain; name="=?utf-8?Q?tempfile.tmp?="', $fileAttachment->type); // check VEVENT ORGANIZER mailto $vcalendarPart = $parts[0]; $vcalendar = quoted_printable_decode($vcalendarPart->getContent()); $this->assertContains('SENT-BY="mailto:' . Tinebase_Core::getUser()->accountEmailAddress . '":mailto:', str_replace("\r\n ", '', $vcalendar), 'sent-by mailto not quoted'); // @todo assert attachment content (this seems to not work with array mailer, maybe we need a "real" email test here) // $content = $fileAttachment->getDecodedContent(); // $this->assertEquals('test file content', $content); }
/** * 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(); }
/** * 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); }