/**
  * 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());
 }
 /**
  * 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');
 }
 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}"];
 }
Exemple #4
0
 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;
     }
 }
    /**
     * @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 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;
    }
    /**
     * Creates the image alias $aliasName if it's not already part of the
     * existing aliases
     *
     * @param string $aliasName Name of the alias to create
     * @param array $existingAliasList
     *        Reference to the current alias list. The created alias will be
     *        added to the list.
     * @param array $parameters
     *        Optional array that can be used to specify the image's basename
     * @return bool true if the alias was created, false if it wasn't
     */
    function createImageAlias( $aliasName, &$existingAliasList, $parameters = array() )
    {
        $fname = "createImageAlias( $aliasName )";

        // check for $aliasName validity
        $aliasList = $this->aliasList();
        if ( !isset( $aliasList[$aliasName] ) )
        {
            eZDebug::writeWarning( "Alias name $aliasName does not exist, cannot create it" );
            return false;
        }

        // check if the reference alias is defined, and if no, use original as ref
        $currentAliasInfo = $aliasList[$aliasName];
        $referenceAlias = $currentAliasInfo['reference'];
        if ( $referenceAlias and !$this->hasAlias( $referenceAlias ) )
        {
            eZDebug::writeError( "The referenced alias '$referenceAlias' for image alias '$aliasName' does not exist, cannot use it for reference.\n" .
                                 "Will use 'original' alias instead.",
                                 __METHOD__ );
            $referenceAlias = false;
        }
        if ( !$referenceAlias )
            $referenceAlias = 'original';

        // generate the reference alias if it hasn't been generated yet
        $hasReference = false;
        if ( array_key_exists( $referenceAlias, $existingAliasList ) )
        {
            $fileHandler = eZClusterFileHandler::instance();
            if ( $fileHandler->fileExists( $existingAliasList[$referenceAlias]['url'] ) )
            {
                $hasReference = true;
            }
            else
            {
                eZDebug::writeError( "The reference alias $referenceAlias file {$existingAliasList[$referenceAlias]['url']} does not exist", __METHOD__ );
            }
        }
        if ( !$hasReference )
        {
            $ini = eZINI::instance( 'image.ini' );
            
            if ( $ini->hasVariable( 'AliasSettings', 'AlwaysGenerate') && $ini->variable( 'AliasSettings', 'AlwaysGenerate' ) == 'enabled' ) 
            {
                $mimeData = eZMimeType::findByURL( $existingAliasList[$referenceAlias]['url'] );
                $destinationMimeData = eZMimeType::findByName( $mimeData['name'] );

                if ( $aliasName != 'original' )
                {
                    foreach ( array( 'url', 'filename', 'basename') as $k )
                    {
                        $mimeData[$k] = preg_replace('#(\.[^.]+)$#', '_'.strtolower($aliasName).'.'.$destinationMimeData['suffix'], $mimeData[$k]);
                    }
                }
                $existingAliasList[$aliasName] = $mimeData;
                return true;
            } 
            else 
            {
                if ( $referenceAlias == 'original' )
                {
                    eZDebug::writeError( "Original alias does not exist, cannot create other aliases without it" );
                    return false;
                }
                if ( !$this->createImageAlias( $referenceAlias, $existingAliasList, $parameters ) )
                {
                    eZDebug::writeError( "Failed creating the referenced alias $referenceAlias, cannot create alias $aliasName", __METHOD__ );
                    return false;
                }
            }
        }

        // from now on, our reference image (either reference or original)
        // exists
        $aliasInfo = $existingAliasList[$referenceAlias];
        $aliasFilePath = $aliasInfo['url'];
        $aliasKey = $currentAliasInfo['alias_key'];

        $sourceMimeData = eZMimeType::findByFileContents( $aliasFilePath );

        /**
         * at first, destinationMimeData (mimedata for the alias we're
         * generating) is the same as sourceMimeData. It will evolve as
         * alias generation goes on
         */
        $destinationMimeData = $sourceMimeData;
        if ( isset( $parameters['basename'] ) )
        {
            $sourceMimeData['basename'] = $parameters['basename'];
            eZMimeType::changeBasename( $destinationMimeData, $parameters['basename'] );
        }

        /**
         * Concurrency protection
         * startCacheGeneration will return true if the file is not
         * already being generated by another process. If it is, it will
         * return the maximum time before the generating process enters
         * generation timeout
         */
        while ( true )
        {
            $convertHandler = eZClusterFileHandler::instance( $sourceMimeData['url'] );
            $startGeneration = $convertHandler->startCacheGeneration();
            if ( $startGeneration === true )
            {
                $destinationMimeData['is_valid'] = false;
                if ( $this->convert( $sourceMimeData, $destinationMimeData, $aliasName, $parameters ) )
                {
                    /**
                     * At this point, we consider that the image exists and destinationMimeData
                     * has been filled with the proper information
                     *
                     * If we were locked during alias generation, we need to recreate
                     * this structure so that the image can actually be used, but ONLY
                     * if it was the same alias... sounds like a HUGE mess.
                     *
                     * Can we reload the alias list somehow ?
                     */
                    $currentAliasData = array( 'url' => $destinationMimeData['url'],
                                               'dirpath' => $destinationMimeData['dirpath'],
                                               'filename' => $destinationMimeData['filename'],
                                               'suffix' => $destinationMimeData['suffix'],
                                               'basename' => $destinationMimeData['basename'],
                                               'alternative_text' => $aliasInfo['alternative_text'],
                                               'name' => $aliasName,
                                               'sub_type' => false,
                                               'timestamp' => time(),
                                               'alias_key' => $aliasKey,
                                               'mime_type' => $destinationMimeData['name'],
                                               'override_mime_type' => false,
                                               'info' => false,
                                               'width' => false,
                                               'height' => false,
                                               'is_valid' => true,
                                               'is_new' => true );

                    if ( isset( $destinationMimeData['override_mime_type'] ) )
                        $currentAliasData['override_mime_type'] = $destinationMimeData['override_mime_type'];
                    if ( isset( $destinationMimeData['info'] ) )
                        $currentAliasData['info'] = $destinationMimeData['info'];
                    $currentAliasData['full_path'] = $currentAliasData['url'];

                    if ( function_exists( 'getimagesize' ) )
                    {
                        /**
                         * we may want to fetch a unique name here, since we won't use
                         * the data for anything else
                         */
                        $fileHandler = eZClusterFileHandler::instance( $destinationMimeData['url'] );
                        if ( $tempPath = $fileHandler->fetchUnique() )
                        {
                            $info = getimagesize( $tempPath );
                            if ( $info )
                            {
                                list( $currentAliasData['width'], $currentAliasData['height'] ) = $info;
                            }
                            else
                            {
                                eZDebug::writeError("The size of the generated image {$destinationMimeData['url']} could not be read by getimagesize()", __METHOD__ );
                            }
                            $fileHandler->fileDeleteLocal( $tempPath );
                        }
                        else
                        {
                            eZDebug::writeError( "The destination image {$destinationMimeData['url']} does not exist, cannot figure out image size", __METHOD__ );
                        }
                    }
                    else
                    {
                        eZDebug::writeError( "Unknown function 'getimagesize', cannot get image size", __METHOD__ );
                    }
                    $existingAliasList[$aliasName] = $currentAliasData;

                    $convertHandler->endCacheGeneration( false );

                    // Notify about image alias generation. Parameters are alias
                    // url and alias name.
                    ezpEvent::getInstance()->notify( 'image/alias', array( $currentAliasData['url'],
                                                                           $currentAliasData['name'] ) );
                    
                    return true;
                }
                // conversion failed, we abort generation
                else
                {
                    $sourceFile = $sourceMimeData['url'];
                    $destinationDir = $destinationMimeData['dirpath'];
                    eZDebug::writeError( "Failed converting $sourceFile to alias '$aliasName' in directory '$destinationDir'", __METHOD__ );
                    $convertHandler->abortCacheGeneration();
                    return false;
                }
            }
            // we were not granted file generation (someone else is doing it)
            // we wait for max. $remainingGenerationTime and check if the
            // file has been generated in between
            // Actually, we have no clue if the generated file was the one we were
            // looking for, and it doesn't seem possible to RELOAD the alias list.
            // We don't even know what attribute we're using... CRAP
            else
            {
                eZDebug::writeDebug( "An alias is already being generated for this image, let's wait", __METHOD__ );
                while ( true )
                {
                    $startGeneration = $convertHandler->startCacheGeneration();
                    // generation lock granted: we can start again by breaking to
                    // the beggining of the while loop
                    if ( $startGeneration === true )
                    {
                        eZDebug::writeDebug( "Got granted generation permission, restarting !", __METHOD__ );
                        $convertHandler->abortCacheGeneration();
                        continue 2;
                    }
                    else
                    {
                        sleep( 1 );
                    }
                }
            }
        }
        return false;
    }
Exemple #9
0
 /**
  * Initializes the content object attribute with the uploaded HTTP file
  *
  * @param eZHTTPFile $httpFile
  * @param string $imageAltText Optional image ALT text
  *
  * @return TODO: FIXME
  */
 function initializeFromHTTPFile($httpFile, $imageAltText = false)
 {
     $this->increaseImageSerialNumber();
     $mimeData = eZMimeType::findByFileContents($httpFile->attribute('filename'));
     if (!$mimeData['is_valid']) {
         $mimeData = eZMimeType::findByName($httpFile->attribute('mime_type'));
         if (!$mimeData['is_valid']) {
             $mimeData = eZMimeType::findByURL($httpFile->attribute('original_filename'));
         }
     }
     $attr = false;
     $this->removeAliases($attr);
     $this->setOriginalAttributeDataValues($this->ContentObjectAttributeData['id'], $this->ContentObjectAttributeData['version'], $this->ContentObjectAttributeData['language_code']);
     $contentVersion = eZContentObjectVersion::fetchVersion($this->ContentObjectAttributeData['version'], $this->ContentObjectAttributeData['contentobject_id']);
     $objectName = $this->imageName($this->ContentObjectAttributeData, $contentVersion);
     $objectPathString = $this->imagePath($this->ContentObjectAttributeData, $contentVersion, true);
     eZMimeType::changeBaseName($mimeData, $objectName);
     eZMimeType::changeDirectoryPath($mimeData, $objectPathString);
     $httpFile->store(false, false, $mimeData);
     $originalFilename = $httpFile->attribute('original_filename');
     return $this->initialize($mimeData, $originalFilename, $imageAltText);
 }
 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;
     }
 }
 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;
}
    /**
     * 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');
        }
    }
 /**
  * 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;
 }
 /**
  * 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;
 }
Exemple #16
0
 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;
     }
 }
Exemple #17
0
 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;
             }
         }
     }
 }