function copyImagesToDB($remove) { global $cli, $fileHandler; $db = eZDB::instance(); $cli->output("Importing images and imagealiases files to database:"); $rows = $db->arrayQuery('select filepath from ezimagefile'); foreach ($rows as $row) { $filePath = $row['filepath']; $cli->output("- " . $filePath); $mimeData = eZMimeType::findByFileContents($filePath); $fileHandler->fileStore($filePath, 'image', $remove, $mimeData['name']); } }
/** * Gathers information about a given node specified as parameter. * * The format of the returned array is: * <code> * array( 'name' => node name (eg. 'Group picture'), * 'size' => storage size of the_node in bytes (eg. 57123), * 'mimetype' => mime type of the node (eg. 'image/jpeg'), * 'ctime' => creation time as timestamp, * 'mtime' => latest modification time as timestamp, * 'href' => the path to the node (eg. '/plain_site_user/Content/Folder1/file1.jpg') * </code> * * @param string $target Eg. '/plain_site_user/Content/Folder1/file1.jpg * @param eZContentObject &$node The node corresponding to $target * @return array(string=>mixed) * @todo remove/replace .ini calls, eZContentUpload, eZMimeType, eZSys RequestURI * @todo handle articles as files */ protected function fetchNodeInfo($target, &$node) { // When finished, we'll return an array of attributes/properties. $entry = array(); $classIdentifier = $node->attribute('class_identifier'); $object = $node->attribute('object'); $urlAlias = $node->urlAlias(); // By default, everything is displayed as a folder: // Trim the name of the node, it is in some cases whitespace in eZ Publish $name = trim($node->attribute('name')); // @as 2009-03-09: return node_id as displayname in case name is missing // displayname is not actually used by WebDAV clients $entry["name"] = $name !== '' && $name !== NULL ? $name : $node->attribute('node_id'); $entry["size"] = 0; $entry["mimetype"] = self::DIRECTORY_MIMETYPE; eZWebDAVContentBackend::appendLogEntry('FetchNodeInfo:' . $node->attribute('name') . '/' . $urlAlias); // @todo handle articles as files // if ( $classIdentifier === 'article' ) // { // $entry["mimetype"] = 'application/ms-word'; // } $entry["ctime"] = $object->attribute('published'); $entry["mtime"] = $object->attribute('modified'); $upload = new eZContentUpload(); $info = $upload->objectFileInfo($object); $suffix = ''; $class = $object->contentClass(); $isObjectFolder = $this->isObjectFolder($object, $class); if ($isObjectFolder) { // We do nothing, the default is to see it as a folder } else { if ($info) { $filePath = $info['filepath']; $entry['filepath'] = $filePath; $entry["mimetype"] = false; $entry["size"] = false; if (isset($info['filesize'])) { $entry['size'] = $info['filesize']; } if (isset($info['mime_type'])) { $entry['mimetype'] = $info['mime_type']; } // Fill in information from the actual file if they are missing. $file = eZClusterFileHandler::instance($filePath); if (!$entry['size'] and $file->exists()) { $entry["size"] = $file->size(); } if (!$entry['mimetype']) { $mimeInfo = eZMimeType::findByURL($filePath); $entry["mimetype"] = $mimeInfo['name']; $suffix = $mimeInfo['suffix']; if (strlen($suffix) > 0) { $entry["name"] .= '.' . $suffix; } } else { // eZMimeType returns first suffix in its list // this could be another one than the original file extension // so let's try to get the suffix from the file path first $suffix = eZFile::suffix($filePath); if (!$suffix) { $mimeInfo = eZMimeType::findByName($entry['mimetype']); $suffix = $mimeInfo['suffix']; } if (strlen($suffix) > 0) { $entry["name"] .= '.' . $suffix; } } if ($file->exists()) { $entry["ctime"] = $file->mtime(); $entry["mtime"] = $file->mtime(); } } else { // Here we only show items as folders if they have // is_container set to true, otherwise it's an unknown binary file if (!$class->attribute('is_container')) { $entry['mimetype'] = 'application/octet-stream'; } } } $scriptURL = $target; if (strlen($scriptURL) > 0 and $scriptURL[strlen($scriptURL) - 1] !== "/") { $scriptURL .= "/"; } $trimmedScriptURL = trim($scriptURL, '/'); $scriptURLParts = explode('/', $trimmedScriptURL); $urlPartCount = count($scriptURLParts); if ($urlPartCount >= 2) { // one of the virtual folders // or inside one of the virtual folders $siteAccess = $scriptURLParts[0]; $virtualFolder = $scriptURLParts[1]; // only when the virtual folder is Content we need to add its path to the start URL // the paths of other top level folders (like Media) are included in URL aliases of their descending nodes if ($virtualFolder === self::virtualContentFolderName()) { $startURL = '/' . $siteAccess . '/' . $virtualFolder . '/'; } else { if ($virtualFolder === self::virtualMediaFolderName()) { $startURL = '/' . $siteAccess . '/' . $virtualFolder . '/'; $urlAlias = substr($urlAlias, strpos($urlAlias, '/') + 1); } else { $startURL = '/' . $siteAccess . '/'; } } } else { // site access level $startURL = $scriptURL; } // Set the href attribute (note that it doesn't just equal the name). if (!isset($entry['href'])) { if (strlen($suffix) > 0) { $suffix = '.' . $suffix; } $entry["href"] = $startURL . $urlAlias . $suffix; } // Return array of attributes/properties (name, size, mime, times, etc.). return $entry; }
function fetchCollectionAttributeHTTPInput($collection, $collectionAttribute, $http, $base, $contentObjectAttribute) { EnhancedeZBinaryFileType::checkFileUploads(); if (eZHTTPFile::canFetch($base . "_data_enhancedbinaryfilename_" . $contentObjectAttribute->attribute("id")) != eZHTTPFile::UPLOADEDFILE_OK) { return false; } //Check allowed file type - must do it here,again - otherwise an illegal //file will still be created in the storage directory $binaryFile = eZHTTPFile::fetch($base . "_data_enhancedbinaryfilename_" . $contentObjectAttribute->attribute("id")); if (!$binaryFile) { return eZInputValidator::STATE_INVALID; } $moduleINI = eZINI::instance('module.ini.append.php', 'settings'); $allowed = $moduleINI->variable('AllowedFileTypes', 'AllowedFileTypeList'); // $binaryFile->attribute( 'mime_type_part' ) not always the extension $extension = preg_replace('/.*\\.(.+?)$/', '\\1', $binaryFile->attribute("original_filename")); if (!in_array(strtolower($extension), $allowed)) { $contentObjectAttribute->setValidationError(ezpI18n::tr('kernel/classes/datatypes', 'Failed to store file. Only the following file types are allowed: %1.'), implode(", ", $allowed)); return eZInputValidator::STATE_INVALID; } //$contentObjectAttribute->setContent( $binaryFile ); if ($binaryFile instanceof eZHTTPFile) { //clean up older files. $moduleINI = eZINI::instance('module.ini.append.php', 'settings'); $maxFiles = $moduleINI->variable('RemoveFiles', 'MaxFiles'); $downloadPath = $moduleINI->variable('RemoveFiles', 'DownloadPath'); $downloadPath = trim($downloadPath, "/"); if (!$downloadPath) { $downloadPath = 'original/collected'; } if ($maxFiles > 0) { $Files = array(); $storageDir = eZSys::storageDirectory(); $fileCollection = eZDir::recursiveFindRelative($storageDir, $downloadPath, '.*'); if (count($fileCollection) >= $maxFiles) { foreach ($fileCollection as $fileItem) { $lastModified = filemtime($storageDir . '/' . $fileItem); $Files[$fileItem] = filemtime($storageDir . '/' . $fileItem); } asort($Files, SORT_NUMERIC); while (count($Files) >= $maxFiles) { $removeFile = key($Files); if (file_exists($storageDir . '/' . $removeFile)) { if (!unlink($storageDir . '/' . $removeFile)) { eZDebug::writeError("Failed to delete file: " . $storageDir . '/' . $removeFile, "EnhancedeZBinaryFileType"); return false; } } array_shift($Files); } } } //end cleanup // $contentObjectAttributeID = $contentObjectAttribute->attribute( "id" ); //$version = $contentObjectAttribute->attribute( "version" ); $mimeData = eZMimeType::findByFileContents($binaryFile->attribute("original_filename")); //Nice name but it still uses the extension to set the mimetype and therefore can be bogus $mime = $mimeData['name']; if ($mime == '') { $mime = $binaryFile->attribute("mime_type"); } $extension = eZFile::suffix($binaryFile->attribute("original_filename")); $binaryFile->setMimeType($mime); if (!$binaryFile->store($downloadPath, $extension)) { eZDebug::writeError("Failed to store http-file: " . $binaryFile->attribute("original_filename"), "EnhancedeZBinaryFileType"); return false; } //Adds xmltext to collection attribute with file info to data_text attribute $doc = new DOMDocument('1.0', 'utf-8'); $root = $doc->createElement('binaryfile-info'); $binaryFileList = $doc->createElement('binaryfile-attributes'); foreach ($binaryFile as $key => $binaryFileItem) { $binaryFileElement = $doc->createElement($key, $binaryFileItem); $binaryFileList->appendChild($binaryFileElement); } $root->appendChild($binaryFileList); $doc->appendChild($root); $docText = EnhancedeZBinaryFileType::domString($doc); $collectionAttribute->setAttribute('data_text', $docText); } return true; }
/** * Image information for $aliasName. This is the information which normally * would be provided during generation of aliasName. This so that requests * not holding the lock will provide meaningful information. * * @param mixed $mimeData * @param string $aliasName * @return array */ function imageAliasInfo( $mimeData, $aliasName, $isAliasNew = false ) { if ( is_string( $mimeData ) ) $mimeData = eZMimeType::findByFileContents( $mimeData ); $this->analyzeImage( $mimeData ); if ( $aliasName ) { $aliasList = $this->aliasList(); if ( isset( $aliasList[$aliasName] ) ) { $alias = $aliasList[$aliasName]; if ( $alias['mime_type'] ) { eZMimeType::changeMIMEType( $mimeData, $alias['mime_type'] ); } } } if ( $aliasName != 'original' ) { $mimeData['filename'] = $mimeData['basename'] . '_' . $aliasName . '.' . $mimeData['suffix']; $mimeData['url'] = $mimeData['dirpath'] . '/' . $mimeData['filename']; } // eZDebug::writeDebug( $mimeData, __METHOD__ ); return $mimeData; }
/** * Validate the object attribute input in http. If there is validation failure, there failure message will be put into $contentObjectAttribute->ValidationError * @param $http: http object * @param $base: * @param $contentObjectAttribute: content object attribute being validated * @return validation result- eZInputValidator::STATE_INVALID or eZInputValidator::STATE_ACCEPTED * * @see kernel/classes/eZDataType#validateObjectAttributeHTTPInput($http, $base, $objectAttribute) */ function validateObjectAttributeHTTPInput($http, $base, $contentObjectAttribute) { $classAttribute = $contentObjectAttribute->contentClassAttribute(); $httpFileName = $base . "_data_imagename_" . $contentObjectAttribute->attribute("id"); $maxSize = 1024 * 1024 * $classAttribute->attribute(self::FILESIZE_FIELD); $mustUpload = false; if ($contentObjectAttribute->validateIsRequired()) { $tmpImgObj = $contentObjectAttribute->attribute('content'); $original = $tmpImgObj->attribute('original'); if (!$original['is_valid']) { $mustUpload = true; } } $canFetchResult = eZHTTPFile::canFetch($httpFileName, $maxSize); if (isset($_FILES[$httpFileName]) and $_FILES[$httpFileName]["tmp_name"] != "") { $imagefile = $_FILES[$httpFileName]['tmp_name']; if (!$_FILES[$httpFileName]["size"]) { $contentObjectAttribute->setValidationError(ezpI18n::tr('kernel/classes/datatypes', 'The image file must have non-zero size.')); return eZInputValidator::STATE_INVALID; } if (function_exists('getimagesize')) { $info = getimagesize($imagefile); if (!$info) { $contentObjectAttribute->setValidationError(ezpI18n::tr('kernel/classes/datatypes', 'A valid image file is required.')); return eZInputValidator::STATE_INVALID; } } else { $mimeType = eZMimeType::findByURL($_FILES[$httpFileName]['name']); $nameMimeType = $mimeType['name']; $nameMimeTypes = explode("/", $nameMimeType); if ($nameMimeTypes[0] != 'image') { $contentObjectAttribute->setValidationError(ezpI18n::tr('kernel/classes/datatypes', 'A valid image file is required.')); return eZInputValidator::STATE_INVALID; } } } if ($mustUpload && $canFetchResult == eZHTTPFile::UPLOADEDFILE_DOES_NOT_EXIST) { $contentObjectAttribute->setValidationError(ezpI18n::tr('kernel/classes/datatypes', 'A valid image file is required.')); return eZInputValidator::STATE_INVALID; } if ($canFetchResult == eZHTTPFile::UPLOADEDFILE_EXCEEDS_PHP_LIMIT) { $contentObjectAttribute->setValidationError(ezpI18n::tr('kernel/classes/datatypes', 'The size of the uploaded image exceeds limit set by upload_max_filesize directive in php.ini. Please contact the site administrator.')); return eZInputValidator::STATE_INVALID; } if ($canFetchResult == eZHTTPFile::UPLOADEDFILE_EXCEEDS_MAX_SIZE) { $contentObjectAttribute->setValidationError(ezpI18n::tr('kernel/classes/datatypes', 'The size of the uploaded file exceeds the limit set for this site: %1 bytes.'), $maxSize); return eZInputValidator::STATE_INVALID; } return eZInputValidator::STATE_ACCEPTED; }
function validateImageFiles( $package, $http, $currentStepID, &$stepMap, &$persistentData, &$errorList ) { // If we don't have an image we continue as normal if ( !eZHTTPFile::canFetch( 'PackageImageFile' ) ) return true; $file = eZHTTPFile::fetch( 'PackageImageFile' ); $result = true; if ( $file ) { $mimeData = eZMimeType::findByFileContents( $file->attribute( 'original_filename' ) ); $dir = eZSys::storageDirectory() . '/temp'; eZMimeType::changeDirectoryPath( $mimeData, $dir ); $file->store( false, false, $mimeData ); $persistentData['imagefiles'][] = $mimeData; $result = false; } return $result; }
/** * Function for insert image */ function callImage($info) { $params = array(); $leftMargin = false; $rightMargin = false; eZPDFTable::extractParameters($info['p'], 0, $params, true); $filename = rawurldecode($params['src']); $mimetype = eZMimeType::findByFileContents($filename); $this->transaction('start'); if (!isset($params['static'])) { $params['static'] = false; } if ($this->yOffset() - $params['height'] < $this->ez['bottomMargin']) { $this->ezNewPage(); } if (isset($params['dpi'])) { $newWidth = (int) ($params['width'] * ((int) $params['dpi'] / 72)); $newHeight = (int) ($params['height'] * ((int) $params['dpi'] / 72)); $newFilename = eZSys::cacheDirectory() . '/' . md5(mt_rand()) . '.jpg'; while (file_exists($newFilename)) { $newFilename = eZSys::cacheDirectory() . '/' . md5(mt_rand()) . '.jpg'; } $img = eZImageManager::factory(); $newImg = $img->convert($filename, $newFilename, false, array('filters' => array(array('name' => 'geometry/scaledownonly', 'data' => array($newWidth, $newHeight))))); $filename = $newFilename['url']; } $drawableAreaWidth = $this->ez['pageWidth'] - $this->ez['leftMargin'] - $this->ez['rightMargin']; switch ($params['align']) { case 'right': $xOffset = $this->ez['pageWidth'] - ($this->rightMargin() + $params['width']); $rightMargin = $this->rightMargin() + $params['width']; if ($rightMargin > $drawableAreaWidth + $this->rightMargin()) { // the image is equal or larger then width of the page(of the drawable area) => no point // to set $rightMargin and next object(text, image, ...) should be outputted below the image. $rightMargin = false; } break; case 'center': $xOffset = ($this->ez['pageWidth'] - $this->rightMargin() - $this->leftMargin()) / 2 + $this->leftMargin() - $params['width'] / 2; break; case 'left': default: $xOffset = $this->leftMargin(); $leftMargin = $this->leftMargin() + $params['width']; if ($leftMargin > $drawableAreaWidth + $this->leftMargin()) { // the image is equal or larger then width of the page(of the drawable area) => no point // to set $leftMargin and next object(text, image, ...) should be outputted below the image. $leftMargin = false; } break; } if (isset($params['x'])) { $xOffset = $params['x']; $leftMargin = false; $rightMargin = false; } $yOffset = $this->yOffset(); $whileCount = 0; if ($params['width'] < $drawableAreaWidth) { while ($this->leftMargin($yOffset) > $xOffset && ++$whileCount < 100) { $yOffset -= 10; } } $yOffset -= $params['height']; $yOffset += $this->lineHeight() / 2; if (isset($params['y'])) { $yOffset = $params['y']; } if ($leftMargin !== false) { $this->setLimitedLeftMargin($yOffset - 7, $yOffset + $params['height'] + 7, $leftMargin + 7); } if ($rightMargin !== false) { $this->setLimitedRightMargin($yOffset - 7, $yOffset + $params['height'] + 7, $rightMargin + 7); } switch ($mimetype['name']) { case 'image/gif': $newFilename = eZSys::cacheDirectory() . '/' . md5(mt_rand()) . '.jpg'; while (file_exists($newFilename)) { $newFilename = eZSys::cacheDirectory() . '/' . md5(mt_rand()) . '.jpg'; } $newMimetype = eZMimeType::findByURL($newFilename); $img = eZImageManager::factory(); $newImg = $img->convert($mimetype, $newMimetype, false, array()); $this->addJpegFromFile($newMimetype['url'], $xOffset, $yOffset, $params['width'], $params['height']); break; case 'image/jpeg': $this->addJpegFromFile($filename, $xOffset, $yOffset, $params['width'], $params['height']); break; case 'image/png': if ($this->addPngFromFile($filename, $xOffset, $yOffset, $params['width'], $params['height']) === false) { $this->transaction('abort'); return; } break; default: eZDebug::writeError('Unsupported image file type, ' . $mimetype['name'], __METHOD__); $this->transaction('abort'); return; break; } $this->transaction('commit'); if (!$leftMargin && !$rightMargin && !$params['static']) { $this->y -= $params['height'] + $this->lineHeight(); } return array('y' => $params['height'] + $this->lineHeight()); }
static function fetch($http_name) { if (!isset($GLOBALS["eZHTTPFile-{$http_name}"]) || !$GLOBALS["eZHTTPFile-{$http_name}"] instanceof eZHTTPFile) { $GLOBALS["eZHTTPFile-{$http_name}"] = null; if (isset($_FILES[$http_name]) and $_FILES[$http_name]["name"] != "") { $mimeType = eZMimeType::findByURL($_FILES[$http_name]['name']); $_FILES[$http_name]['type'] = $mimeType['name']; $GLOBALS["eZHTTPFile-{$http_name}"] = new eZHTTPFile($http_name, $_FILES[$http_name]); } else { eZDebug::writeError("Unknown file for post variable: {$http_name}", "eZHTTPFile"); } } return $GLOBALS["eZHTTPFile-{$http_name}"]; }
static function findByBuffer($buffer, $length = false, $offset = false, $url = false, $returnDefault = true) { return eZMimeType::findByURL($url, $returnDefault); }
function getFileInfo($dir, $file) { append_to_log("inside getFileInfo, dir: {$dir}, file: {$file}"); $realPath = $dir . '/' . $file; $fileInfo = array(); $fileInfo["name"] = $file; // If the file is a directory: if (is_dir($realPath)) { $fileInfo["size"] = 0; $fileInfo["mimetype"] = "httpd/unix-directory"; // Get the dir's creation & modification times. $fileInfo["ctime"] = filectime($realPath . '/.'); $fileInfo["mtime"] = filemtime($realPath . '/.'); } else { // Get the file's creation & modification times. $fileInfo["ctime"] = filectime($realPath); $fileInfo["mtime"] = filemtime($realPath); // Get the file size (bytes). $fileInfo["size"] = filesize($realPath); // Check if the filename exists and is readable: if (is_readable($realPath)) { // Attempt to get & set the MIME type. $mimeInfo = eZMimeType::findByURL($dir . '/' . $file); $fileInfo['mimetype'] = $mimeInfo['name']; } else { $fileInfo["mimetype"] = "application/x-non-readable"; } } // Return the array (hopefully containing correct info). return $fileInfo; }
$newBaseName = $objectName; } if ($newFilePath != $filePath) { if (!file_exists($newDirPath)) { eZDir::mkdir($newDirPath, false, true); } eZFileHandler::copy($filePath, $newFilePath); $filePath = $newFilePath; $fileName = $newFileName; $suffix = $newSuffix; $dirPath = $newDirPath; $baseName = $newBaseName; } } } $mimeData = eZMimeType::findByFileContents($fileName); $imageManager->analyzeImage($mimeData); $imageNode->setAttribute('serial_number', false); $imageNode->setAttribute('is_valid', $isValid); $imageNode->setAttribute('filename', $fileName); $imageNode->setAttribute('suffix', $suffix); $imageNode->setAttribute('basename', $baseName); $imageNode->setAttribute('dirpath', $dirPath); $imageNode->setAttribute('url', $filePath); $imageNode->setAttribute('original_filename', $originalFileName); $imageNode->setAttribute('mime_type', $mimeType); $imageNode->setAttribute('width', $width); $imageNode->setAttribute('height', $height); $imageNode->setAttribute('alternative_text', $altText); $imageNode->setAttribute('alias_key', $imageManager->createImageAliasKey($imageManager->alias('original'))); $imageNode->setAttribute('timestamp', time());
function insertRegularFile($object, $objectVersion, $objectLanguage, $objectAttribute, $filePath, &$result) { $result = array('errors' => array(), 'require_storage' => false); $attributeID = $objectAttribute->attribute('id'); $media = eZMedia::fetch($attributeID, $objectVersion); if ($media === null) { $media = eZMedia::create($attributeID, $objectVersion); } $fileName = basename($filePath); $mimeData = eZMimeType::findByFileContents($filePath); $storageDir = eZSys::storageDirectory(); list($group, $type) = explode('/', $mimeData['name']); $destination = $storageDir . '/original/' . $group; if (!file_exists($destination)) { if (!eZDir::mkdir($destination, false, true)) { return false; } } // create dest filename in the same manner as eZHTTPFile::store() // grab file's suffix $fileSuffix = eZFile::suffix($fileName); // prepend dot if ($fileSuffix) { $fileSuffix = '.' . $fileSuffix; } // grab filename without suffix $fileBaseName = basename($fileName, $fileSuffix); // create dest filename $destFileName = md5($fileBaseName . microtime() . mt_rand()) . $fileSuffix; $destination = $destination . '/' . $destFileName; copy($filePath, $destination); $fileHandler = eZClusterFileHandler::instance(); $fileHandler->fileStore($destination, 'mediafile', true, $mimeData['name']); $classAttribute = $objectAttribute->contentClassAttribute(); $player = $classAttribute->attribute("data_text1"); $pluginPage = eZMediaType::pluginPage($player); $media->setAttribute("contentobject_attribute_id", $attributeID); $media->setAttribute("version", $objectVersion); $media->setAttribute("filename", $destFileName); $media->setAttribute("original_filename", $fileName); $media->setAttribute("mime_type", $mimeData['name']); // Setting width and height to zero means that the browser/player must find the size itself. // In the future we will probably analyze the media file and find this information $width = $height = 0; // Quality is not known, so we don't set any $quality = false; // Not sure what this is for, set to false $controls = false; // We want to show controllers by default $hasController = true; // Don't play automatically $isAutoplay = false; // Don't loop movie $isLoop = false; $media->setAttribute("width", $width); $media->setAttribute("height", $height); $media->setAttribute("quality", $quality); $media->setAttribute("controls", $controls); $media->setAttribute("pluginspage", $pluginPage); $media->setAttribute("is_autoplay", $isAutoplay); $media->setAttribute("has_controller", $hasController); $media->setAttribute("is_loop", $isLoop); $media->store(); $objectAttribute->setContent($media); return true; }
/** * Outputs file contents prepending them with appropriate HTTP headers. * * \public */ function passthrough() { $path = $this->filePath; eZDebugSetting::writeDebug('kernel-clustering', "fs::passthrough()", __METHOD__); eZDebug::accumulatorStart('dbfile', false, 'dbfile'); $mimeData = eZMimeType::findByFileContents($path); // $mimeType = $mimeData['name']; $mimeType = 'application/octec-stream'; $contentLength = filesize($path); header("Content-Length: {$contentLength}"); header("Content-Type: {$mimeType}"); header("Expires: " . gmdate('D, d M Y H:i:s', time() + 6000) . 'GMT'); header("Connection: close"); readfile($path); eZDebug::accumulatorStop('dbfile'); }
function fetchHTTPFile($httpFileIdentifier, &$errors, &$file, &$mimeData) { if (!eZHTTPFile::canFetch($httpFileIdentifier)) { $errors[] = array('description' => ezpI18n::tr('kernel/content/upload', 'A file is required for upload, no file were found.')); return false; } $file = eZHTTPFile::fetch($httpFileIdentifier); if (!$file instanceof eZHTTPFile) { $errors[] = array('description' => ezpI18n::tr('kernel/content/upload', 'Expected a eZHTTPFile object but got nothing.')); return false; } $mimeData = eZMimeType::findByFileContents($file->attribute("original_filename")); return false; }
/** * Initializes image handler for the given application and applies selection rules * (internal) fetches the good eZContentObjectAttribute containing the expected image and its image alias handler * * @return void * @throws Exception */ public function initImage() { if ( !isset($this->_imageAttribute) ) { $this->_imageAttribute = $this->fetchImageAttribute(); if ( $this->_imageAttribute !== true ) { $handler = new eZImageAliasHandler($this->_imageAttribute); $this->_aliasHandler = $handler->imageAlias($this->_aliasName); } else if ( $this->_isLocalImage ) { $filePath = self::$_localImagePaths[$this->_localImage]; $mime = eZMimeType::findByURL($filePath); $this->_aliasHandler = array( 'url' => $filePath, 'filesize' => filesize($filePath), 'mime_type' => $mime['name'], ); } else throw new Exception('Image Attribute has no valid case'); } }
/** * @param $fieldArray * @param array $mapping * @throws RootNodeException * @return mixed */ public function getSpecialFieldContent($fieldArray, $mapping) { $fieldName = $mapping['internalField']; $specialProcess = $mapping['specialProcess']; $autoContent = false; $rootImport = $this->importINI->variable( 'XMLImportSettings', 'RootImport' ); if (!empty($mapping['associatedField']) && isset($fieldArray[$mapping['associatedField']])) { $associatedField = $fieldArray[$mapping['associatedField']]; } if (isset($associatedField) && empty($associatedField->calculatedValue)) { unset($associatedField); } switch ($specialProcess) { case 'getFileSize': { if (isset($associatedField)) { $file = trim("$rootImport/{$associatedField->calculatedValue}"); $tmpParts = pathinfo($file); $explodeDir = explode('/', $tmpParts['dirname']); $archivedFile = ''; for( $i = 0; $i < count($explodeDir)-1; $i++ ) $archivedFile.= $explodeDir[$i] . '/'; $archivedFile.= 'archived/' . $explodeDir[count($explodeDir) - 1] . '/' . $tmpParts['filename'] . '.' . $tmpParts['extension']; if (file_exists($file)) { $fieldContent = filesize($file); if ($fieldContent !== false) $autoContent = $fieldContent; } elseif(file_exists($archivedFile)) { $fieldContent = filesize($archivedFile); if ($fieldContent !== false) $autoContent = $fieldContent; } } } break; case 'getMediaEncoding': { if (isset($associatedField)) { $file = trim("$rootImport/{$associatedField->calculatedValue}"); $tmpParts = pathinfo($file); $explodeDir = explode('/', $tmpParts['dirname']); $archivedFile = ''; for( $i = 0; $i < count($explodeDir)-1; $i++ ) $archivedFile.= $explodeDir[$i] . '/'; $archivedFile.= 'archived/' . $explodeDir[count($explodeDir) - 1] . '/' . $tmpParts['filename'] . '.' . $tmpParts['extension']; if (file_exists($file)) { $fieldContent = eZMimeType::findByURL($file, false); if ($fieldContent !== false) $autoContent = $fieldContent['name']; } elseif(file_exists($archivedFile)) { $fieldContent = eZMimeType::findByURL($archivedFile, false); if ($fieldContent !== false) $autoContent = $fieldContent['name']; } } } break; case 'storeBlob': { if (isset($associatedField)) { $fieldContent = trim($associatedField->calculatedValue); $archived = false; $tmpParts = pathinfo($fieldContent); $explodeDir = explode('/', $tmpParts['dirname']); $archivedFile = ''; for( $i = 0; $i < count($explodeDir)-1; $i++ ) $archivedFile.= $explodeDir[$i] . '/'; $archivedFile.= 'archived/' . $explodeDir[count($explodeDir) - 1] . '/' . $tmpParts['filename'] . '.' . $tmpParts['extension']; if (file_exists($fieldContent)) $tmpFilePath = $fieldContent; elseif (file_exists($archivedFile)) $tmpFilePath = $archivedFile; if (isset($tmpFilePath)) { $parts = pathinfo($tmpFilePath); if (!empty($parts) && isset($parts['extension'])) { if ($parts['extension'] != 'png') { $pngFilePath = $parts['dirname'] . '/' . $parts['filename'] . '.png'; exec('convert ' . $tmpFilePath . ' ' . $pngFilePath); if (file_exists($pngFilePath)) { if ( !$archived ) { $this->blobedFiles[] = $tmpFilePath; $this->blobedFiles[] = $pngFilePath; } $autoContent = file_get_contents($pngFilePath); } else XMLImportMonitor::log("Image convertion failed : { $fieldContent }", 'warning'); } else { if ( !$archived ) $this->blobedFiles[] = $tmpFilePath; $autoContent = file_get_contents($tmpFilePath); } } } else XMLImportMonitor::log("The file $fieldContent in field $fieldName of type {$mapping['type']} doesn't exists", 'warning'); } } break; case 'contactFromFieldName': { if ($mapping['internalField'] == 'author') $autoContent = 'Author'; elseif ($mapping['internalField'] == 'reviewer') $autoContent = 'Reviewer'; } break; case 'getLanguageFromRoot': { if (!isset($fieldArray[$fieldName])) { if ($this->getRealRoot()->hasAttribute('language')) { $language = trim($this->getRealRoot()->getAttribute('language')); $autoContent = $language; } } } break; case 'getIdFromRoot': { if ($this->getRealRoot()->hasAttribute('id')) $autoContent = $this->getRealRoot()->getAttribute('id'); } break; case 'getPublisherId': { $autoContent = $this->publisherInfos['id']; } break; case 'getMediaType': { if (!isset($fieldArray[$fieldName])) { if (isset($fieldArray['url'])) $autoContent = 'link'; elseif (isset($fieldArray['file'])) { $filename = trim($fieldArray['file']->calculatedValue); $parts = pathinfo($filename); if (!empty($parts) && isset($parts['extension'])) { $extension = strtolower($parts['extension']); if ($extension == 'pdf') $autoContent = 'pdf'; elseif ( in_array($extension, array( 'mp3', 'oog', 'wma' ) )) $autoContent = 'audio'; elseif (in_array($extension, array( 'bmp', 'png', 'jpg', 'jpeg', 'gif' ) )) $autoContent = 'image'; elseif (in_array($extension, array( 'avi', 'mp4', 'mkv', 'wmv', 'mov', 'mpg', 'm4v' ) )) $autoContent = 'video'; } } } } break; case 'parentIdPostPound': { } default: { XMLImportMonitor::log("The field $fieldName of type {$mapping['type']} has an incorrect specialProcess : $specialProcess", 'error'); } break; } return $autoContent; }
function storeImage($image, $dirs, $base, $md5Text, $alternativeText, $imageType) { $name = preg_replace(array("#[^a-zA-Z0-9_-]+#", "#__+#", "#_\$#"), array('_', '_', ''), $alternativeText); $file = "{$name}.{$imageType}"; $splitMD5Path = eZDir::getPathFromFilename($md5Text); $dirPath = eZDir::path(array($dirs, $base, $splitMD5Path, $md5Text)); $image->store($file, $dirPath, $imageType); $fileHandler = eZClusterFileHandler::instance(); $filePath = eZDir::path(array($dirPath, $file)); $mimeData = eZMimeType::findByURL($filePath, true); $fileHandler->fileStore($filePath, 'texttoimage', false, $mimeData['name']); }
function generateXMLData() { $doc = new DOMDocument('1.0', 'utf-8'); $imageNode = $doc->createElement("ezimage"); $doc->appendChild($imageNode); $fileName = false; $imageManager = eZImageManager::factory(); $mimeData = eZMimeType::findByFileContents($fileName); $imageManager->analyzeImage($mimeData); $imageNode->setAttribute('serial_number', false); $imageNode->setAttribute('is_valid', false); $imageNode->setAttribute('filename', $fileName); $imageNode->setAttribute('suffix', false); $imageNode->setAttribute('basename', false); $imageNode->setAttribute('dirpath', false); $imageNode->setAttribute('url', false); $imageNode->setAttribute('original_filename', false); $imageNode->setAttribute('mime_type', false); $imageNode->setAttribute('width', false); $imageNode->setAttribute('height', false); $imageNode->setAttribute('alternative_text', false); $imageNode->setAttribute('alias_key', $imageManager->createImageAliasKey($imageManager->alias('original'))); $imageNode->setAttribute('timestamp', time()); $this->createImageInformationNode($imageNode, $mimeData); $this->storeDOMTree($doc, true, false); }
static function download($file, $isAttachedDownload = true, $overrideFilename = false) { if (file_exists($file)) { $mimeinfo = eZMimeType::findByURL($file); ob_clean(); header('X-Powered-By: eZ Publish'); header('Content-Length: ' . filesize($file)); header('Content-Type: ' . $mimeinfo['name']); // Fixes problems with IE when opening a file directly header("Pragma: "); header("Cache-Control: "); /* Set cache time out to 10 minutes, this should be good enough to work around an IE bug */ header("Expires: " . gmdate('D, d M Y H:i:s', time() + 600) . ' GMT'); if ($overrideFilename) { $mimeinfo['filename'] = $overrideFilename; } if ($isAttachedDownload) { header('Content-Disposition: attachment; filename=' . $mimeinfo['filename']); } else { header('Content-Disposition: inline; filename=' . $mimeinfo['filename']); } header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); ob_end_clean(); @readfile($file); eZExecution::cleanExit(); } else { return false; } }
function outputSendDataToClient($output, $headers_only = false) { if (!$output) { $this->appendLogEntry("outputData: no data available", 'outputSendDataToClient'); return eZWebDAVServer::FAILED_NOT_FOUND; } // Check if we are dealing with custom data. if ($output["data"]) { $this->appendLogEntry("outputData: DATA is a string...", 'outputSendDataToClient'); } elseif ($output["file"]) { $this->appendLogEntry("outputData: DATA is a file...", 'outputSendDataToClient'); $realPath = $output["file"]; // Check if the file/dir actually exists and is readable (permission): if (file_exists($realPath) && is_readable($realPath)) { $this->appendLogEntry("outputData: file exists on server...", 'outputSendDataToClient'); // Get misc. file info. $eTag = md5_file($realPath); $size = filesize($realPath); $dir = dirname($realPath); $file = basename($realPath); $mimeInfo = eZMimeType::findByURL($dir . '/' . $file); $mimeType = $mimeInfo['name']; // Send necessary headers to client. header('HTTP/1.1 200 OK'); header('Accept-Ranges: bytes'); header('Content-Length: ' . $size); header('Content-Type: ' . $mimeType); header('ETag: ' . $eTag); $text = @ob_get_contents(); if (strlen($text) != 0) { $this->appendLogEntry($text, "DAV: PHP Output"); } for ($i = 0, $obLevel = ob_get_level(); $i < $obLevel; ++$i) { ob_end_clean(); } if (!$headers_only) { // Attempt to open the file. $fp = fopen($realPath, "rb"); // Output the actual contents of the file. $status = fpassthru($fp); // Check if the last command succeded.. if ($status == $size) { return eZWebDAVServer::OK_SILENT; } else { return eZWebDAVServer::FAILED_FORBIDDEN; } } else { return eZWebDAVServer::OK_SILENT; } } else { $this->appendLogEntry("outputData: file DOES NOT exist on server...", 'outputSendDataToClient'); return eZWebDAVServer::FAILED_NOT_FOUND; } } else { $this->appendLogEntry("outputData: No file specified", 'outputSendDataToClient'); $text = @ob_get_contents(); if (strlen($text) != 0) { $this->appendLogEntry($text, "DAV: PHP Output"); } for ($i = 0, $obLevel = ob_get_level(); $i < $obLevel; ++$i) { ob_end_clean(); } return eZWebDAVServer::FAILED_NOT_FOUND; } }
/** * Handles the header part of a file transfer to the client * * @see download() * * @param string $file Path to the local file * @param bool $isAttachedDownload Determines weather to download the file as an attachment ( download popup box ) or not. * @param string $overrideFilename Filename to send in headers instead of the actual file's name * @param int $startOffset Offset to start transfer from, in bytes * @param int $length Data size to transfer * @param string $fileSize The file's size. If not given, actual filesize will be queried. Required to work with clusterized files... */ public static function downloadHeaders($file, $isAttachedDownload = true, $overrideFilename = false, $startOffset = 0, $length = false, $fileSize = false) { if ($fileSize === false) { if (!file_exists($file)) { eZDebug::writeError("\$fileSize not given, and file not found", __METHOD__); return false; } $fileSize = filesize($file); } header('X-Powered-By: eZ Publish'); $mimeinfo = eZMimeType::findByURL($file); header("Content-Type: {$mimeinfo['name']}"); // Fixes problems with IE when opening a file directly header("Pragma: "); header("Cache-Control: "); // Last-Modified header cannot be set, otherwise browser like FF will fail while resuming a paused download // because it compares the value of Last-Modified headers between requests. header("Last-Modified: "); /* Set cache time out to 10 minutes, this should be good enough to work around an IE bug */ header("Expires: " . gmdate('D, d M Y H:i:s', time() + 600) . ' GMT'); header("Content-Disposition: " . ($isAttachedDownload ? 'attachment' : 'inline') . ($overrideFilename !== false ? "; filename={$overrideFilename}" : '')); // partial download (HTTP 'Range' header) if ($startOffset !== 0) { $endOffset = $length !== false ? $length + $startOffset - 1 : $fileSize - 1; header("Content-Length: " . ($endOffset - $startOffset + 1)); header("Content-Range: bytes {$startOffset}-{$endOffset}/{$fileSize}"); header("HTTP/1.1 206 Partial Content"); } else { header("Content-Length: {$fileSize}"); } header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); }
function insertRegularFile( $object, $objectVersion, $objectLanguage, $objectAttribute, $filePath, &$result ) { $result = array( 'errors' => array(), 'require_storage' => false ); $attributeID = $objectAttribute->attribute( 'id' ); $binary = eZBinaryFile::fetch( $attributeID, $objectVersion ); if ( $binary === null ) $binary = eZBinaryFile::create( $attributeID, $objectVersion ); $fileName = basename( $filePath ); $mimeData = eZMimeType::findByFileContents( $filePath ); $storageDir = eZSys::storageDirectory(); list( $group, $type ) = explode( '/', $mimeData['name'] ); $destination = $storageDir . '/original/' . $group; if ( !file_exists( $destination ) ) { if ( !eZDir::mkdir( $destination, false, true ) ) { return false; } } // create dest filename in the same manner as eZHTTPFile::store() // grab file's suffix $fileSuffix = eZFile::suffix( $fileName ); // prepend dot if( $fileSuffix ) $fileSuffix = '.' . $fileSuffix; // grab filename without suffix $fileBaseName = basename( $fileName, $fileSuffix ); // create dest filename $destFileName = md5( $fileBaseName . microtime() . mt_rand() ) . $fileSuffix; $destination = $destination . '/' . $destFileName; copy( $filePath, $destination ); $fileHandler = eZClusterFileHandler::instance(); $fileHandler->fileStore( $destination, 'binaryfile', true, $mimeData['name'] ); $binary->setAttribute( "contentobject_attribute_id", $attributeID ); $binary->setAttribute( "version", $objectVersion ); $binary->setAttribute( "filename", $destFileName ); $binary->setAttribute( "original_filename", $fileName ); $binary->setAttribute( "mime_type", $mimeData['name'] ); $binary->store(); $objectAttribute->setContent( $binary ); return true; }
function outputMIMEType(&$manager, $currentMimeData, $wantedMimeData, $supportedFormatsOriginal, $aliasName = false) { if (is_array($this->conversionRules())) { $conversionRules = array_merge($manager->conversionRules(), $this->conversionRules()); } else { $conversionRules = $manager->conversionRules(); } $mimeData = false; $mimeType = false; if (!$this->isInputMIMETypeSupported($currentMimeData)) { return false; } if ($wantedMimeData) { $conversionRules = array_merge(array(array('from' => $currentMimeData['name'], 'to' => $wantedMimeData['name'])), $conversionRules); } $supportedFormats = array(); foreach ($supportedFormatsOriginal as $supportedFormat) { if ($this->isOutputMIMETypeSupported($supportedFormat)) { $supportedFormats[] = $supportedFormat; $conversionRules[] = array('from' => $supportedFormat, 'to' => $supportedFormat); } } if ($wantedMimeData and in_array($wantedMimeData['name'], $supportedFormats)) { $mimeType = $wantedMimeData['name']; } else { if (is_array($conversionRules)) { foreach ($conversionRules as $rule) { if (!$this->isOutputMIMETypeSupported($rule['to']) or !in_array($rule['to'], $supportedFormats)) { continue; } $matchRule = false; if (strpos($rule['from'], '*') !== false) { $matchString = eZImageHandler::wildcardToRegexp($rule['from']); if (preg_match("#^" . $matchString . "\$#", $currentMimeData['name'])) { $matchRule = $rule; } } else { if ($rule['from'] == $currentMimeData['name']) { $matchRule = $rule; } } if ($matchRule) { if ($mimeType) { if ($wantedMimeData and $matchRule['to'] == $wantedMimeData['name']) { $mimeType = $matchRule['to']; } } else { $mimeType = $matchRule['to']; } } } } } if ($mimeType) { $mimeData = eZMimeType::findByName($mimeType); $this->rewriteURL($currentMimeData, $mimeData, $this->outputRewriteType(), $aliasName); } return $mimeData; }
/** * Fetches the HTTP-File into $file and fills in MIME-Type information into $mimeData. * * @return bool false if something went wrong. */ function fetchHTTPFile($httpFileIdentifier, &$errors, &$file, &$mimeData) { $returnCode = eZHTTPFile::canFetch($httpFileIdentifier, 0); if ($returnCode !== eZHTTPFile::UPLOADEDFILE_OK && $returnCode !== true) { switch ($returnCode) { case eZHTTPFile::UPLOADEDFILE_DOES_NOT_EXIST: $errors[] = array('description' => ezpI18n::tr('kernel/content/upload', 'A file is required for upload, no file were found.')); break; case eZHTTPFile::UPLOADEDFILE_EXCEEDS_PHP_LIMIT: case eZHTTPFile::UPLOADEDFILE_EXCEEDS_MAX_SIZE: $errors[] = array('description' => ezpI18n::tr('kernel/content/upload', 'The uploaded file size is above the maximum limit.')); break; case eZHTTPFile::UPLOADEDFILE_MISSING_TMP_DIR: case eZHTTPFile::UPLOADEDFILE_CANT_WRITE: case eZHTTPFile::UPLOADEDFILE_UNKNOWN_ERROR: $errors[] = array('description' => ezpI18n::tr('kernel/content/upload', 'A system error occured while writing the uploaded file.')); break; } return false; } $file = eZHTTPFile::fetch($httpFileIdentifier); if (!$file instanceof eZHTTPFile) { $errors[] = array('description' => ezpI18n::tr('kernel/content/upload', 'Expected a eZHTTPFile object but got nothing.')); return false; } $mimeData = eZMimeType::findByFileContents($file->attribute("original_filename")); return true; }
function storedFilename(&$binary, $returnMimeData = false) { $origDir = eZSys::storageDirectory() . '/original'; $class = get_class($binary); $fileName = false; $originalFilename = false; if (in_array($class, array('eZBinaryFile', 'eZMedia'))) { $fileName = $origDir . "/" . $binary->attribute('mime_type_category') . '/' . $binary->attribute("filename"); $originalFilename = $binary->attribute('original_filename'); } else { if ($class == 'eZImageAliasHandler') { $alias = $binary->attribute('original'); if ($alias) { $fileName = $alias['url']; } $originalFilename = $binary->attribute('original_filename'); } } if ($fileName) { $mimeData = eZMimeType::findByFileContents($fileName); $mimeData['original_filename'] = $originalFilename; if (!isset($mimeData['name'])) { $mimeData['name'] = 'application/octet-stream'; } if ($returnMimeData) { return $mimeData; } else { return $mimeData['url']; } } return false; }
function fetchNodeInfo( &$node ) { // When finished, we'll return an array of attributes/properties. $entry = array(); // Grab settings from the ini file: $webdavINI = eZINI::instance( eZWebDAVContentServer::WEBDAV_INI_FILE ); $iniSettings = $webdavINI->variable( 'DisplaySettings', 'FileAttribute' ); $classIdentifier = $node->attribute( 'class_identifier' ); $object = $node->attribute( 'object' ); // By default, everything is displayed as a folder: // Trim the name of the node, it is in some cases whitespace in eZ Publish $entry["name"] = trim( $node->attribute( 'name' ) ); $entry["size"] = 0; $entry["mimetype"] = 'httpd/unix-directory'; $entry["ctime"] = $object->attribute( 'published' ); $entry["mtime"] = $object->attribute( 'modified' ); $upload = new eZContentUpload(); $info = $upload->objectFileInfo( $object ); $suffix = ''; $class = $object->contentClass(); $isObjectFolder = $this->isObjectFolder( $object, $class ); if ( $isObjectFolder ) { // We do nothing, the default is to see it as a folder } else if ( $info ) { $filePath = $info['filepath']; $entry["mimetype"] = false; $entry["size"] = false; if ( isset( $info['filesize'] ) ) $entry['size'] = $info['filesize']; if ( isset( $info['mime_type'] ) ) $entry['mimetype'] = $info['mime_type']; // Fill in information from the actual file if they are missing. $file = eZClusterFileHandler::instance( $filePath ); if ( !$entry['size'] and $file->exists() ) { $entry["size"] = $file->size(); } if ( !$entry['mimetype'] ) { $mimeInfo = eZMimeType::findByURL( $filePath ); $entry["mimetype"] = $mimeInfo['name']; $suffix = $mimeInfo['suffix']; if ( strlen( $suffix ) > 0 ) $entry["name"] .= '.' . $suffix; } else { // eZMimeType returns first suffix in its list // this could be another one than the original file extension // so let's try to get the suffix from the file path first $suffix = eZFile::suffix( $filePath ); if ( !$suffix ) { $mimeInfo = eZMimeType::findByName( $entry['mimetype'] ); $suffix = $mimeInfo['suffix']; } if ( strlen( $suffix ) > 0 ) $entry["name"] .= '.' . $suffix; } if ( $file->exists() ) { $entry["ctime"] = $file->mtime(); $entry["mtime"] = $file->mtime(); } } else { // Here we only show items as folders if they have // is_container set to true, otherwise it's an unknown binary file if ( !$class->attribute( 'is_container' ) ) { $entry['mimetype'] = 'application/octet-stream'; } } $scriptURL = eZSys::instance()->RequestURI; if ( strlen( $scriptURL ) > 0 and $scriptURL[ strlen( $scriptURL ) - 1 ] != "/" ) $scriptURL .= "/"; $trimmedScriptURL = trim( $scriptURL, '/' ); $scriptURLParts = explode( '/', $trimmedScriptURL ); $siteAccess = $scriptURLParts[0]; $virtualFolder = $scriptURLParts[1]; $startURL = '/' . $siteAccess . '/' . $virtualFolder . '/'; // Set the href attribute (note that it doesn't just equal the name). if ( !isset( $entry['href'] ) ) { if ( strlen( $suffix ) > 0 ) $suffix = '.' . $suffix; $alias = $node->urlAlias(); if ( $virtualFolder == eZWebDAVContentServer::virtualMediaFolderName() ) { // remove the real media node url alias, the virtual media folder is already in $startURL $aliasParts = explode( '/', $alias ); array_shift( $aliasParts ); $alias = implode( '/', $aliasParts ); } $entry["href"] = $startURL . $alias . $suffix; } // Return array of attributes/properties (name, size, mime, times, etc.). return $entry; }
static function mimeTypeFor($path, $file) { eZDebug::writeWarning('eZMimeType::mimeTypeFor() is deprecated, use eZMimeType::findByURL() instead', 'DEPRECATED FUNCTION eZMimeType::mimeTypeFor'); $url = $path; if ($url) { $url .= '/' . $file; } else { $url = $file; } $match = eZMimeType::findByURL($url, false); if ($match) { return $match['name']; } else { return false; } }
static function sendNewsletterMail($newsletter, $sendPreview = false, $previewFormat = false, $receiverLimit = null) { $sendMailSettings = eZINI::instance('ezsendmailsettings.ini'); $replaceMsgIDHost = $sendMailSettings->variable('SendNewsletter', 'ReplaceMessageIDHost'); $newSendHost = $sendMailSettings->variable('SendNewsletter', 'Host'); $hostSettings['replace'] = $replaceMsgIDHost; $hostSettings['host'] = $newSendHost; $mail = new eZNewsletterMail(); $sys = eZSys::instance(); $newsletterMailData = array(); // Check that the newsletter type exists, if not, process next newsletter if (!$newsletter->attribute('newsletter_type')) { return; } $newsletterMailData[eZNewsletter::OutputFormatText] = $newsletter->generateNewsletter(eZNewsletter::OutputFormatText, $sendPreview); $newsletterMailData[eZNewsletter::OutputFormatHTML] = $newsletter->generateNewsletter(eZNewsletter::OutputFormatHTML, $sendPreview); $newsletterMailData[eZNewsletter::OutputFormatExternalHTML] = $newsletter->generateNewsletter(eZNewsletter::OutputFormatExternalHTML, $sendPreview); $newsletterMailData[eZNewsletter::OutputFormatSMS] = $newsletter->generateNewsletter(eZNewsletter::OutputFormatSMS, $sendPreview); $newsletterOutputFormatList = $newsletter->attribute('output_format_list'); $noMimeMessage = "This message is in MIME format. Since your mail reader does not understand\nthis format, some or all of this message may not be legible."; $lineBreak = "\r\n"; $partCounter = 0; $boundary = date("YmdGHjs") . ':' . getmypid() . ':' . $partCounter++; $charset = eZTextCodec::internalCharset(); $contentTypeHtmlPart = "Content-Type: text/html; charset={$charset}"; foreach (array(eZNewsletter::OutputFormatHTML, eZNewsletter::OutputFormatExternalHTML) as $key) { $htmlOutput =& $newsletterMailData[$key]; if ($htmlOutput['imageNameMap']) { $data = $noMimeMessage . $lineBreak; $data .= $lineBreak . '--' . $boundary . $lineBreak; $data .= $contentTypeHtmlPart . $lineBreak; $data .= "Content-Transfer-Encoding: 8bit" . $lineBreak . $lineBreak; $data .= $htmlOutput['body'] . $lineBreak; foreach ($htmlOutput['imageNameMap'] as $id => $filename) { $filename = trim($filename); if (is_readable($filename)) { $mime = eZMimeType::findByURL($filename); $encodedFileContent = chunk_split(base64_encode(file_get_contents($filename)), 76, $lineBreak); $data .= $lineBreak . '--' . $boundary . $lineBreak; $data .= "Content-Type: " . $mime['name'] . ';' . $lineBreak . ' name="' . basename($filename) . '"' . $lineBreak; $data .= "Content-ID: <" . $id . ">" . $lineBreak; $data .= "Content-Transfer-Encoding: base64" . $lineBreak; $original_filename = basename($filename); if ($htmlOutput['imageNameMapName'][$id]) { $original_filename = $htmlOutput['imageNameMapName'][$id]; } $data .= 'Content-Disposition: INLINE;' . $lineBreak . ' filename="' . $original_filename . '"' . $lineBreak . $lineBreak; $data .= $encodedFileContent; } } $data .= $lineBreak . '--' . $boundary . '--'; $htmlOutput['body'] = $data; } else { $data = $noMimeMessage . $lineBreak; $data .= $lineBreak . '--' . $boundary . $lineBreak; $data .= $contentTypeHtmlPart . $lineBreak; $data .= "Content-Transfer-Encoding: 8bit" . $lineBreak . $lineBreak; $data .= $htmlOutput['body'] . $lineBreak; $data .= $lineBreak . '--' . $boundary . '--'; $htmlOutput['body'] = $data; } } // 4. Go through revceivers, and send emails. if (!$sendPreview) { $mail->setSender($newsletterMailData[eZNewsletter::OutputFormatText]['emailSender'], $newsletterMailData[eZNewsletter::OutputFormatText]['emailSenderName']); $idcounter = 0; $sendCount = 0; $skipCount = 0; // HACK! $receiverList = eZSendNewsletterItem::fetchByNewsletterID($newsletter->attribute('id'), 0, $receiverLimit); foreach ($receiverList as $receiver) { $msgid = eZNewsletter::generateMessageId($newsletterMailData[eZNewsletter::OutputFormatText]['emailSender'], $receiver->attribute('id'), $idcounter++, $hostSettings); $mail->setMessageID($msgid); $userData = $receiver->attribute('user_data'); if (!$userData) { //When no userdata is found, it is usually the result of a deleted subscription, //we mark the mail as being sent, without sending it. $receiver->setAttribute('send_status', eZSendNewsletterItem::SendStatusSent); $receiver->setAttribute('send_ts', time()); $receiver->sync(); continue; } // #TODO# IDs expected $userOutputFormatList = explode(',', $userData['output_format']); // #TODO# #echo " ### userOutputFormatList\n"; ok #var_dump( $userOutputFormatList ); #echo " ### newsletterOutputFormatList\n"; ok #var_dump( $newsletterOutputFormatList ); $outputFormat = false; //special case for SMS sending if (in_array(eZNewsletter::OutputFormatSMS, $userOutputFormatList) && in_array(eZNewsletter::OutputFormatSMS, $newsletterOutputFormatList)) { $mail->setContentType("sms", false, false, false, $boundary); $outputFormat = eZNewsletter::OutputFormatSMS; //$mail->setSubject( $userMailData['subject'] ); ### $userMailData is undefined # echo " ### userMailData\n"; # var_dump( $userMailData ); # $mail->setSubject( $userMailData['subject'] ); # $mail->setReceiver( $userData['email'] ); # $mail->setMobile( $userData['mobile'] ); //$mail->setBody( $userMailData['body'] ); ### $userMailData is undefined # $mail->setBody( $userMailData['body'] ); # $mail->setDateTimestamp( $newsletter->attribute( 'send_date') ); $mailResult = eZNewsletterMailTransport::send($mail, false); } //send regular emails if (in_array(eZNewsletter::OutputFormatHTML, $userOutputFormatList) && in_array(eZNewsletter::OutputFormatHTML, $newsletterOutputFormatList)) { $mail->setContentType("multipart/related", false, false, false, $boundary); $outputFormat = eZNewsletter::OutputFormatHTML; } if (in_array(eZNewsletter::OutputFormatExternalHTML, $userOutputFormatList) && in_array(eZNewsletter::OutputFormatExternalHTML, $newsletterOutputFormatList)) { $mail->setContentType("multipart/related", false, false, false, $boundary); $outputFormat = eZNewsletter::OutputFormatExternalHTML; } // ... if ($outputFormat === false) { $outputIntersect = array_intersect($userOutputFormatList, $newsletterOutputFormatList); if (count($outputIntersect) > 0) { $outputFormat = $outputIntersect[0]; } } if ($outputFormat !== false) { //personalize if set in type $newsletter_type = eZNewsletterType::fetch($newsletter->attribute('newslettertype_id')); if ($newsletter_type->attribute('personalise') === '1') { $userMailData = eZNewsletter::personalize($newsletterMailData[$outputFormat], $userData, true); } else { $userMailData = eZNewsletter::personalize($newsletterMailData[$outputFormat], $userData, false); } $mail->setSubject($userMailData['subject']); $mail->setReceiver($userData['email']); $mail->setMobile($userData['mobile']); $mail->setBody($userMailData['body']); $mail->setDateTimestamp($newsletter->attribute('send_date')); //if only SMS was selected, don't send email if (!(in_array(eZNewsletter::OutputFormatSMS, $userOutputFormatList) && count($userOutputFormatList) == 1)) { $mailResult = eZNewsletterMailTransport::send($mail, false); } $sendCount++; } else { // User doesnt want any format we defined - skipped $skipCount++; } $receiver->setAttribute('send_status', eZSendNewsletterItem::SendStatusSent); $receiver->setAttribute('send_ts', time()); $receiver->sync(); } //send SMS messages $instance = eZSMS::instance(); if ($instance->countNumbers() > 0) { echo "Preparing to send " . $instance->countNumbers() . " SMS messages..." . "\n"; $instance->setContent($newsletterMailData[eZNewsletter::OutputFormatSMS]['body']); foreach ($instance->getNumbers() as $number) { echo "Recipient is: " . $number . "\n"; } $reply = $instance->sendMessages(); if ($reply != "") { echo "SMS Reply:" . "\n"; echo $reply; } } //} return array('sendCount' => $sendCount, 'skipCount' => $skipCount); } else { //send preview $msgid = eZNewsletter::generateMessageId($newsletterMailData[eZNewsletter::OutputFormatText]['emailSender'], 0, 0, $hostSettings); $mail->setMessageID($msgid); $userOutputFormatList = $previewFormat; $outputFormat = false; //special case for SMS sending if (in_array(eZNewsletter::OutputFormatSMS, $userOutputFormatList)) { $mail->setContentType("sms", false, false, false, $boundary); $outputFormat = eZNewsletter::OutputFormatSMS; $newsletterMail = $newsletterMailData[eZNewsletter::OutputFormatSMS]; $mail->setSender($newsletterMail['emailSender'], $newsletterMail['emailSenderName']); $mail->setReceiver($newsletter->attribute('preview_email')); $mail->setMobile($newsletter->attribute('preview_mobile')); $mail->setBody($newsletterMail['body']); $mail->setSubject($newsletterMail['subject']); $mail->setDateTimestamp($newsletter->attribute('send_date')); $mailResult = eZNewsletterMailTransport::send($mail, true); } //send regular emails if (in_array(eZNewsletter::OutputFormatHTML, $userOutputFormatList)) { $mail->setContentType("multipart/related", false, false, false, $boundary); $outputFormat = eZNewsletter::OutputFormatHTML; } if (in_array(eZNewsletter::OutputFormatExternalHTML, $userOutputFormatList)) { $mail->setContentType("multipart/related", false, false, false, $boundary); $outputFormat = eZNewsletter::OutputFormatExternalHTML; } if ($outputFormat === false) { $outputIntersect = array_intersect($userOutputFormatList, $newsletterOutputFormatList); if (count($outputIntersect) > 0) { $outputFormat = $outputIntersect[0]; } } if ($outputFormat === false) { $outputFormat = $newsletterOutputFormatList[0]; if ($outputFormat == eZNewsletter::OutputFormatHTML || $outputFormat == eZNewsletter::OutputFormatExternalHTML) { $mail->setContentType("multipart/related", false, false, false, $boundary); } } $user = eZUser::currentUser(); $userObject = $user->attribute('contentobject'); //personalize if set in type $newsletter_type = eZNewsletterType::fetch($newsletter->attribute('newslettertype_id')); if ($newsletter_type->attribute('personalise') === '1') { $newsletterMail = $newsletter->personalize($newsletterMailData[$outputFormat], array('name' => $userObject->attribute('name')), true); } else { $newsletterMail = $newsletter->personalize($newsletterMailData[$outputFormat], array('name' => $userObject->attribute('name')), false); } $mail->setSender($newsletterMail['emailSender']); $mail->setReceiver($newsletter->attribute('preview_email')); $mail->setMobile($newsletter->attribute('preview_mobile')); $mail->setBody($newsletterMail['body']); $mail->setSubject($newsletterMail['subject']); $mail->setDateTimestamp($newsletter->attribute('send_date')); //if only SMS was selected, don't send email if (!(in_array(eZNewsletter::OutputFormatSMS, $userOutputFormatList) && count($userOutputFormatList) == 1)) { $mailResult = eZNewsletterMailTransport::send($mail, true); } //send SMS messages $instance = eZSMS::instance(); if ($instance->countNumbers() > 0) { //echo "Preparing to send ".$instance->countNumbers()." SMS messages..."."\n"; $instance->setContent($newsletterMailData[eZNewsletter::OutputFormatSMS]['body']); $reply = $instance->sendMessages(); if ($reply != "") { echo "SMS Reply:" . "\n"; echo $reply; } } } }