Current File : /home/k/a/r/karenpetzb/www/items/category/File.tar
Transfer/Exception.php000060400000002747150713445260011014 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_File_Transfer
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * Zend_Exception
 */
require_once 'Zend/Exception.php';

/**
 * Exception class for Zend_File_Transfer
 *
 * @category   Zend
 * @package    Zend_File_Transfer
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_File_Transfer_Exception extends Zend_Exception
{
    protected $_fileerror = null;

    public function __construct($message, $fileerror = 0)
    {
        $this->_fileerror = $fileerror;
        parent::__construct($message);
    }

    /**
     * Returns the transfer error code for the exception
     * This is not the exception code !!!
     *
     * @return integer
     */
    public function getFileError()
    {
        return $this->_fileerror;
    }
}
Transfer/Adapter/Http.php000060400000016430150713445260011347 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_File_Transfer
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

require_once 'Zend/File/Transfer/Adapter/Abstract.php';

/**
 * File transfer adapter class for the HTTP protocol
 *
 * @category  Zend
 * @package   Zend_File_Transfer
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_File_Transfer_Adapter_Http extends Zend_File_Transfer_Adapter_Abstract
{
    /**
     * Constructor for Http File Transfers
     *
     * @param array $options OPTIONAL Options to set
     */
    public function __construct($options = array())
    {
        if (ini_get('file_uploads') == false) {
            require_once 'Zend/File/Transfer/Exception.php';
            throw new Zend_File_Transfer_Exception('File uploads are not allowed in your php config!');
        }

        $this->_files = $this->_prepareFiles($_FILES);
        $this->addValidator('Upload', false, $this->_files);

        if (is_array($options)) {
            $this->setOptions($options);
        }
    }

    /**
     * Sets a validator for the class, erasing all previous set
     *
     * @param  string|array $validator Validator to set
     * @param  string|array $files     Files to limit this validator to
     * @return Zend_File_Transfer_Adapter
     */
    public function setValidators(array $validators, $files = null)
    {
        $this->clearValidators();
        $this->addValidator('Upload', false, $this->_files);
        return $this->addValidators($validators, $files);
    }

    /**
     * Send the file to the client (Download)
     *
     * @param  string|array $options Options for the file(s) to send
     * @return void
     * @throws Zend_File_Transfer_Exception Not implemented
     */
    public function send($options = null)
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Method not implemented');
    }

    /**
     * Receive the file from the client (Upload)
     *
     * @param  string|array $files (Optional) Files to receive
     * @return bool
     */
    public function receive($files = null)
    {
        if (!$this->isValid($files)) {
            return false;
        }

        $check = $this->_getFiles($files);
        foreach ($check as $file => $content) {
            if (!$content['received']) {
                $directory   = '';
                $destination = $this->getDestination($file);
                if ($destination !== null) {
                    $directory = $destination . DIRECTORY_SEPARATOR;
                }

                // Should never return false when it's tested by the upload validator
                if (!move_uploaded_file($content['tmp_name'], ($directory . $content['name']))) {
                    if ($content['options']['ignoreNoFile']) {
                        $this->_files[$file]['received'] = true;
                        $this->_files[$file]['filtered'] = true;
                        continue;
                    }

                    $this->_files[$file]['received'] = false;
                    return false;
                }

                $this->_files[$file]['received'] = true;
            }

            if (!$content['filtered']) {
                if (!$this->_filter($file)) {
                    $this->_files[$file]['filtered'] = false;
                    return false;
                }

                $this->_files[$file]['filtered'] = true;
            }
        }

        return true;
    }

    /**
     * Checks if the file was already sent
     *
     * @param  string|array $file Files to check
     * @return bool
     * @throws Zend_File_Transfer_Exception Not implemented
     */
    public function isSent($files = null)
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Method not implemented');
    }

    /**
     * Checks if the file was already received
     *
     * @param  string|array $files (Optional) Files to check
     * @return bool
     */
    public function isReceived($files = null)
    {
        $files = $this->_getFiles($files);
        foreach ($files as $content) {
            if ($content['received'] !== true) {
                return false;
            }
        }

        return true;
    }

    /**
     * Checks if the file was already filtered
     *
     * @param  string|array $files (Optional) Files to check
     * @return bool
     */
    public function isFiltered($files = null)
    {
        $files = $this->_getFiles($files);
        foreach ($files as $content) {
            if ($content['filtered'] !== true) {
                return false;
            }
        }

        return true;
    }

    /**
     * Has a file been uploaded ?
     *
     * @param  array|string|null $file
     * @return bool
     */
    public function isUploaded($files = null)
    {
        $files = $this->_getFiles($files);
        foreach ($files as $file) {
            if (empty($file['name'])) {
                return false;
            }
        }

        return true;
    }

    /**
     * Returns the actual progress of file up-/downloads
     *
     * @return string Returns the state
     * @return int
     * @throws Zend_File_Transfer_Exception Not implemented
     */
    public function getProgress()
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Method not implemented');
    }

    /**
     * Prepare the $_FILES array to match the internal syntax of one file per entry
     *
     * @param  array $files
     * @return array
     */
    protected function _prepareFiles(array $files = array())
    {
        $result = array();
        foreach ($files as $form => $content) {
            if (is_array($content['name'])) {
                foreach ($content as $param => $file) {
                    foreach ($file as $number => $target) {
                        $result[$form . '_' . $number . '_'][$param]      = $target;
                        $result[$form . '_' . $number . '_']['options']   = $this->_options;
                        $result[$form . '_' . $number . '_']['validated'] = false;
                        $result[$form . '_' . $number . '_']['received']  = false;
                        $result[$form . '_' . $number . '_']['filtered']  = false;
                    }
                }
            } else {
                $result[$form]              = $content;
                $result[$form]['options']   = $this->_options;
                $result[$form]['validated'] = false;
                $result[$form]['received']  = false;
                $result[$form]['filtered']  = false;
            }
        }

        return $result;
    }
}
Transfer/Adapter/Abstract.php000060400000117405150713445260012177 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_File_Transfer
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * Abstract class for file transfers (Downloads and Uploads)
 *
 * @category  Zend
 * @package   Zend_File_Transfer
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_File_Transfer_Adapter_Abstract
{
    /**@+
     * @const string Plugin loader Constants
     */
    const FILTER    = 'FILTER';
    const VALIDATE  = 'VALIDATE';
    /**@-*/

    /**
     * Internal list of breaks
     *
     * @var array
     */
    protected $_break = array();

    /**
     * Internal list of filters
     *
     * @var array
     */
    protected $_filters = array();

    /**
     * Plugin loaders for filter and validation chains
     *
     * @var array
     */
    protected $_loaders = array();

    /**
     * Internal list of messages
     *
     * @var array
     */
    protected $_messages = array();

    /**
     * @var Zend_Translate
     */
    protected $_translator;

    /**
     * Is translation disabled?
     *
     * @var bool
     */
    protected $_translatorDisabled = false;

    /**
     * Internal list of validators
     * @var array
     */
    protected $_validators = array();

    /**
     * Internal list of files
     * This array looks like this:
     *     array(form => array( - Form is the name within the form or, if not set the filename
     *         name,            - Original name of this file
     *         type,            - Mime type of this file
     *         size,            - Filesize in bytes
     *         tmp_name,        - Internalally temporary filename for uploaded files
     *         error,           - Error which has occured
     *         destination,     - New destination for this file
     *         validators,      - Set validator names for this file
     *         files            - Set file names for this file
     *     ))
     *
     * @var array
     */
    protected $_files = array();

    /**
     * TMP directory
     * @var string
     */
    protected $_tmpDir;

    /**
     * Available options for file transfers
     */
    protected $_options = array(
        'ignoreNoFile' => false
    );

    /**
     * Send file
     *
     * @param  mixed $options
     * @return bool
     */
    abstract public function send($options = null);

    /**
     * Receive file
     *
     * @param  mixed $options
     * @return bool
     */
    abstract public function receive($options = null);

    /**
     * Is file sent?
     *
     * @param  array|string|null $files
     * @return bool
     */
    abstract public function isSent($files = null);

    /**
     * Is file received?
     *
     * @param  array|string|null $files
     * @return bool
     */
    abstract public function isReceived($files = null);

    /**
     * Has a file been uploaded ?
     *
     * @param  array|string|null $files
     * @return bool
     */
    abstract public function isUploaded($files = null);

    /**
     * Has the file been filtered ?
     *
     * @param array|string|null $files
     * @return bool
     */
    abstract public function isFiltered($files = null);

    /**
     * Retrieve progress of transfer
     *
     * @return float
     */
    abstract public function getProgress();

    /**
     * Set plugin loader to use for validator or filter chain
     *
     * @param  Zend_Loader_PluginLoader_Interface $loader
     * @param  string $type 'filter', or 'validate'
     * @return Zend_File_Transfer_Adapter_Abstract
     * @throws Zend_File_Transfer_Exception on invalid type
     */
    public function setPluginLoader(Zend_Loader_PluginLoader_Interface $loader, $type)
    {
        $type = strtoupper($type);
        switch ($type) {
            case self::FILTER:
            case self::VALIDATE:
                $this->_loaders[$type] = $loader;
                return $this;
            default:
                require_once 'Zend/File/Transfer/Exception.php';
                throw new Zend_File_Transfer_Exception(sprintf('Invalid type "%s" provided to setPluginLoader()', $type));
        }
    }

    /**
     * Retrieve plugin loader for validator or filter chain
     *
     * Instantiates with default rules if none available for that type. Use
     * 'filter' or 'validate' for $type.
     *
     * @param  string $type
     * @return Zend_Loader_PluginLoader
     * @throws Zend_File_Transfer_Exception on invalid type.
     */
    public function getPluginLoader($type)
    {
        $type = strtoupper($type);
        switch ($type) {
            case self::FILTER:
            case self::VALIDATE:
                $prefixSegment = ucfirst(strtolower($type));
                $pathSegment   = $prefixSegment;
                if (!isset($this->_loaders[$type])) {
                    $paths         = array(
                        'Zend_' . $prefixSegment . '_'     => 'Zend/' . $pathSegment . '/',
                        'Zend_' . $prefixSegment . '_File' => 'Zend/' . $pathSegment . '/File',
                    );

                    require_once 'Zend/Loader/PluginLoader.php';
                    $this->_loaders[$type] = new Zend_Loader_PluginLoader($paths);
                } else {
                    $loader = $this->_loaders[$type];
                    $prefix = 'Zend_' . $prefixSegment . '_File_';
                    if (!$loader->getPaths($prefix)) {
                        $loader->addPrefixPath($prefix, str_replace('_', '/', $prefix));
                    }
                }
                return $this->_loaders[$type];
            default:
                require_once 'Zend/File/Transfer/Exception.php';
                throw new Zend_File_Transfer_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
        }
    }

    /**
     * Add prefix path for plugin loader
     *
     * If no $type specified, assumes it is a base path for both filters and
     * validators, and sets each according to the following rules:
     * - filters:    $prefix = $prefix . '_Filter'
     * - validators: $prefix = $prefix . '_Validate'
     *
     * Otherwise, the path prefix is set on the appropriate plugin loader.
     *
     * @param  string $path
     * @return Zend_File_Transfer_Adapter_Abstract
     * @throws Zend_File_Transfer_Exception for invalid type
     */
    public function addPrefixPath($prefix, $path, $type = null)
    {
        $type = strtoupper($type);
        switch ($type) {
            case self::FILTER:
            case self::VALIDATE:
                $loader = $this->getPluginLoader($type);
                $loader->addPrefixPath($prefix, $path);
                return $this;
            case null:
                $prefix = rtrim($prefix, '_');
                $path   = rtrim($path, DIRECTORY_SEPARATOR);
                foreach (array(self::FILTER, self::VALIDATE) as $type) {
                    $cType        = ucfirst(strtolower($type));
                    $pluginPath   = $path . DIRECTORY_SEPARATOR . $cType . DIRECTORY_SEPARATOR;
                    $pluginPrefix = $prefix . '_' . $cType;
                    $loader       = $this->getPluginLoader($type);
                    $loader->addPrefixPath($pluginPrefix, $pluginPath);
                }
                return $this;
            default:
                require_once 'Zend/File/Transfer/Exception.php';
                throw new Zend_File_Transfer_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
        }
    }

    /**
     * Add many prefix paths at once
     *
     * @param  array $spec
     * @return Zend_File_Transfer_Exception
     */
    public function addPrefixPaths(array $spec)
    {
        if (isset($spec['prefix']) && isset($spec['path'])) {
            return $this->addPrefixPath($spec['prefix'], $spec['path']);
        }
        foreach ($spec as $type => $paths) {
            if (is_numeric($type) && is_array($paths)) {
                $type = null;
                if (isset($paths['prefix']) && isset($paths['path'])) {
                    if (isset($paths['type'])) {
                        $type = $paths['type'];
                    }
                    $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
                }
            } elseif (!is_numeric($type)) {
                if (!isset($paths['prefix']) || !isset($paths['path'])) {
                    foreach ($paths as $prefix => $spec) {
                        if (is_array($spec)) {
                            foreach ($spec as $path) {
                                if (!is_string($path)) {
                                    continue;
                                }
                                $this->addPrefixPath($prefix, $path, $type);
                            }
                        } elseif (is_string($spec)) {
                            $this->addPrefixPath($prefix, $spec, $type);
                        }
                    }
                } else {
                    $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
                }
            }
        }
        return $this;
    }

    /**
     * Adds a new validator for this class
     *
     * @param  string|array $validator           Type of validator to add
     * @param  boolean      $breakChainOnFailure If the validation chain should stop an failure
     * @param  string|array $options             Options to set for the validator
     * @param  string|array $files               Files to limit this validator to
     * @return Zend_File_Transfer_Adapter
     */
    public function addValidator($validator, $breakChainOnFailure = false, $options = null, $files = null)
    {
        if ($validator instanceof Zend_Validate_Interface) {
            $name = get_class($validator);
        } elseif (is_string($validator)) {
            $name      = $this->getPluginLoader(self::VALIDATE)->load($validator);
            $validator = new $name($options);
        } else {
            require_once 'Zend/File/Transfer/Exception.php';
            throw new Zend_File_Transfer_Exception('Invalid validator provided to addValidator; must be string or Zend_Validate_Interface');
        }

        $this->_validators[$name] = $validator;
        $this->_break[$name]      = $breakChainOnFailure;
        $files                    = $this->_getFiles($files, true, true);
        foreach ($files as $file) {
            $this->_files[$file]['validators'][] = $name;
            $this->_files[$file]['validated']    = false;
        }

        return $this;
    }

    /**
     * Add Multiple validators at once
     *
     * @param  array $validators
     * @param  string|array $files
     * @return Zend_File_Transfer_Adapter_Abstract
     */
    public function addValidators(array $validators, $files = null)
    {
        foreach ($validators as $name => $validatorInfo) {
            if ($validatorInfo instanceof Zend_Validate_Interface) {
                $this->addValidator($validatorInfo, null, null, $files);
            } else if (is_string($validatorInfo)) {
                if (!is_int($name)) {
                    $this->addValidator($name, null, $validatorInfo, $files);
                } else {
                    $this->addValidator($validatorInfo, null, null, $files);
                }
            } else if (is_array($validatorInfo)) {
                $argc                = count($validatorInfo);
                $breakChainOnFailure = false;
                $options             = array();
                if (isset($validatorInfo['validator'])) {
                    $validator = $validatorInfo['validator'];
                    if (isset($validatorInfo['breakChainOnFailure'])) {
                        $breakChainOnFailure = $validatorInfo['breakChainOnFailure'];
                    }

                    if (isset($validatorInfo['options'])) {
                        $options = $validatorInfo['options'];
                    }

                    $this->addValidator($validator, $breakChainOnFailure, $options, $files);
                } else {
                    if (is_string($name)) {
                        $validator = $name;
                        $options   = $validatorInfo;
                        $this->addValidator($validator, $breakChainOnFailure, $options, $files);
                    } else {
                        switch (true) {
                            case (0 == $argc):
                                break;
                            case (1 <= $argc):
                                $validator  = array_shift($validatorInfo);
                            case (2 <= $argc):
                                $breakChainOnFailure = array_shift($validatorInfo);
                            case (3 <= $argc):
                                $options = array_shift($validatorInfo);
                            case (4 <= $argc):
                                $files = array_shift($validatorInfo);
                            default:
                                $this->addValidator($validator, $breakChainOnFailure, $options, $files);
                                break;
                        }
                    }
                }
            } else {
                require_once 'Zend/Form/Exception.php';
                throw new Zend_Form_Exception('Invalid validator passed to addValidators()');
            }
        }

        return $this;
    }

    /**
     * Sets a validator for the class, erasing all previous set
     *
     * @param  string|array $validator Validator to set
     * @param  string|array $files     Files to limit this validator to
     * @return Zend_File_Transfer_Adapter
     */
    public function setValidators(array $validators, $files = null)
    {
        $this->clearValidators();
        return $this->addValidators($validators, $files);
    }

    /**
     * Determine if a given validator has already been registered
     *
     * @param  string $name
     * @return bool
     */
    public function hasValidator($name)
    {
        return (false !== $this->_getValidatorIdentifier($name));
    }

    /**
     * Retrieve individual validator
     *
     * @param  string $name
     * @return Zend_Validate_Interface|null
     */
    public function getValidator($name)
    {
        if (false === ($identifier = $this->_getValidatorIdentifier($name))) {
            return null;
        }
        return $this->_validators[$identifier];
    }

    /**
     * Returns all set validators
     *
     * @param  string|array $files (Optional) Returns the validator for this files
     * @return null|array List of set validators
     */
    public function getValidators($files = null)
    {
        $files = $this->_getFiles($files, true, true);

        if (empty($files)) {
            return $this->_validators;
        }

        $validators = array();
        foreach ($files as $file) {
            if (!empty($this->_files[$file]['validators'])) {
                $validators += $this->_files[$file]['validators'];
            }
        }
        $validators = array_unique($validators);

        $result = array();
        foreach ($validators as $validator) {
            $result[$validator] = $this->_validators[$validator];
        }
        return $result;
    }

    /**
     * Remove an individual validator
     *
     * @param  string $name
     * @return Zend_File_Transfer_Adapter_Abstract
     */
    public function removeValidator($name)
    {
        if (false === ($key = $this->_getValidatorIdentifier($name))) {
            return $this;
        }

        unset($this->_validators[$key]);
        foreach (array_keys($this->_files) as $file) {
            if (!$index = array_search($key, $this->_files[$file]['validators'])) {
                continue;
            }
            unset($this->_files[$file]['validators'][$index]);
            $this->_files[$file]['validated'] = false;
        }

        return $this;
    }

    /**
     * Remove all validators
     *
     * @return Zend_File_Transfer_Adapter_Abstract
     */
    public function clearValidators()
    {
        $this->_validators = array();
        foreach (array_keys($this->_files) as $file) {
            $this->_files[$file]['validators'] = array();
            $this->_files[$file]['validated']  = false;
        }

        return $this;
    }

    /**
     * Sets Options for adapters
     *
     * @param array $options Options to set
     * @param array $files   (Optional) Files to set the options for
     */
    public function setOptions($options = array(), $files = null) {
        $file = $this->_getFiles($files, false, true);

        if (is_array($options)) {
            foreach ($options as $name => $value) {
                foreach ($file as $key => $content) {
                    if (array_key_exists($name, $this->_options)) {
                        $this->_files[$key]['options'][$name] = (boolean) $value;
                    } else {
                        require_once 'Zend/File/Transfer/Exception.php';
                        throw new Zend_File_Transfer_Exception("Unknown option: $name = $value");
                    }
                }
            }
        }

        return $this;
    }

    /**
     * Returns set options for adapters or files
     *
     * @param  array $files (Optional) Files to return the options for
     * @return array Options for given files
     */
    public function getOptions($files = null) {
        $file = $this->_getFiles($files, false, true);

        foreach ($file as $key => $content) {
            if (isset($this->_files[$key]['options'])) {
                $options[$key] = $this->_files[$key]['options'];
            } else {
                $options[$key] = array();
            }
        }

        return $options;
    }

    /**
     * Checks if the files are valid
     *
     * @param  string|array $files (Optional) Files to check
     * @return boolean True if all checks are valid
     */
    public function isValid($files = null)
    {
        $check           = $this->_getFiles($files);
        $translator      = $this->getTranslator();
        $this->_messages = array();
        $break           = false;
        foreach ($check as $key => $content) {
            $fileerrors  = array();
            if ($content['validated'] === true) {
                continue;
            }

            if (array_key_exists('validators', $content)) {
                foreach ($content['validators'] as $class) {
                    $validator = $this->_validators[$class];
                    if (method_exists($validator, 'setTranslator')) {
                        $validator->setTranslator($translator);
                    }

                    $tocheck = $content['tmp_name'];
                    if (($class === 'Zend_Validate_File_Upload') and (empty($content['tmp_name']))) {
                        $tocheck = $key;
                    }

                    if (!$validator->isValid($tocheck, $content)) {
                        $fileerrors += $validator->getMessages();
                    }

                    if (!empty($content['options']['ignoreNoFile']) and (isset($fileerrors['fileUploadErrorNoFile']))) {
                        unset($fileerrors['fileUploadErrorNoFile']);
                        break;
                    }

                    if (($class === 'Zend_Validate_File_Upload') and (count($fileerrors) > 0)) {
                        break;
                    }

                    if (($this->_break[$class]) and (count($fileerrors) > 0)) {
                        $break = true;
                        break;
                    }
                }
            }

            if (count($fileerrors) > 0) {
                $this->_files[$key]['validated'] = false;
            } else {
                $this->_files[$key]['validated'] = true;
            }

            $this->_messages += $fileerrors;
            if ($break) {
                break;
            }
        }

        if (count($this->_messages) > 0) {
            return false;
        }

        return true;
    }

    /**
     * Returns found validation messages
     *
     * @return array
     */
    public function getMessages()
    {
        return $this->_messages;
    }

    /**
     * Retrieve error codes
     *
     * @return array
     */
    public function getErrors()
    {
        return array_keys($this->_messages);
    }

    /**
     * Are there errors registered?
     *
     * @return boolean
     */
    public function hasErrors()
    {
        return (!empty($this->_messages));
    }

    /**
     * Adds a new filter for this class
     *
     * @param  string|array $filter Type of filter to add
     * @param  string|array $options   Options to set for the filter
     * @param  string|array $files     Files to limit this filter to
     * @return Zend_File_Transfer_Adapter
     */
    public function addFilter($filter, $options = null, $files = null)
    {
        if ($filter instanceof Zend_Filter_Interface) {
            $class = get_class($filter);
        } elseif (is_string($filter)) {
            $class  = $this->getPluginLoader(self::FILTER)->load($filter);
            $filter = new $class($options);
        } else {
            require_once 'Zend/File/Transfer/Exception.php';
            throw new Zend_File_Transfer_Exception('Invalid filter specified');
        }

        $this->_filters[$class] = $filter;
        $files                  = $this->_getFiles($files, true, true);
        foreach ($files as $file) {
            $this->_files[$file]['filters'][] = $class;
        }

        return $this;
    }

    /**
     * Add Multiple filters at once
     *
     * @param  array $filters
     * @param  string|array $files
     * @return Zend_File_Transfer_Adapter_Abstract
     */
    public function addFilters(array $filters, $files = null)
    {
        foreach ($filters as $key => $spec) {
            if ($spec instanceof Zend_Filter_Interface) {
                $this->addFilter($spec, null, $files);
                continue;
            }

            if (is_string($key)) {
                $this->addFilter($key, $spec, $files);
                continue;
            }

            if (is_int($key)) {
                if (is_string($spec)) {
                    $this->addFilter($spec, null, $files);
                    continue;
                }

                if (is_array($spec)) {
                    if (!array_key_exists('filter', $spec)) {
                        continue;
                    }

                    $filter = $spec['filter'];
                    unset($spec['filter']);
                    $this->addFilter($filter, $spec, $files);
                    continue;
                }

                continue;
            }
        }

        return $this;
    }

    /**
     * Sets a filter for the class, erasing all previous set
     *
     * @param  string|array $filter Filter to set
     * @param  string|array $files     Files to limit this filter to
     * @return Zend_File_Transfer_Adapter
     */
    public function setFilters(array $filters, $files = null)
    {
        $this->clearFilters();
        return $this->addFilters($filters, $files);
    }

    /**
     * Determine if a given filter has already been registered
     *
     * @param  string $name
     * @return bool
     */
    public function hasFilter($name)
    {
        return (false !== $this->_getFilterIdentifier($name));
    }

    /**
     * Retrieve individual filter
     *
     * @param  string $name
     * @return Zend_Filter_Interface|null
     */
    public function getFilter($name)
    {
        if (false === ($identifier = $this->_getFilterIdentifier($name))) {
            return null;
        }
        return $this->_filters[$identifier];
    }

    /**
     * Returns all set filters
     *
     * @param  string|array $files (Optional) Returns the filter for this files
     * @return array List of set filters
     * @throws Zend_File_Transfer_Exception When file not found
     */
    public function getFilters($files = null)
    {
        if ($files === null) {
            return $this->_filters;
        }

        $files   = $this->_getFiles($files, true, true);
        $filters = array();
        foreach ($files as $file) {
            if (!empty($this->_files[$file]['filters'])) {
                $filters += $this->_files[$file]['filters'];
            }
        }

        $filters = array_unique($filters);
        $result  = array();
        foreach ($filters as $filter) {
            $result[] = $this->_filters[$filter];
        }

        return $result;
    }

    /**
     * Remove an individual filter
     *
     * @param  string $name
     * @return Zend_File_Transfer_Adapter_Abstract
     */
    public function removeFilter($name)
    {
        if (false === ($key = $this->_getFilterIdentifier($name))) {
            return $this;
        }

        unset($this->_filters[$key]);
        foreach (array_keys($this->_files) as $file) {
            if (!$index = array_search($key, $this->_files[$file]['filters'])) {
                continue;
            }
            unset($this->_files[$file]['filters'][$index]);
        }
        return $this;
    }

    /**
     * Remove all filters
     *
     * @return Zend_File_Transfer_Adapter_Abstract
     */
    public function clearFilters()
    {
        $this->_filters = array();
        foreach (array_keys($this->_files) as $file) {
            $this->_files[$file]['filters'] = array();
        }
        return $this;
    }

    /**
     * Returns all set files
     *
     * @return array List of set files
     * @throws Zend_File_Transfer_Exception Not implemented
     */
    public function getFile()
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Method not implemented');
    }

    /**
     * Retrieves the filename of transferred files.
     *
     * @param  string  $fileelement (Optional) Element to return the filename for
     * @param  boolean $path        (Optional) Should the path also be returned ?
     * @return string|array
     */
    public function getFileName($file = null, $path = true)
    {
        $files = $this->_getFiles($file, true, true);

        $result    = array();
        $directory = "";
        foreach($files as $file) {
            if (empty($this->_files[$file]['name'])) {
                continue;
            }

            if ($path === true) {
                $directory = $this->getDestination($file) . DIRECTORY_SEPARATOR;
            }

            $result[$file] = $directory . $this->_files[$file]['name'];
        }

        if (count($result) == 1) {
            return current($result);
        }

        return $result;
    }

    /**
     * Retrieve additional internal file informations for files
     *
     * @param  string $file (Optional) File to get informations for
     * @return array
     */
    public function getFileInfo($file = null)
    {
        return $this->_getFiles($file);
    }

    /**
     * Adds one or more files
     *
     * @param  string|array $file      File to add
     * @param  string|array $validator Validators to use for this file, must be set before
     * @param  string|array $filter    Filters to use for this file, must be set before
     * @return Zend_File_Transfer_Adapter_Abstract
     * @throws Zend_File_Transfer_Exception Not implemented
     */
    public function addFile($file, $validator = null, $filter = null)
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Method not implemented');
    }

    /**
     * Returns all set types
     *
     * @return array List of set types
     * @throws Zend_File_Transfer_Exception Not implemented
     */
    public function getType()
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Method not implemented');
    }

    /**
     * Adds one or more type of files
     *
     * @param  string|array $type Type of files to add
     * @param  string|array $validator Validators to use for this file, must be set before
     * @param  string|array $filter    Filters to use for this file, must be set before
     * @return Zend_File_Transfer_Adapter_Abstract
     * @throws Zend_File_Transfer_Exception Not implemented
     */
    public function addType($type, $validator = null, $filter = null)
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Method not implemented');
    }

    /**
     * Sets a new destination for the given files
     *
     * @deprecated Will be changed to be a filter!!!
     * @param  string       $destination New destination directory
     * @param  string|array $files       Files to set the new destination for
     * @return Zend_File_Transfer_Abstract
     * @throws Zend_File_Transfer_Exception when the given destination is not a directory or does not exist
     */
    public function setDestination($destination, $files = null)
    {
        $orig = $files;
        $destination = rtrim($destination, "/\\");
        if (!is_dir($destination)) {
            require_once 'Zend/File/Transfer/Exception.php';
            throw new Zend_File_Transfer_Exception('The given destination is no directory or does not exist');
        }

        if (!is_writable($destination)) {
            require_once 'Zend/File/Transfer/Exception.php';
            throw new Zend_File_Transfer_Exception('The given destination is not writeable');
        }

        if ($files === null) {
            foreach ($this->_files as $file => $content) {
                $this->_files[$file]['destination'] = $destination;
            }
        } else {
            $files = $this->_getFiles($files, true, true);
            if (empty($this->_files) and is_string($orig)) {
                $this->_files[$orig]['destination'] = $destination;
            }

            foreach ($files as $file) {
                $this->_files[$file]['destination'] = $destination;
            }
        }

        return $this;
    }

    /**
     * Retrieve destination directory value
     *
     * @param  null|string|array $files
     * @return null|string|array
     */
    public function getDestination($files = null)
    {
        $files = $this->_getFiles($files, false);
        $destinations = array();
        foreach ($files as $key => $content) {
            if (isset($this->_files[$key]['destination'])) {
                $destinations[$key] = $this->_files[$key]['destination'];
            } else {
                $tmpdir = $this->_getTmpDir();
                $this->setDestination($tmpdir, $key);
                $destinations[$key] = $tmpdir;
            }
        }

        if (empty($destinations)) {
            $destinations = $this->_getTmpDir();
        } else if (count($destinations) == 1) {
            $destinations = current($destinations);
        }

        return $destinations;
    }

    /**
     * Set translator object for localization
     *
     * @param  Zend_Translate|null $translator
     * @return Zend_File_Transfer_Abstract
     */
    public function setTranslator($translator = null)
    {
        if (null === $translator) {
            $this->_translator = null;
        } elseif ($translator instanceof Zend_Translate_Adapter) {
            $this->_translator = $translator;
        } elseif ($translator instanceof Zend_Translate) {
            $this->_translator = $translator->getAdapter();
        } else {
            require_once 'Zend/File/Transfer/Exception.php';
            throw new Zend_File_Transfer_Exception('Invalid translator specified');
        }

        return $this;
    }

    /**
     * Retrieve localization translator object
     *
     * @return Zend_Translate_Adapter|null
     */
    public function getTranslator()
    {
        if ($this->translatorIsDisabled()) {
            return null;
        }

        return $this->_translator;
    }

    /**
     * Indicate whether or not translation should be disabled
     *
     * @param  bool $flag
     * @return Zend_File_Transfer_Abstract
     */
    public function setDisableTranslator($flag)
    {
        $this->_translatorDisabled = (bool) $flag;
        return $this;
    }

    /**
     * Is translation disabled?
     *
     * @return bool
     */
    public function translatorIsDisabled()
    {
        return $this->_translatorDisabled;
    }

    /**
     * Returns the hash for a given file
     *
     * @param  string       $hash  Hash algorithm to use
     * @param  string|array $files Files to return the hash for
     * @return string|array Hashstring
     * @throws Zend_File_Transfer_Exception On unknown hash algorithm
     */
    public function getHash($hash = 'crc32', $files = null)
    {
        if (!in_array($hash, hash_algos())) {
            require_once 'Zend/File/Transfer/Exception.php';
            throw new Zend_File_Transfer_Exception('Unknown hash algorithm');
        }

        $files  = $this->_getFiles($files);
        $result = array();
        foreach($files as $key => $value) {
            if (file_exists($value['name'])) {
                $result[$key] = hash_file($hash, $value['name']);
            } else if (file_exists($value['tmp_name'])) {
                $result[$key] = hash_file($hash, $value['tmp_name']);
            }
        }

        if (count($result) == 1) {
            return current($result);
        }

        return $result;
    }

    /**
     * Internal function to filter all given files
     *
     * @param  string|array $files (Optional) Files to check
     * @return boolean False on error
     */
    protected function _filter($files = null)
    {
        $check           = $this->_getFiles($files);
        foreach ($check as $name => $content) {
            if (array_key_exists('filters', $content)) {
                foreach ($content['filters'] as $class) {
                    $filter = $this->_filters[$class];
                    try {
                        $result = $filter->filter($this->getFileName($name));

                        $this->_files[$name]['destination'] = dirname($result);
                        $this->_files[$name]['name']        = basename($result);
                    } catch (Zend_Filter_Exception $e) {
                        $this->_messages += array($e->getMessage());
                    }
                }
            }
        }

        if (count($this->_messages) > 0) {
            return false;
        }

        return true;
    }

    /**
     * Determine system TMP directory and detect if we have read access
     *
     * @return string
     * @throws Zend_File_Transfer_Exception if unable to determine directory
     */
    protected function _getTmpDir()
    {
        if (null === $this->_tmpDir) {
            $tmpdir = array();
            if (function_exists('sys_get_temp_dir')) {
                $tmpdir[] = sys_get_temp_dir();
            }

            if (!empty($_ENV['TMP'])) {
                $tmpdir[] = realpath($_ENV['TMP']);
            }

            if (!empty($_ENV['TMPDIR'])) {
                $tmpdir[] = realpath($_ENV['TMPDIR']);
            }

            if (!empty($_ENV['TEMP'])) {
                $tmpdir[] = realpath($_ENV['TEMP']);
            }

            $upload = ini_get('upload_tmp_dir');
            if ($upload) {
                $tmpdir[] = realpath($upload);
            }

            foreach($tmpdir as $directory) {
                if ($this->_isPathWriteable($directory)) {
                    $this->_tmpDir = $directory;
                }
            }

            if (empty($this->_tmpDir)) {
                // Attemp to detect by creating a temporary file
                $tempFile = tempnam(md5(uniqid(rand(), TRUE)), '');
                if ($tempFile) {
                    $this->_tmpDir = realpath(dirname($tempFile));
                    unlink($tempFile);
                } else {
                    require_once 'Zend/File/Transfer/Exception.php';
                    throw new Zend_File_Transfer_Exception('Could not determine temp directory');
                }
            }

            $this->_tmpDir = rtrim($this->_tmpDir, "/\\");
        }
        return $this->_tmpDir;
    }

    /**
     * Tries to detect if we can read and write to the given path
     *
     * @param string $path
     */
    protected function _isPathWriteable($path)
    {
        $tempFile = rtrim($path, "/\\");
        $tempFile .= '/' . 'test.1';

        $result = @file_put_contents($tempFile, 'TEST');

        if ($result == false) {
            return false;
        }

        $result = @unlink($tempFile);

        if ($result == false) {
            return false;
        }

        return true;
    }

    /**
     * Returns found files based on internal file array and given files
     *
     * @param  string|array $files       (Optional) Files to return
     * @param  boolean      $names       (Optional) Returns only names on true, else complete info
     * @param  boolean      $noexception (Optional) Allows throwing an exception, otherwise returns an empty array
     * @return array Found files
     * @throws Zend_File_Transfer_Exception On false filename
     */
    protected function _getFiles($files, $names = false, $noexception = false)
    {
        $check = array();

        if (is_string($files)) {
            $files = array($files);
        }

        if (is_array($files)) {
            foreach ($files as $find) {
                $found = array();
                foreach ($this->_files as $file => $content) {
                    if ($file === $find) {
                        $found[] = $file;
                        break;
                    }

                    if (strpos($file, ($find . '_')) !== false) {
                        $found[] = $file;
                    }

                    if (!isset($content['name'])) {
                        continue;
                    }

                    if ($content['name'] === $find) {
                        $found[] = $file;
                        break;
                    }
                }

                if (empty($found)) {
                    if ($noexception !== false) {
                        return array();
                    }

                    require_once 'Zend/File/Transfer/Exception.php';
                    throw new Zend_File_Transfer_Exception(sprintf('"%s" not found by file transfer adapter', $find));
                }

                foreach ($found as $checked) {
                    $check[$checked] = $this->_files[$checked];
                }
            }
        }

        if ($files === null) {
            $check = $this->_files;
        }

        if ($names) {
            $check = array_keys($check);
        }

        return $check;
    }

    /**
     * Retrieve internal identifier for a named validator
     *
     * @param  string $name
     * @return string
     */
    protected function _getValidatorIdentifier($name)
    {
        if (array_key_exists($name, $this->_validators)) {
            return $name;
        }

        foreach (array_keys($this->_validators) as $test) {
            if (preg_match('/' . preg_quote($name) . '$/i', $test)) {
                return $test;
            }
        }

        return false;
    }

    /**
     * Retrieve internal identifier for a named filter
     *
     * @param  string $name
     * @return string
     */
    protected function _getFilterIdentifier($name)
    {
        if (array_key_exists($name, $this->_filters)) {
            return $name;
        }

        foreach (array_keys($this->_filters) as $test) {
            if (preg_match('/' . preg_quote($name) . '$/i', $test)) {
                return $test;
            }
        }

        return false;
    }
}
Transfer.php000060400000003522150713445260007046 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_File_Transfer
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * Base class for all protocols supporting file transfers
 *
 * @category  Zend
 * @package   Zend_File_Transfer
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_File_Transfer
{
    /**
     * Creates a file processing handler
     *
     * @param string $protocol Protocol to use
     */
    public function __construct($protocol = null)
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Implementation in progress');

        switch (strtoupper($protocol)) {
            default:
                $adapter = 'Zend_File_Transfer_Adapter_Http';
                break;
        }
        
        Zend_Loader::loadClass($adapter);
        $this->_adapter = new $adapter();
        if (!$this->_adapter instanceof Zend_File_Transfer_Adapter) {
            require_once 'Zend/File/Transfer/Exception.php';
            throw new Zend_File_Transfer_Exception("Adapter " . $adapter . " does not extend Zend_File_Transfer_Adapter'");
        }

        return $this->_adapter;
    }
}
Size.php000060400000025727150713635440006210 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/Abstract.php';

/**
 * Validator for the maximum size of a file up to a max of 2GB
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_Size extends Zend_Validate_Abstract
{
    /**#@+
     * @const string Error constants
     */
    const TOO_BIG   = 'fileSizeTooBig';
    const TOO_SMALL = 'fileSizeTooSmall';
    const NOT_FOUND = 'fileSizeNotFound';
    /**#@-*/

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::TOO_BIG   => "Maximum allowed size for file '%value%' is '%max%' but '%size%' detected",
        self::TOO_SMALL => "Minimum expected size for file '%value%' is '%min%' but '%size%' detected",
        self::NOT_FOUND => "The file '%value%' could not be found"
    );

    /**
     * @var array Error message template variables
     */
    protected $_messageVariables = array(
        'min'  => '_min',
        'max'  => '_max',
        'size' => '_size',
    );

    /**
     * Minimum filesize
     * @var integer
     */
    protected $_min;

    /**
     * Maximum filesize
     *
     * If null, there is no maximum filesize
     *
     * @var integer|null
     */
    protected $_max;

    /**
     * Detected size
     *
     * @var integer
     */
    protected $_size;

    /**
     * Use bytestring ?
     *
     * @var boolean
     */
    protected $_useByteString = true;

    /**
     * Sets validator options
     *
     * If $options is a integer, it will be used as maximum filesize
     * As Array is accepts the following keys:
     * 'min': Minimum filesize
     * 'max': Maximum filesize
     * 'bytestring': Use bytestring or real size for messages
     *
     * @param  integer|array $options Options for the adapter
     */
    public function __construct($options)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } elseif (is_string($options) || is_numeric($options)) {
            $options = array('max' => $options);
        } elseif (!is_array($options)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception ('Invalid options to validator provided');
        }

        if (1 < func_num_args()) {
            trigger_error('Multiple constructor options are deprecated in favor of a single options array', E_USER_NOTICE);
            $argv = func_get_args();
            array_shift($argv);
            $options['max'] = array_shift($argv);
            if (!empty($argv)) {
                $options['bytestring'] = array_shift($argv);
            }
        }

        if (isset($options['bytestring'])) {
            $this->setUseByteString($options['bytestring']);
        }

        if (isset($options['min'])) {
            $this->setMin($options['min']);
        }

        if (isset($options['max'])) {
            $this->setMax($options['max']);
        }
    }

    /**
     * Returns the minimum filesize
     *
     * @param  boolean $byteString Use bytestring ?
     * @return integer
     */
    public function setUseByteString($byteString = true)
    {
        $this->_useByteString = (bool) $byteString;
        return $this;
    }

    /**
     * Will bytestring be used?
     *
     * @return boolean
     */
    public function useByteString()
    {
        return $this->_useByteString;
    }

    /**
     * Returns the minimum filesize
     *
     * @param  bool $raw Whether or not to force return of the raw value (defaults off)
     * @return integer|string
     */
    public function getMin($raw = false)
    {
        $min = $this->_min;
        if (!$raw && $this->useByteString()) {
            $min = $this->_toByteString($min);
        }

        return $min;
    }

    /**
     * Sets the minimum filesize
     *
     * @param  integer $min The minimum filesize
     * @throws Zend_Validate_Exception When min is greater than max
     * @return Zend_Validate_File_Size Provides a fluent interface
     */
    public function setMin($min)
    {
        if (!is_string($min) and !is_numeric($min)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception ('Invalid options to validator provided');
        }

        $min = (integer) $this->_fromByteString($min);
        $max = $this->getMax(true);
        if (($max !== null) && ($min > $max)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception("The minimum must be less than or equal to the maximum filesize, but $min >"
                                            . " $max");
        }

        $this->_min = $min;
        return $this;
    }

    /**
     * Returns the maximum filesize
     *
     * @param  bool $raw Whether or not to force return of the raw value (defaults off)
     * @return integer|string
     */
    public function getMax($raw = false)
    {
        $max = $this->_max;
        if (!$raw && $this->useByteString()) {
            $max = $this->_toByteString($max);
        }

        return $max;
    }

    /**
     * Sets the maximum filesize
     *
     * @param  integer $max The maximum filesize
     * @throws Zend_Validate_Exception When max is smaller than min
     * @return Zend_Validate_StringLength Provides a fluent interface
     */
    public function setMax($max)
    {
        if (!is_string($max) && !is_numeric($max)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception ('Invalid options to validator provided');
        }

        $max = (integer) $this->_fromByteString($max);
        $min = $this->getMin(true);
        if (($min !== null) && ($max < $min)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception("The maximum must be greater than or equal to the minimum filesize, but "
                                            . "$max < $min");
        }

        $this->_max = $max;
        return $this;
    }

    /**
     * Retrieve current detected file size
     *
     * @return int
     */
    protected function _getSize()
    {
        return $this->_size;
    }

    /**
     * Set current size
     *
     * @param  int $size
     * @return Zend_Validate_File_Size
     */
    protected function _setSize($size)
    {
        $this->_size = $size;
        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the filesize of $value is at least min and
     * not bigger than max (when max is not null).
     *
     * @param  string $value Real file to check for size
     * @param  array  $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_FOUND);
        }

        // limited to 4GB files
        $size = sprintf("%u", @filesize($value));

        // Check to see if it's smaller than min size
        $min = $this->getMin(true);
        $max = $this->getMax(true);
        if (($min !== null) && ($size < $min)) {
            if ($this->useByteString()) {
                $this->_min  = $this->_toByteString($min);
                $this->_size = $this->_toByteString($size);
                $this->_throw($file, self::TOO_SMALL);
                $this->_min  = $min;
                $this->_size = $size;
            } else {
                $this->_throw($file, self::TOO_SMALL);
            }
        }

        // Check to see if it's larger than max size
        if (($max !== null) && ($max < $size)) {
            if ($this->useByteString()) {
                $this->_max  = $this->_toByteString($max);
                $this->_size = $this->_toByteString($size);
                $this->_throw($file, self::TOO_BIG);
                $this->_max  = $max;
                $this->_size = $size;
            } else {
                $this->_throw($file, self::TOO_BIG);
            }
        }

        if (count($this->_messages) > 0) {
            return false;
        }

        return true;
    }

    /**
     * Returns the formatted size
     *
     * @param  integer $size
     * @return string
     */
    protected function _toByteString($size)
    {
        $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
        for ($i=0; $size >= 1024 && $i < 9; $i++) {
            $size /= 1024;
        }

        return round($size, 2) . $sizes[$i];
    }

    /**
     * Returns the unformatted size
     *
     * @param  string $size
     * @return integer
     */
    protected function _fromByteString($size)
    {
        if (is_numeric($size)) {
            return (integer) $size;
        }

        $type  = trim(substr($size, -2, 1));

        $value = substr($size, 0, -1);
        if (!is_numeric($value)) {
            $value = substr($value, 0, -1);
        }

        switch (strtoupper($type)) {
            case 'Y':
                $value *= (1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024);
                break;
            case 'Z':
                $value *= (1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024);
                break;
            case 'E':
                $value *= (1024 * 1024 * 1024 * 1024 * 1024 * 1024);
                break;
            case 'P':
                $value *= (1024 * 1024 * 1024 * 1024 * 1024);
                break;
            case 'T':
                $value *= (1024 * 1024 * 1024 * 1024);
                break;
            case 'G':
                $value *= (1024 * 1024 * 1024);
                break;
            case 'M':
                $value *= (1024 * 1024);
                break;
            case 'K':
                $value *= 1024;
                break;
            default:
                break;
        }

        return $value;
    }

    /**
     * Throws an error of the given type
     *
     * @param  string $file
     * @param  string $errorType
     * @return false
     */
    protected function _throw($file, $errorType)
    {
        if ($file !== null) {
            $this->_value = $file['name'];
        }

        $this->_error($errorType);
        return false;
    }
}
MimeType.php000060400000017274150713635440007025 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/Abstract.php';

/**
 * Validator for the mime type of a file
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_MimeType extends Zend_Validate_Abstract
{
    /**#@+
     * @const Error type constants
     */
    const FALSE_TYPE   = 'fileMimeTypeFalse';
    const NOT_DETECTED = 'fileMimeTypeNotDetected';
    const NOT_READABLE = 'fileMimeTypeNotReadable';
    /**#@-*/

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::FALSE_TYPE   => "The file '%value%' has a false mimetype of '%type%'",
        self::NOT_DETECTED => "The mimetype of file '%value%' could not been detected",
        self::NOT_READABLE => "The file '%value%' can not be read"
    );

    /**
     * @var array
     */
    protected $_messageVariables = array(
        'type' => '_type'
    );

    /**
     * @var string
     */
    protected $_type;

    /**
     * Mimetypes
     *
     * If null, there is no mimetype
     *
     * @var string|null
     */
    protected $_mimetype;

    /**
     * Magicfile to use
     *
     * @var string|null
     */
    protected $_magicfile;

    /**
     * Sets validator options
     *
     * Mimetype to accept
     *
     * @param  string|array $mimetype MimeType
     * @return void
     */
    public function __construct($mimetype)
    {
        if ($mimetype instanceof Zend_Config) {
            $mimetype = $mimetype->toArray();
        } elseif (is_string($mimetype)) {
            $mimetype = explode(',', $mimetype);
        } elseif (!is_array($mimetype)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception("Invalid options to validator provided");
        }

        if (isset($mimetype['magicfile'])) {
            $this->setMagicFile($mimetype['magicfile']);
        }

        $this->setMimeType($mimetype);
    }

    /**
     * Returna the actual set magicfile
     *
     * @return string
     */
    public function getMagicFile()
    {
        return $this->_magicfile;
    }

    /**
     * Sets the magicfile to use
     * if null, the MAGIC constant from php is used
     *
     * @param  string $file
     * @return Zend_Validate_File_MimeType Provides fluid interface
     */
    public function setMagicFile($file)
    {
        if (empty($file)) {
            $this->_magicfile = null;
        } else if (!is_readable($file)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception('The given magicfile can not be read');
        } else {
            $this->_magicfile = (string) $file;
        }

        return $this;
    }

    /**
     * Returns the set mimetypes
     *
     * @param  boolean $asArray Returns the values as array, when false an concated string is returned
     * @return string|array
     */
    public function getMimeType($asArray = false)
    {
        $asArray   = (bool) $asArray;
        $mimetype = (string) $this->_mimetype;
        if ($asArray) {
            $mimetype = explode(',', $mimetype);
        }

        return $mimetype;
    }

    /**
     * Sets the mimetypes
     *
     * @param  string|array $mimetype The mimetypes to validate
     * @return Zend_Validate_File_Extension Provides a fluent interface
     */
    public function setMimeType($mimetype)
    {
        $this->_mimetype = null;
        $this->addMimeType($mimetype);
        return $this;
    }

    /**
     * Adds the mimetypes
     *
     * @param  string|array $mimetype The mimetypes to add for validation
     * @return Zend_Validate_File_Extension Provides a fluent interface
     */
    public function addMimeType($mimetype)
    {
        $mimetypes = $this->getMimeType(true);

        if (is_string($mimetype)) {
            $mimetype = explode(',', $mimetype);
        } elseif (!is_array($mimetype)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception("Invalid options to validator provided");
        }

        if (isset($mimetype['magicfile'])) {
            unset($mimetype['magicfile']);
        }

        foreach ($mimetype as $content) {
            if (empty($content) || !is_string($content)) {
                continue;
            }
            $mimetypes[] = trim($content);
        }
        $mimetypes = array_unique($mimetypes);

        // Sanity check to ensure no empty values
        foreach ($mimetypes as $key => $mt) {
            if (empty($mt)) {
                unset($mimetypes[$key]);
            }
        }

        $this->_mimetype = implode(',', $mimetypes);

        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if the mimetype of the file matches the given ones. Also parts
     * of mimetypes can be checked. If you give for example "image" all image
     * mime types will be accepted like "image/gif", "image/jpeg" and so on.
     *
     * @param  string $value Real file to check for mimetype
     * @param  array  $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_READABLE);
        }

        if ($file !== null) {
            $mimefile = $this->getMagicFile();
            if (class_exists('finfo', false) && ((!empty($mimefile)) or (defined('MAGIC')))) {
                if (!empty($mimefile)) {
                    $mime = new finfo(FILEINFO_MIME, $mimefile);
                } else {
                    $mime = new finfo(FILEINFO_MIME);
                }

                $this->_type = $mime->file($value);
                unset($mime);
            } elseif (function_exists('mime_content_type') && ini_get('mime_magic.magicfile')) {
                $this->_type = mime_content_type($value);
            } else {
                $this->_type = $file['type'];
            }
        }

        if (empty($this->_type)) {
            return $this->_throw($file, self::NOT_DETECTED);
        }

        $mimetype = $this->getMimeType(true);
        if (in_array($this->_type, $mimetype)) {
            return true;
        }

        $types = explode('/', $this->_type);
        $types = array_merge($types, explode('-', $this->_type));
        foreach($mimetype as $mime) {
            if (in_array($mime, $types)) {
                return true;
            }
        }

        return $this->_throw($file, self::FALSE_TYPE);
    }

    /**
     * Throws an error of the given type
     *
     * @param  string $file
     * @param  string $errorType
     * @return false
     */
    protected function _throw($file, $errorType)
    {
        if ($file !== null) {
            $this->_value = $file['name'];
        }

        $this->_error($errorType);
        return false;
    }
}
ExcludeMimeType.php000060400000006006150713635440010326 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_File_MimeType
 */
require_once 'Zend/Validate/File/MimeType.php';

/**
 * Validator for the mime type of a file
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_ExcludeMimeType extends Zend_Validate_File_MimeType
{
    const FALSE_TYPE   = 'fileExcludeMimeTypeFalse';
    const NOT_DETECTED = 'fileExcludeMimeTypeNotDetected';
    const NOT_READABLE = 'fileExcludeMimeTypeNotReadable';

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if the mimetype of the file does not matche the given ones. Also parts
     * of mimetypes can be checked. If you give for example "image" all image
     * mime types will not be accepted like "image/gif", "image/jpeg" and so on.
     *
     * @param  string $value Real file to check for mimetype
     * @param  array  $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_READABLE);
        }

        if ($file !== null) {
            if (class_exists('finfo', false) && defined('MAGIC')) {
                $mime = new finfo(FILEINFO_MIME);
                $this->_type = $mime->file($value);
                unset($mime);
            } elseif (function_exists('mime_content_type') && ini_get('mime_magic.magicfile')) {
                $this->_type = mime_content_type($value);
            } else {
                $this->_type = $file['type'];
            }
        }

        if (empty($this->_type)) {
            return $this->_throw($file, self::NOT_DETECTED);
        }

        $mimetype = $this->getMimeType(true);
        if (in_array($this->_type, $mimetype)) {
            return $this->_throw($file, self::FALSE_TYPE);
        }

        $types = explode('/', $this->_type);
        $types = array_merge($types, explode('-', $this->_type));
        foreach($mimetype as $mime) {
            if (in_array($mime, $types)) {
                return $this->_throw($file, self::FALSE_TYPE);
            }
        }

        return true;
    }
}
ImageSize.php000060400000026062150713635440007144 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/Abstract.php';

/**
 * Validator for the image size of a image file
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_ImageSize extends Zend_Validate_Abstract
{
    /**
     * @const string Error constants
     */
    const WIDTH_TOO_BIG    = 'fileImageSizeWidthTooBig';
    const WIDTH_TOO_SMALL  = 'fileImageSizeWidthTooSmall';
    const HEIGHT_TOO_BIG   = 'fileImageSizeHeightTooBig';
    const HEIGHT_TOO_SMALL = 'fileImageSizeHeightTooSmall';
    const NOT_DETECTED     = 'fileImageSizeNotDetected';
    const NOT_READABLE     = 'fileImageSizeNotReadable';

    /**
     * @var array Error message template
     */
    protected $_messageTemplates = array(
        self::WIDTH_TOO_BIG    => "Maximum allowed width for image '%value%' should be '%maxwidth%' but '%width%' detected",
        self::WIDTH_TOO_SMALL  => "Minimum expected width for image '%value%' should be '%minwidth%' but '%width%' detected",
        self::HEIGHT_TOO_BIG   => "Maximum allowed height for image '%value%' should be '%maxheight%' but '%height%' detected",
        self::HEIGHT_TOO_SMALL => "Minimum expected height for image '%value%' should be '%minheight%' but '%height%' detected",
        self::NOT_DETECTED     => "The size of image '%value%' could not be detected",
        self::NOT_READABLE     => "The image '%value%' can not be read"
    );

    /**
     * @var array Error message template variables
     */
    protected $_messageVariables = array(
        'minwidth'  => '_minwidth',
        'maxwidth'  => '_maxwidth',
        'minheight' => '_minheight',
        'maxheight' => '_maxheight',
        'width'     => '_width',
        'height'    => '_height'
    );

    /**
     * Minimum image width
     *
     * @var integer
     */
    protected $_minwidth;

    /**
     * Maximum image width
     *
     * @var integer
     */
    protected $_maxwidth;

    /**
     * Minimum image height
     *
     * @var integer
     */
    protected $_minheight;

    /**
     * Maximum image height
     *
     * @var integer
     */
    protected $_maxheight;

    /**
     * Detected width
     *
     * @var integer
     */
    protected $_width;

    /**
     * Detected height
     *
     * @var integer
     */
    protected $_height;

    /**
     * Sets validator options
     *
     * Accepts the following option keys:
     * - minheight
     * - minwidth
     * - maxheight
     * - maxwidth
     *
     * @param  Zend_Config|array $options
     * @return void
     */
    public function __construct($options)
    {
        $minwidth  = 0;
        $minheight = 0;
        $maxwidth  = null;
        $maxheight = null;

        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } elseif (1 < func_num_args()) {
            trigger_error('Multiple constructor options are deprecated in favor of a single options array', E_USER_NOTICE);
            if (!is_array($options)) {
                $options = array('minwidth' => $options);
            }
            $argv = func_get_args();
            array_shift($argv);
            $options['minheight'] = array_shift($argv);
            if (!empty($argv)) {
                $options['maxwidth'] = array_shift($argv);
                if (!empty($argv)) {
                    $options['maxheight'] = array_shift($argv);
                }
            }
        } else if (!is_array($options)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception ('Invalid options to validator provided');
        }

        if (isset($options['minheight']) || isset($options['minwidth'])) {
            $this->setImageMin($options);
        }

        if (isset($options['maxheight']) || isset($options['maxwidth'])) {
            $this->setImageMax($options);
        }
    }

    /**
     * Returns the set minimum image sizes
     *
     * @return array
     */
    public function getImageMin()
    {
        return array('minwidth' => $this->_minwidth, 'minheight' => $this->_minheight);
    }

    /**
     * Returns the set maximum image sizes
     *
     * @return array
     */
    public function getImageMax()
    {
        return array('maxwidth' => $this->_maxwidth, 'maxheight' => $this->_maxheight);
    }

    /**
     * Returns the set image width sizes
     *
     * @return array
     */
    public function getImageWidth()
    {
        return array('minwidth' => $this->_minwidth, 'maxwidth' => $this->_maxwidth);
    }

    /**
     * Returns the set image height sizes
     *
     * @return array
     */
    public function getImageHeight()
    {
        return array('minheight' => $this->_minheight, 'maxheight' => $this->_maxheight);
    }

    /**
     * Sets the minimum image size
     *
     * @param  array $options               The minimum image dimensions
     * @throws Zend_Validate_Exception      When minwidth is greater than maxwidth
     * @throws Zend_Validate_Exception      When minheight is greater than maxheight
     * @return Zend_Validate_File_ImageSize Provides a fluent interface
     */
    public function setImageMin($options)
    {
        if (isset($options['minwidth'])) {
            if (($this->_maxwidth !== null) and ($options['minwidth'] > $this->_maxwidth)) {
                require_once 'Zend/Validate/Exception.php';
                throw new Zend_Validate_Exception("The minimum image width must be less than or equal to the "
                    . " maximum image width, but {$options['minwidth']} > {$this->_maxwidth}");
            }
        }

        if (isset($options['maxheight'])) {
            if (($this->_maxheight !== null) and ($options['minheight'] > $this->_maxheight)) {
                require_once 'Zend/Validate/Exception.php';
                throw new Zend_Validate_Exception("The minimum image height must be less than or equal to the "
                    . " maximum image height, but {$options['minheight']} > {$this->_maxheight}");
            }
        }

        if (isset($options['minwidth'])) {
            $this->_minwidth  = (int) $options['minwidth'];
        }

        if (isset($options['minheight'])) {
            $this->_minheight = (int) $options['minheight'];
        }

        return $this;
    }

    /**
     * Sets the maximum image size
     *
     * @param  array $options          The maximum image dimensions
     * @throws Zend_Validate_Exception When maxwidth is smaller than minwidth
     * @throws Zend_Validate_Exception When maxheight is smaller than minheight
     * @return Zend_Validate_StringLength Provides a fluent interface
     */
    public function setImageMax($options)
    {
        if (isset($options['maxwidth'])) {
            if (($this->_minwidth !== null) and ($options['maxwidth'] < $this->_minwidth)) {
                require_once 'Zend/Validate/Exception.php';
                throw new Zend_Validate_Exception("The maximum image width must be greater than or equal to the "
                    . "minimum image width, but {$options['maxwidth']} < {$this->_minwidth}");
            }
        }

        if (isset($options['maxheight'])) {
            if (($this->_minheight !== null) and ($options['maxheight'] < $this->_minheight)) {
                require_once 'Zend/Validate/Exception.php';
                throw new Zend_Validate_Exception("The maximum image height must be greater than or equal to the "
                    . "minimum image height, but {$options['maxheight']} < {$this->_minwidth}");
            }
        }

        if (isset($options['maxwidth'])) {
            $this->_maxwidth  = (int) $options['maxwidth'];
        }

        if (isset($options['maxheight'])) {
            $this->_maxheight = (int) $options['maxheight'];
        }

        return $this;
    }

    /**
     * Sets the mimimum and maximum image width
     *
     * @param  array $options               The image width dimensions
     * @return Zend_Validate_File_ImageSize Provides a fluent interface
     */
    public function setImageWidth($options)
    {
        $this->setImageMin($options);
        $this->setImageMax($options);

        return $this;
    }

    /**
     * Sets the mimimum and maximum image height
     *
     * @param  array $options               The image height dimensions
     * @return Zend_Validate_File_ImageSize Provides a fluent interface
     */
    public function setImageHeight($options)
    {
        $this->setImageMin($options);
        $this->setImageMax($options);

        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the imagesize of $value is at least min and
     * not bigger than max
     *
     * @param  string $value Real file to check for image size
     * @param  array  $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_READABLE);
        }

        $size = @getimagesize($value);
        $this->_setValue($file);

        if (empty($size) or ($size[0] === 0) or ($size[1] === 0)) {
            return $this->_throw($file, self::NOT_DETECTED);
        }

        $this->_width  = $size[0];
        $this->_height = $size[1];
        if ($this->_width < $this->_minwidth) {
            $this->_throw($file, self::WIDTH_TOO_SMALL);
        }

        if (($this->_maxwidth !== null) and ($this->_maxwidth < $this->_width)) {
            $this->_throw($file, self::WIDTH_TOO_BIG);
        }

        if ($this->_height < $this->_minheight) {
            $this->_throw($file, self::HEIGHT_TOO_SMALL);
        }

        if (($this->_maxheight !== null) and ($this->_maxheight < $this->_height)) {
            $this->_throw($file, self::HEIGHT_TOO_BIG);
        }

        if (count($this->_messages) > 0) {
            return false;
        }

        return true;
    }

    /**
     * Throws an error of the given type
     *
     * @param  string $file
     * @param  string $errorType
     * @return false
     */
    protected function _throw($file, $errorType)
    {
        if ($file !== null) {
            $this->_value = $file['name'];
        }

        $this->_error($errorType);
        return false;
    }
}
Upload.php000060400000016247150713635440006517 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/Abstract.php';

/**
 * Validator for the maximum size of a file up to a max of 2GB
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_Upload extends Zend_Validate_Abstract
{
    /**@#+
     * @const string Error constants
     */
    const INI_SIZE       = 'fileUploadErrorIniSize';
    const FORM_SIZE      = 'fileUploadErrorFormSize';
    const PARTIAL        = 'fileUploadErrorPartial';
    const NO_FILE        = 'fileUploadErrorNoFile';
    const NO_TMP_DIR     = 'fileUploadErrorNoTmpDir';
    const CANT_WRITE     = 'fileUploadErrorCantWrite';
    const EXTENSION      = 'fileUploadErrorExtension';
    const ATTACK         = 'fileUploadErrorAttack';
    const FILE_NOT_FOUND = 'fileUploadErrorFileNotFound';
    const UNKNOWN        = 'fileUploadErrorUnknown';
    /**@#-*/

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::INI_SIZE       => "The file '%value%' exceeds the defined ini size",
        self::FORM_SIZE      => "The file '%value%' exceeds the defined form size",
        self::PARTIAL        => "The file '%value%' was only partially uploaded",
        self::NO_FILE        => "The file '%value%' was not uploaded",
        self::NO_TMP_DIR     => "No temporary directory was found for the file '%value%'",
        self::CANT_WRITE     => "The file '%value%' can't be written",
        self::EXTENSION      => "The extension returned an error while uploading the file '%value%'",
        self::ATTACK         => "The file '%value%' was illegal uploaded, possible attack",
        self::FILE_NOT_FOUND => "The file '%value%' was not found",
        self::UNKNOWN        => "Unknown error while uploading the file '%value%'"
    );

    /**
     * Internal array of files
     * @var array
     */
    protected $_files = array();

    /**
     * Sets validator options
     *
     * The array $files must be given in syntax of Zend_File_Transfer to be checked
     * If no files are given the $_FILES array will be used automatically.
     * NOTE: This validator will only work with HTTP POST uploads!
     *
     * @param  array $files Array of files in syntax of Zend_File_Transfer
     * @return void
     */
    public function __construct($files = array())
    {
        $this->setFiles($files);
    }

    /**
     * Returns the array of set files
     *
     * @param  string $files (Optional) The file to return in detail
     * @return array
     * @throws Zend_Validate_Exception If file is not found
     */
    public function getFiles($file = null)
    {
        if ($file !== null) {
            $return = array();
            foreach ($this->_files as $name => $content) {
                if ($name === $file) {
                    $return[$file] = $this->_files[$name];
                }

                if ($content['name'] === $file) {
                    $return[$name] = $this->_files[$name];
                }
            }

            if (count($return) === 0) {
                require_once 'Zend/Validate/Exception.php';
                throw new Zend_Validate_Exception("The file '$file' was not found");
            }

            return $return;
        }

        return $this->_files;
    }

    /**
     * Sets the minimum filesize
     *
     * @param  array $files The files to check in syntax of Zend_File_Transfer
     * @return Zend_Validate_File_Upload Provides a fluent interface
     */
    public function setFiles($files = array())
    {
        if (count($files) === 0) {
            $this->_files = $_FILES;
        } else {
            $this->_files = $files;
        }
        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the file was uploaded without errors
     *
     * @param  string $value Single file to check for upload errors, when giving null the $_FILES array
     *                       from initialization will be used
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        if (array_key_exists($value, $this->_files)) {
            $files[$value] = $this->_files[$value];
        } else {
            foreach ($this->_files as $file => $content) {
                if ($content['name'] === $value) {
                    $files[$file] = $this->_files[$file];
                }

                if ($content['tmp_name'] === $value) {
                    $files[$file] = $this->_files[$file];
                }
            }
        }

        if (empty($files)) {
            return $this->_throw($file, self::FILE_NOT_FOUND);
        }

        foreach ($files as $file => $content) {
            $this->_value = $file;
            switch($content['error']) {
                case 0:
                    if (!is_uploaded_file($content['tmp_name'])) {
                        $this->_throw($file, self::ATTACK);
                    }
                    break;

                case 1:
                    $this->_throw($file, self::INI_SIZE);
                    break;

                case 2:
                    $this->_throw($file, self::FORM_SIZE);
                    break;

                case 3:
                    $this->_throw($file, self::PARTIAL);
                    break;

                case 4:
                    $this->_throw($file, self::NO_FILE);
                    break;

                case 6:
                    $this->_throw($file, self::NO_TMP_DIR);
                    break;

                case 7:
                    $this->_throw($file, self::CANT_WRITE);
                    break;

                case 8:
                    $this->_throw($file, self::EXTENSION);
                    break;

                default:
                    $this->_throw($file, self::UNKNOWN);
                    break;
            }
        }

        if (count($this->_messages) > 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Throws an error of the given type
     *
     * @param  string $file
     * @param  string $errorType
     * @return false
     */
    protected function _throw($file, $errorType)
    {
        if ($file !== null) {
            if (is_array($file) and !empty($file['name'])) {
                $this->_value = $file['name'];
            }
        }

        $this->_error($errorType);
        return false;
    }
}
ExcludeExtension.php000060400000005502150713635440010551 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/File/Extension.php';

/**
 * Validator for the excluding file extensions
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_ExcludeExtension extends Zend_Validate_File_Extension
{
    /**
     * @const string Error constants
     */
    const FALSE_EXTENSION = 'fileExcludeExtensionFalse';
    const NOT_FOUND       = 'fileExcludeExtensionNotFound';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::FALSE_EXTENSION => "The file '%value%' has a false extension",
        self::NOT_FOUND       => "The file '%value%' was not found"
    );

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the fileextension of $value is not included in the
     * set extension list
     *
     * @param  string  $value Real file to check for extension
     * @param  array   $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_FOUND);
        }

        if ($file !== null) {
            $info['extension'] = substr($file['name'], strrpos($file['name'], '.') + 1);
        } else {
            $info = pathinfo($value);
        }

        $extensions = $this->getExtension();

        if ($this->_case and (!in_array($info['extension'], $extensions))) {
            return true;
        } else if (!$this->_case) {
            $found = false;
            foreach ($extensions as $extension) {
                if (strtolower($extension) == strtolower($info['extension'])) {
                    $found = true;
                }
            }

            if (!$found) {
                return true;
            }
        }

        return $this->_throw($file, self::FALSE_EXTENSION);
    }
}
Exists.php000060400000013131150713635440006537 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/Abstract.php';

/**
 * Validator which checks if the file already exists in the directory
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_Exists extends Zend_Validate_Abstract
{
    /**
     * @const string Error constants
     */
    const DOES_NOT_EXIST = 'fileExistsDoesNotExist';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::DOES_NOT_EXIST => "The file '%value%' does not exist"
    );

    /**
     * Internal list of directories
     * @var string
     */
    protected $_directory = '';

    /**
     * @var array Error message template variables
     */
    protected $_messageVariables = array(
        'directory' => '_directory'
    );

    /**
     * Sets validator options
     *
     * @param  string|array $directory
     * @return void
     */
    public function __construct($directory = array())
    {
        if ($directory instanceof Zend_Config) {
            $directory = $directory->toArray();
        } else if (is_string($directory)) {
            $directory = explode(',', $directory);
        } else if (!is_array($directory)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception ('Invalid options to validator provided');
        }

        $this->setDirectory($directory);
    }

    /**
     * Returns the set file directories which are checked
     *
     * @param  boolean $asArray Returns the values as array, when false an concated string is returned
     * @return string
     */
    public function getDirectory($asArray = false)
    {
        $asArray   = (bool) $asArray;
        $directory = (string) $this->_directory;
        if ($asArray) {
            $directory = explode(',', $directory);
        }

        return $directory;
    }

    /**
     * Sets the file directory which will be checked
     *
     * @param  string|array $directory The directories to validate
     * @return Zend_Validate_File_Extension Provides a fluent interface
     */
    public function setDirectory($directory)
    {
        $this->_directory = null;
        $this->addDirectory($directory);
        return $this;
    }

    /**
     * Adds the file directory which will be checked
     *
     * @param  string|array $directory The directory to add for validation
     * @return Zend_Validate_File_Extension Provides a fluent interface
     */
    public function addDirectory($directory)
    {
        $directories = $this->getDirectory(true);

        if (is_string($directory)) {
            $directory = explode(',', $directory);
        } else if (!is_array($directory)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception ('Invalid options to validator provided');
        }

        foreach ($directory as $content) {
            if (empty($content) || !is_string($content)) {
                continue;
            }

            $directories[] = trim($content);
        }
        $directories = array_unique($directories);

        // Sanity check to ensure no empty values
        foreach ($directories as $key => $dir) {
            if (empty($dir)) {
                unset($directories[$key]);
            }
        }

        $this->_directory = implode(',', $directories);

        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the file already exists in the set directories
     *
     * @param  string  $value Real file to check for existance
     * @param  array   $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        $directories = $this->getDirectory(true);
        if (($file !== null) and (!empty($file['destination']))) {
            $directories[] = $file['destination'];
        } else if (!isset($file['name'])) {
            $file['name'] = $value;
        }

        $check = false;
        foreach ($directories as $directory) {
            if (empty($directory)) {
                continue;
            }

            $check = true;
            if (!file_exists($directory . DIRECTORY_SEPARATOR . $file['name'])) {
                return $this->_throw($file, self::DOES_NOT_EXIST);
            }
        }

        if (!$check) {
            return $this->_throw($file, self::DOES_NOT_EXIST);
        }

        return true;
    }

    /**
     * Throws an error of the given type
     *
     * @param  string $file
     * @param  string $errorType
     * @return false
     */
    protected function _throw($file, $errorType)
    {
        if ($file !== null) {
            $this->_value = $file['name'];
        }

        $this->_error($errorType);
        return false;
    }
}
Count.php000060400000016505150713635440006360 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/Abstract.php';

/**
 * Validator for counting all given files
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_Count extends Zend_Validate_Abstract
{
    /**#@+
     * @const string Error constants
     */
    const TOO_MUCH = 'fileCountTooMuch';
    const TOO_LESS = 'fileCountTooLess';
    /**#@-*/

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::TOO_MUCH => "Too much files, maximum '%max%' are allowed but '%count%' are given",
        self::TOO_LESS => "Too less files, minimum '%min%' are expected but '%count%' are given"
    );

    /**
     * @var array Error message template variables
     */
    protected $_messageVariables = array(
        'min'   => '_min',
        'max'   => '_max',
        'count' => '_count'
    );

    /**
     * Minimum file count
     *
     * If null, there is no minimum file count
     *
     * @var integer
     */
    protected $_min;

    /**
     * Maximum file count
     *
     * If null, there is no maximum file count
     *
     * @var integer|null
     */
    protected $_max;

    /**
     * Actual filecount
     *
     * @var integer
     */
    protected $_count;

    /**
     * Internal file array
     * @var array
     */
    protected $_files;

    /**
     * Sets validator options
     *
     * Min limits the file count, when used with max=null it is the maximum file count
     * It also accepts an array with the keys 'min' and 'max'
     *
     * If $options is a integer, it will be used as maximum file count
     * As Array is accepts the following keys:
     * 'min': Minimum filecount
     * 'max': Maximum filecount
     *
     * @param  integer|array $options Options for the adapter
     * @param  integer $max (Deprecated) Maximum value (implies $options is the minimum)
     * @return void
     */
    public function __construct($options)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } elseif (is_string($options) || is_numeric($options)) {
            $options = array('max' => $options);
        } elseif (!is_array($options)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception ('Invalid options to validator provided');
        }

        if (1 < func_num_args()) {
            trigger_error('Multiple arguments are deprecated in favor of an array of named arguments', E_USER_NOTICE);
            $options['min'] = func_get_arg(0);
            $options['max'] = func_get_arg(1);
        }

        if (isset($options['min'])) {
            $this->setMin($options);
        }

        if (isset($options['max'])) {
            $this->setMax($options);
        }
    }

    /**
     * Returns the minimum file count
     *
     * @return integer
     */
    public function getMin()
    {
        return $this->_min;
    }

    /**
     * Sets the minimum file count
     *
     * @param  integer|array $min The minimum file count
     * @return Zend_Validate_File_Size Provides a fluent interface
     * @throws Zend_Validate_Exception When min is greater than max
     */
    public function setMin($min)
    {
        if (is_array($min) and isset($min['min'])) {
            $min = $min['min'];
        }

        if (!is_string($min) and !is_numeric($min)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception ('Invalid options to validator provided');
        }

        $min = (integer) $min;
        if (($this->_max !== null) && ($min > $this->_max)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception("The minimum must be less than or equal to the maximum file count, but $min >"
                                            . " {$this->_max}");
        }

        $this->_min = $min;
        return $this;
    }

    /**
     * Returns the maximum file count
     *
     * @return integer
     */
    public function getMax()
    {
        return $this->_max;
    }

    /**
     * Sets the maximum file count
     *
     * @param  integer|array $max The maximum file count
     * @return Zend_Validate_StringLength Provides a fluent interface
     * @throws Zend_Validate_Exception When max is smaller than min
     */
    public function setMax($max)
    {
        if (is_array($max) and isset($max['max'])) {
            $max = $max['max'];
        }

        if (!is_string($max) and !is_numeric($max)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception ('Invalid options to validator provided');
        }

        $max = (integer) $max;
        if (($this->_min !== null) && ($max < $this->_min)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception("The maximum must be greater than or equal to the minimum file count, but "
                                            . "$max < {$this->_min}");
        }

        $this->_max = $max;
        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the file count of all checked files is at least min and
     * not bigger than max (when max is not null). Attention: When checking with set min you
     * must give all files with the first call, otherwise you will get an false.
     *
     * @param  string|array $value Filenames to check for count
     * @param  array        $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        if (is_string($value)) {
            $value = array($value);
        }

        foreach ($value as $file) {
            if (!isset($this->_files[$file])) {
                $this->_files[$file] = $file;
            }
        }

        $this->_count = count($this->_files);
        if (($this->_max !== null) && ($this->_count > $this->_max)) {
            return $this->_throw($file, self::TOO_MUCH);
        }

        if (($this->_min !== null) && ($this->_count < $this->_min)) {
            return $this->_throw($file, self::TOO_LESS);
        }

        return true;
    }

    /**
     * Throws an error of the given type
     *
     * @param  string $file
     * @param  string $errorType
     * @return false
     */
    protected function _throw($file, $errorType)
    {
        if ($file !== null) {
            $this->_value = $file['name'];
        }

        $this->_error($errorType);
        return false;
    }
}
Md5.php000060400000011662150713635440005714 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_File_Hash
 */
require_once 'Zend/Validate/File/Hash.php';

/**
 * Validator for the md5 hash of given files
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_Md5 extends Zend_Validate_File_Hash
{
    /**
     * @const string Error constants
     */
    const DOES_NOT_MATCH = 'fileMd5DoesNotMatch';
    const NOT_DETECTED   = 'fileMd5NotDetected';
    const NOT_FOUND      = 'fileMd5NotFound';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::DOES_NOT_MATCH => "The file '%value%' does not match the given md5 hashes",
        self::NOT_DETECTED   => "There was no md5 hash detected for the given file",
        self::NOT_FOUND      => "The file '%value%' could not be found"
    );

    /**
     * Hash of the file
     *
     * @var string
     */
    protected $_hash;

    /**
     * Sets validator options
     *
     * $hash is the hash we accept for the file $file
     *
     * @param  string|array $options
     * @return void
     */
    public function __construct($options)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } elseif (is_scalar($options)) {
            $options = array('hash1' => $options);
        } elseif (!is_array($options)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception('Invalid options to validator provided');
        }

        $this->setMd5($options);
    }

    /**
     * Returns all set md5 hashes
     *
     * @return array
     */
    public function getMd5()
    {
        return $this->getHash();
    }

    /**
     * Sets the md5 hash for one or multiple files
     *
     * @param  string|array $options
     * @param  string       $algorithm (Deprecated) Algorithm to use, fixed to md5
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function setHash($options)
    {
        if (!is_array($options)) {
            $options = (array) $options;
        }

        $options['algorithm'] = 'md5';
        parent::setHash($options);
        return $this;
    }

    /**
     * Sets the md5 hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function setMd5($options)
    {
        $this->setHash($options);
        return $this;
    }

    /**
     * Adds the md5 hash for one or multiple files
     *
     * @param  string|array $options
     * @param  string       $algorithm (Depreciated) Algorithm to use, fixed to md5
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function addHash($options)
    {
        if (!is_array($options)) {
            $options = (array) $options;
        }

        $options['algorithm'] = 'md5';
        parent::addHash($options);
        return $this;
    }

    /**
     * Adds the md5 hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function addMd5($options)
    {
        $this->addHash($options);
        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the given file confirms the set hash
     *
     * @param  string $value Filename to check for hash
     * @param  array  $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_FOUND);
        }

        $hashes = array_unique(array_keys($this->_hash));
        $filehash = hash_file('md5', $value);
        if ($filehash === false) {
            return $this->_throw($file, self::NOT_DETECTED);
        }

        foreach($hashes as $hash) {
            if ($filehash === $hash) {
                return true;
            }
        }

        return $this->_throw($file, self::DOES_NOT_MATCH);
    }
}
Sha1.php000060400000011437150713635440006063 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_File_Hash
 */
require_once 'Zend/Validate/File/Hash.php';

/**
 * Validator for the sha1 hash of given files
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_Sha1 extends Zend_Validate_File_Hash
{
    /**
     * @const string Error constants
     */
    const DOES_NOT_MATCH = 'fileSha1DoesNotMatch';
    const NOT_DETECTED   = 'fileSha1NotDetected';
    const NOT_FOUND      = 'fileSha1NotFound';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::DOES_NOT_MATCH => "The file '%value%' does not match the given sha1 hashes",
        self::NOT_DETECTED   => "There was no sha1 hash detected for the given file",
        self::NOT_FOUND      => "The file '%value%' could not be found"
    );

    /**
     * Hash of the file
     *
     * @var string
     */
    protected $_hash;

    /**
     * Sets validator options
     *
     * $hash is the hash we accept for the file $file
     *
     * @param  string|array $options
     * @return void
     */
    public function __construct($options)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } elseif (is_scalar($options)) {
            $options = array('hash1' => $options);
        } elseif (!is_array($options)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception('Invalid options to validator provided');
        }

        $this->setHash($options);
    }

    /**
     * Returns all set sha1 hashes
     *
     * @return array
     */
    public function getSha1()
    {
        return $this->getHash();
    }

    /**
     * Sets the sha1 hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function setHash($options)
    {
        if (!is_array($options)) {
            $options = (array) $options;
        }

        $options['algorithm'] = 'sha1';
        parent::setHash($options);
        return $this;
    }

    /**
     * Sets the sha1 hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function setSha1($options)
    {
        $this->setHash($options);
        return $this;
    }

    /**
     * Adds the sha1 hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function addHash($options)
    {
        if (!is_array($options)) {
            $options = (array) $options;
        }

        $options['algorithm'] = 'sha1';
        parent::addHash($options);
        return $this;
    }

    /**
     * Adds the sha1 hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function addSha1($options)
    {
        $this->addHash($options);
        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the given file confirms the set hash
     *
     * @param  string $value Filename to check for hash
     * @param  array  $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_FOUND);
        }

        $hashes = array_unique(array_keys($this->_hash));
        $filehash = hash_file('sha1', $value);
        if ($filehash === false) {
            return $this->_throw($file, self::NOT_DETECTED);
        }

        foreach ($hashes as $hash) {
            if ($filehash === $hash) {
                return true;
            }
        }

        return $this->_throw($file, self::DOES_NOT_MATCH);
    }
}
FilesSize.php000060400000012417150713635440007163 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_File_Size
 */
require_once 'Zend/Validate/File/Size.php';

/**
 * Validator for the size of all files which will be validated in sum
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_FilesSize extends Zend_Validate_File_Size
{
    /**
     * @const string Error constants
     */
    const TOO_BIG      = 'fileFilesSizeTooBig';
    const TOO_SMALL    = 'fileFilesSizeTooSmall';
    const NOT_READABLE = 'fileFilesSizeNotReadable';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::TOO_BIG      => "All files in sum should have a maximum size of '%max%' but '%size%' were detected",
        self::TOO_SMALL    => "All files in sum should have a minimum size of '%min%' but '%size%' were detected",
        self::NOT_READABLE => "One or more files can not be read"
    );

    /**
     * Internal file array
     *
     * @var array
     */
    protected $_files;

    /**
     * Sets validator options
     *
     * Min limits the used diskspace for all files, when used with max=null it is the maximum filesize
     * It also accepts an array with the keys 'min' and 'max'
     *
     * @param  integer|array $min        Minimum diskspace for all files
     * @param  integer       $max        Maximum diskspace for all files (deprecated)
     * @param  boolean       $bytestring Use bytestring or real size ? (deprecated)
     * @return void
     */
    public function __construct($options)
    {
        $this->_files = array();
        $this->_setSize(0);

        if (1 < func_num_args()) {
            trigger_error('Multiple constructor options are deprecated in favor of a single options array', E_USER_NOTICE);
            if ($options instanceof Zend_Config) {
                $options = $options->toArray();
            } elseif (is_scalar($options)) {
                $options = array('min' => $options);
            } elseif (!is_array($options)) {
                require_once 'Zend/Validate/Exception.php';
                throw new Zend_Validate_Exception('Invalid options to validator provided');
            }

            $argv = func_get_args();
            array_shift($argv);
            $options['max'] = array_shift($argv);
            if (!empty($argv)) {
                $options['bytestring'] = array_shift($argv);
            }
        }

        parent::__construct($options);
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the disk usage of all files is at least min and
     * not bigger than max (when max is not null).
     *
     * @param  string|array $value Real file to check for size
     * @param  array        $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        require_once 'Zend/Loader.php';
        if (is_string($value)) {
            $value = array($value);
        }

        $min  = $this->getMin(true);
        $max  = $this->getMax(true);
        $size = $this->_getSize();
        foreach ($value as $files) {
            // Is file readable ?
            if (!Zend_Loader::isReadable($files)) {
                $this->_throw($file, self::NOT_READABLE);
                continue;
            }

            if (!isset($this->_files[$files])) {
                $this->_files[$files] = $files;
            } else {
                // file already counted... do not count twice
                continue;
            }

            // limited to 2GB files
            $size += @filesize($files);
            $this->_setSize($size);
            if (($max !== null) && ($max < $size)) {
                if ($this->useByteString()) {
                    $this->setMax($this->_toByteString($max));
                    $this->_throw($file, self::TOO_BIG);
                    $this->setMax($max);
                } else {
                    $this->_throw($file, self::TOO_BIG);
                }
            }
        }

        // Check that aggregate files are >= minimum size
        if (($min !== null) && ($size < $min)) {
            if ($this->useByteString()) {
                $this->setMin($this->_toByteString($min));
                $this->_throw($file, self::TOO_SMALL);
                $this->setMin($min);
            } else {
                $this->_throw($file, self::TOO_SMALL);
            }
        }

        if (count($this->_messages) > 0) {
            return false;
        }

        return true;
    }
}
Extension.php000060400000013767150713635440007253 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/Abstract.php';

/**
 * Validator for the file extension of a file
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_Extension extends Zend_Validate_Abstract
{
    /**
     * @const string Error constants
     */
    const FALSE_EXTENSION = 'fileExtensionFalse';
    const NOT_FOUND       = 'fileExtensionNotFound';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::FALSE_EXTENSION => "The file '%value%' has a false extension",
        self::NOT_FOUND       => "The file '%value%' was not found"
    );

    /**
     * Internal list of extensions
     * @var string
     */
    protected $_extension = '';

    /**
     * Validate case sensitive
     *
     * @var boolean
     */
    protected $_case = false;

    /**
     * @var array Error message template variables
     */
    protected $_messageVariables = array(
        'extension' => '_extension'
    );

    /**
     * Sets validator options
     *
     * @param  string|array $extension
     * @param  boolean      $case      If true validation is done case sensitive
     * @return void
     */
    public function __construct($options)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        }

        if (1 < func_num_args()) {
            trigger_error('Multiple arguments to constructor are deprecated in favor of options array', E_USER_NOTICE);
            $case = func_get_arg(1);
            $this->setCase($case);
        }

        if (is_array($options) and isset($options['case'])) {
            $this->setCase($options['case']);
            unset($options['case']);
        }

        $this->setExtension($options);
    }

    /**
     * Returns the case option
     *
     * @return boolean
     */
    public function getCase()
    {
        return $this->_case;
    }

    /**
     * Sets the case to use
     *
     * @param  boolean $case
     * @return Zend_Validate_File_Extension Provides a fluent interface
     */
    public function setCase($case)
    {
        $this->_case = (boolean) $case;
        return $this;
    }

    /**
     * Returns the set file extension
     *
     * @return array
     */
    public function getExtension()
    {
        $extension = explode(',', $this->_extension);

        return $extension;
    }

    /**
     * Sets the file extensions
     *
     * @param  string|array $extension The extensions to validate
     * @return Zend_Validate_File_Extension Provides a fluent interface
     */
    public function setExtension($extension)
    {
        $this->_extension = null;
        $this->addExtension($extension);
        return $this;
    }

    /**
     * Adds the file extensions
     *
     * @param  string|array $extension The extensions to add for validation
     * @return Zend_Validate_File_Extension Provides a fluent interface
     */
    public function addExtension($extension)
    {
        $extensions = $this->getExtension();
        if (is_string($extension)) {
            $extension = explode(',', $extension);
        }

        foreach ($extension as $content) {
            if (empty($content) || !is_string($content)) {
                continue;
            }

            $extensions[] = trim($content);
        }
        $extensions = array_unique($extensions);

        // Sanity check to ensure no empty values
        foreach ($extensions as $key => $ext) {
            if (empty($ext)) {
                unset($extensions[$key]);
            }
        }

        $this->_extension = implode(',', $extensions);

        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the fileextension of $value is included in the
     * set extension list
     *
     * @param  string  $value Real file to check for extension
     * @param  array   $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_FOUND);
        }

        if ($file !== null) {
            $info['extension'] = substr($file['name'], strrpos($file['name'], '.') + 1);
        } else {
            $info = pathinfo($value);
        }

        $extensions = $this->getExtension();

        if ($this->_case && (in_array($info['extension'], $extensions))) {
            return true;
        } else if (!$this->getCase()) {
            foreach ($extensions as $extension) {
                if (strtolower($extension) == strtolower($info['extension'])) {
                    return true;
                }
            }
        }

        return $this->_throw($file, self::FALSE_EXTENSION);
    }

    /**
     * Throws an error of the given type
     *
     * @param  string $file
     * @param  string $errorType
     * @return false
     */
    protected function _throw($file, $errorType)
    {
        if (null !== $file) {
            $this->_value = $file['name'];
        }

        $this->_error($errorType);
        return false;
    }
}
NotExists.php000060400000004654150713635440007232 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_File_Exists
 */
require_once 'Zend/Validate/File/Exists.php';

/**
 * Validator which checks if the destination file does not exist
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_NotExists extends Zend_Validate_File_Exists
{
    /**
     * @const string Error constants
     */
    const DOES_EXIST = 'fileNotExistsDoesExist';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::DOES_EXIST => "The file '%value%' does exist"
    );

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the file does not exist in the set destinations
     *
     * @param  string  $value Real file to check for
     * @param  array   $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        $directories = $this->getDirectory(true);
        if (($file !== null) and (!empty($file['destination']))) {
            $directories[] = $file['destination'];
        } else if (!isset($file['name'])) {
            $file['name'] = $value;
        }

        foreach ($directories as $directory) {
            if (empty($directory)) {
                continue;
            }

            $check = true;
            if (file_exists($directory . DIRECTORY_SEPARATOR . $file['name'])) {
                return $this->_throw($file, self::DOES_EXIST);
            }
        }

        if (!isset($check)) {
            return $this->_throw($file, self::DOES_EXIST);
        }

        return true;
    }
}
Hash.php000060400000012627150713635440006154 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/Abstract.php';

/**
 * Validator for the hash of given files
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_Hash extends Zend_Validate_Abstract
{
    /**
     * @const string Error constants
     */
    const DOES_NOT_MATCH = 'fileHashDoesNotMatch';
    const NOT_DETECTED   = 'fileHashHashNotDetected';
    const NOT_FOUND      = 'fileHashNotFound';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::DOES_NOT_MATCH => "The file '%value%' does not match the given hashes",
        self::NOT_DETECTED   => "There was no hash detected for the given file",
        self::NOT_FOUND      => "The file '%value%' could not be found"
    );

    /**
     * Hash of the file
     *
     * @var string
     */
    protected $_hash;

    /**
     * Sets validator options
     *
     * @param  string|array $options
     * @return void
     */
    public function __construct($options)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } elseif (is_scalar($options)) {
            $options = array('hash1' => $options);
        } elseif (!is_array($options)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception('Invalid options to validator provided');
        }

        if (1 < func_num_args()) {
            trigger_error('Multiple constructor options are deprecated in favor of a single options array', E_USER_NOTICE);
            $options['algorithm'] = func_get_arg(1);
        }

        $this->setHash($options);
    }

    /**
     * Returns the set hash values as array, the hash as key and the algorithm the value
     *
     * @return array
     */
    public function getHash()
    {
        return $this->_hash;
    }

    /**
     * Sets the hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function setHash($options)
    {
        $this->_hash  = null;
        $this->addHash($options);

        return $this;
    }

    /**
     * Adds the hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function addHash($options)
    {
        if (is_string($options)) {
            $options = array($options);
        } else if (!is_array($options)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception("False parameter given");
        }

        $known = hash_algos();
        if (!isset($options['algorithm'])) {
            $algorithm = 'crc32';
        } else {
            $algorithm = $options['algorithm'];
            unset($options['algorithm']);
        }

        if (!in_array($algorithm, $known)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception("Unknown algorithm '{$algorithm}'");
        }

        foreach ($options as $value) {
            $this->_hash[$value] = $algorithm;
        }

        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the given file confirms the set hash
     *
     * @param  string $value Filename to check for hash
     * @param  array  $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_FOUND);
        }

        $algos  = array_unique(array_values($this->_hash));
        $hashes = array_unique(array_keys($this->_hash));
        foreach ($algos as $algorithm) {
            $filehash = hash_file($algorithm, $value);
            if ($filehash === false) {
                return $this->_throw($file, self::NOT_DETECTED);
            }

            foreach($hashes as $hash) {
                if ($filehash === $hash) {
                    return true;
                }
            }
        }

        return $this->_throw($file, self::DOES_NOT_MATCH);
    }

    /**
     * Throws an error of the given type
     *
     * @param  string $file
     * @param  string $errorType
     * @return false
     */
    protected function _throw($file, $errorType)
    {
        if ($file !== null) {
            $this->_value = $file['name'];
        }

        $this->_error($errorType);
        return false;
    }
}
Crc32.php000060400000011361150713635440006137 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_File_Hash
 */
require_once 'Zend/Validate/File/Hash.php';

/**
 * Validator for the crc32 hash of given files
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_Crc32 extends Zend_Validate_File_Hash
{
    /**
     * @const string Error constants
     */
    const DOES_NOT_MATCH = 'fileCrc32DoesNotMatch';
    const NOT_DETECTED   = 'fileCrc32NotDetected';
    const NOT_FOUND      = 'fileCrc32NotFound';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::DOES_NOT_MATCH => "The file '%value%' does not match the given crc32 hashes",
        self::NOT_DETECTED   => "There was no crc32 hash detected for the given file",
        self::NOT_FOUND      => "The file '%value%' could not be found"
    );

    /**
     * Hash of the file
     *
     * @var string
     */
    protected $_hash;

    /**
     * Sets validator options
     *
     * @param  string|array $options
     * @return void
     */
    public function __construct($options)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } elseif (is_scalar($options)) {
            $options = array('hash1' => $options);
        } elseif (!is_array($options)) {
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception('Invalid options to validator provided');
        }

        $this->setCrc32($options);
    }

    /**
     * Returns all set crc32 hashes
     *
     * @return array
     */
    public function getCrc32()
    {
        return $this->getHash();
    }

    /**
     * Sets the crc32 hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function setHash($options)
    {
        if (!is_array($options)) {
            $options = array($options);
        }

        $options['algorithm'] = 'crc32';
        parent::setHash($options);
        return $this;
    }

    /**
     * Sets the crc32 hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function setCrc32($options)
    {
        $this->setHash($options);
        return $this;
    }

    /**
     * Adds the crc32 hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function addHash($options)
    {
        if (!is_array($options)) {
            $options = array($options);
        }

        $options['algorithm'] = 'crc32';
        parent::addHash($options);
        return $this;
    }

    /**
     * Adds the crc32 hash for one or multiple files
     *
     * @param  string|array $options
     * @return Zend_Validate_File_Hash Provides a fluent interface
     */
    public function addCrc32($options)
    {
        $this->addHash($options);
        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the given file confirms the set hash
     *
     * @param  string $value Filename to check for hash
     * @param  array  $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_FOUND);
        }

        $hashes = array_unique(array_keys($this->_hash));
        $filehash = hash_file('crc32', $value);
        if ($filehash === false) {
            return $this->_throw($file, self::NOT_DETECTED);
        }

        foreach($hashes as $hash) {
            if ($filehash === $hash) {
                return true;
            }
        }

        return $this->_throw($file, self::DOES_NOT_MATCH);
    }
}IsCompressed.php000060400000010240150713635440007656 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_File_MimeType
 */
require_once 'Zend/Validate/File/MimeType.php';

/**
 * Validator which checks if the file already exists in the directory
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_IsCompressed extends Zend_Validate_File_MimeType
{
    /**
     * @const string Error constants
     */
    const FALSE_TYPE   = 'fileIsCompressedFalseType';
    const NOT_DETECTED = 'fileIsCompressedNotDetected';
    const NOT_READABLE = 'fileIsCompressedNotReadable';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::FALSE_TYPE   => "The file '%value%' is not compressed, '%type%' detected",
        self::NOT_DETECTED => "The mimetype of file '%value%' has not been detected",
        self::NOT_READABLE => "The file '%value%' can not be read"
    );

    /**
     * Sets validator options
     *
     * @param  string|array $compression
     * @return void
     */
    public function __construct($mimetype = array())
    {
        if (empty($mimetype)) {
            $mimetype = array(
                'application/x-tar',
                'application/x-cpio',
                'application/x-debian-package',
                'application/x-archive',
                'application/x-arc',
                'application/x-arj',
                'application/x-lharc',
                'application/x-lha',
                'application/x-rar',
                'application/zip',
                'application/zoo',
                'application/x-eet',
                'application/x-java-pack200',
                'application/x-compress',
                'application/x-gzip',
                'application/x-bzip2'
            );
        }

        $this->setMimeType($mimetype);
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the file is compression with the set compression types
     *
     * @param  string  $value Real file to check for compression
     * @param  array   $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_READABLE);
        }

        if ($file !== null) {
            if (class_exists('finfo', false) && defined('MAGIC')) {
                $mime = new finfo(FILEINFO_MIME);
                $this->_type = $mime->file($value);
                unset($mime);
            } elseif (function_exists('mime_content_type') && ini_get('mime_magic.magicfile')) {
                $this->_type = mime_content_type($value);
            } else {
                $this->_type = $file['type'];
            }
        }

        if (empty($this->_type)) {
            return $this->_throw($file, self::NOT_DETECTED);
        }

        $compressions = $this->getMimeType(true);
        if (in_array($this->_type, $compressions)) {
            return true;
        }

        $types = explode('/', $this->_type);
        $types = array_merge($types, explode('-', $this->_type));
        foreach ($compressions as $mime) {
            if (in_array($mime, $types)) {
                return true;
            }
        }

        return $this->_throw($file, self::FALSE_TYPE);
    }
}
IsImage.php000060400000010312150713635440006574 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

/**
 * @see Zend_Validate_File_MimeType
 */
require_once 'Zend/Validate/File/MimeType.php';

/**
 * Validator which checks if the file already exists in the directory
 *
 * @category  Zend
 * @package   Zend_Validate
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_File_IsImage extends Zend_Validate_File_MimeType
{
    /**
     * @const string Error constants
     */
    const FALSE_TYPE   = 'fileIsImageFalseType';
    const NOT_DETECTED = 'fileIsImageNotDetected';
    const NOT_READABLE = 'fileIsImageNotReadable';

    /**
     * @var array Error message templates
     */
    protected $_messageTemplates = array(
        self::FALSE_TYPE   => "The file '%value%' is no image, '%type%' detected",
        self::NOT_DETECTED => "The mimetype of file '%value%' has not been detected",
        self::NOT_READABLE => "The file '%value%' can not be read"
    );

    /**
     * Sets validator options
     *
     * @param  string|array $mimetype
     * @return void
     */
    public function __construct($mimetype = array())
    {
        if (empty($mimetype)) {
            $mimetype = array(
                'image/x-quicktime',
                'image/jp2',
                'image/x-xpmi',
                'image/x-portable-bitmap',
                'image/x-portable-greymap',
                'image/x-portable-pixmap',
                'image/x-niff',
                'image/tiff',
                'image/png',
                'image/x-unknown',
                'image/gif',
                'image/x-ms-bmp',
                'application/dicom',
                'image/vnd.adobe.photoshop',
                'image/vnd.djvu',
                'image/x-cpi',
                'image/jpeg',
                'image/x-ico',
                'image/x-coreldraw',
                'image/svg+xml'
            );
        }

        $this->setMimeType($mimetype);
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if the file is compression with the set compression types
     *
     * @param  string  $value Real file to check for compression
     * @param  array   $file  File data from Zend_File_Transfer
     * @return boolean
     */
    public function isValid($value, $file = null)
    {
        // Is file readable ?
        require_once 'Zend/Loader.php';
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_READABLE);
        }

        if ($file !== null) {
            if (class_exists('finfo', false) && defined('MAGIC')) {
                $mime = new finfo(FILEINFO_MIME);
                $this->_type = $mime->file($value);
                unset($mime);
            } elseif (function_exists('mime_content_type') && ini_get('mime_magic.magicfile')) {
                $this->_type = mime_content_type($value);
            } else {
                $this->_type = $file['type'];
            }
        }

        if (empty($this->_type)) {
            return $this->_throw($file, self::NOT_DETECTED);
        }

        $compressions = $this->getMimeType(true);
        if (in_array($this->_type, $compressions)) {
            return true;
        }

        $types = explode('/', $this->_type);
        $types = array_merge($types, explode('-', $this->_type));
        foreach($compressions as $mime) {
            if (in_array($mime, $types)) {
                return true;
            }
        }

        return $this->_throw($file, self::FALSE_TYPE);
    }
}
Filesystem.php000060400000013163150714756120007411 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Storage_File */
require_once 'Zend/Search/Lucene/Storage/File.php';

/** Zend_Search_Lucene_Exception */
require_once 'Zend/Search/Lucene/Exception.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Storage_File_Filesystem extends Zend_Search_Lucene_Storage_File
{
    /**
     * Resource of the open file
     *
     * @var resource
     */
    protected $_fileHandle;


    /**
     * Class constructor.  Open the file.
     *
     * @param string $filename
     * @param string $mode
     */
    public function __construct($filename, $mode='r+b')
    {
        global $php_errormsg;

        if (strpos($mode, 'w') === false  &&  !is_readable($filename)) {
            // opening for reading non-readable file
            throw new Zend_Search_Lucene_Exception('File \'' . $filename . '\' is not readable.');
        }

        $trackErrors = ini_get('track_errors');
        ini_set('track_errors', '1');

        $this->_fileHandle = @fopen($filename, $mode);

        if ($this->_fileHandle === false) {
            ini_set('track_errors', $trackErrors);
            throw new Zend_Search_Lucene_Exception($php_errormsg);
        }

        ini_set('track_errors', $trackErrors);
    }

    /**
     * Sets the file position indicator and advances the file pointer.
     * The new position, measured in bytes from the beginning of the file,
     * is obtained by adding offset to the position specified by whence,
     * whose values are defined as follows:
     * SEEK_SET - Set position equal to offset bytes.
     * SEEK_CUR - Set position to current location plus offset.
     * SEEK_END - Set position to end-of-file plus offset. (To move to
     * a position before the end-of-file, you need to pass a negative value
     * in offset.)
     * SEEK_CUR is the only supported offset type for compound files
     *
     * Upon success, returns 0; otherwise, returns -1
     *
     * @param integer $offset
     * @param integer $whence
     * @return integer
     */
    public function seek($offset, $whence=SEEK_SET)
    {
        return fseek($this->_fileHandle, $offset, $whence);
    }


    /**
     * Get file position.
     *
     * @return integer
     */
    public function tell()
    {
        return ftell($this->_fileHandle);
    }

    /**
     * Flush output.
     *
     * Returns true on success or false on failure.
     *
     * @return boolean
     */
    public function flush()
    {
        return fflush($this->_fileHandle);
    }

    /**
     * Close File object
     */
    public function close()
    {
        if ($this->_fileHandle !== null ) {
            @fclose($this->_fileHandle);
            $this->_fileHandle = null;
        }
    }

    /**
     * Get the size of the already opened file
     *
     * @return integer
     */
    public function size()
    {
        $position = ftell($this->_fileHandle);
        fseek($this->_fileHandle, 0, SEEK_END);
        $size = ftell($this->_fileHandle);
        fseek($this->_fileHandle,$position);

        return $size;
    }

    /**
     * Read a $length bytes from the file and advance the file pointer.
     *
     * @param integer $length
     * @return string
     */
    protected function _fread($length=1)
    {
        if ($length == 0) {
            return '';
        }

        if ($length < 1024) {
            return fread($this->_fileHandle, $length);
        }

        $data = '';
        while ( $length > 0 && ($nextBlock = fread($this->_fileHandle, $length)) != false ) {
            $data .= $nextBlock;
            $length -= strlen($nextBlock);
        }
        return $data;
    }


    /**
     * Writes $length number of bytes (all, if $length===null) to the end
     * of the file.
     *
     * @param string $data
     * @param integer $length
     */
    protected function _fwrite($data, $length=null)
    {
        if ($length === null ) {
            fwrite($this->_fileHandle, $data);
        } else {
            fwrite($this->_fileHandle, $data, $length);
        }
    }

    /**
     * Lock file
     *
     * Lock type may be a LOCK_SH (shared lock) or a LOCK_EX (exclusive lock)
     *
     * @param integer $lockType
     * @param boolean $nonBlockingLock
     * @return boolean
     */
    public function lock($lockType, $nonBlockingLock = false)
    {
        if ($nonBlockingLock) {
            return flock($this->_fileHandle, $lockType | LOCK_NB);
        } else {
            return flock($this->_fileHandle, $lockType);
        }
    }

    /**
     * Unlock file
     *
     * Returns true on success
     *
     * @return boolean
     */
    public function unlock()
    {
        if ($this->_fileHandle !== null ) {
            return flock($this->_fileHandle, LOCK_UN);
        } else {
            return true;
        }
    }
}

Memory.php000060400000037461150714756120006544 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Storage_File */
require_once 'Zend/Search/Lucene/Storage/File.php';

/** Zend_Search_Lucene_Exception */
require_once 'Zend/Search/Lucene/Exception.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Storage_File_Memory extends Zend_Search_Lucene_Storage_File
{
    /**
     * FileData
     *
     * @var string
     */
    private $_data;

    /**
     * File Position
     *
     * @var integer
     */
    private $_position = 0;


    /**
     * Object constractor
     *
     * @param string $data
     */
    public function __construct($data)
    {
        $this->_data = $data;
    }

    /**
     * Reads $length number of bytes at the current position in the
     * file and advances the file pointer.
     *
     * @param integer $length
     * @return string
     */
    protected function _fread($length = 1)
    {
        $returnValue = substr($this->_data, $this->_position, $length);
        $this->_position += $length;
        return $returnValue;
    }


    /**
     * Sets the file position indicator and advances the file pointer.
     * The new position, measured in bytes from the beginning of the file,
     * is obtained by adding offset to the position specified by whence,
     * whose values are defined as follows:
     * SEEK_SET - Set position equal to offset bytes.
     * SEEK_CUR - Set position to current location plus offset.
     * SEEK_END - Set position to end-of-file plus offset. (To move to
     * a position before the end-of-file, you need to pass a negative value
     * in offset.)
     * Upon success, returns 0; otherwise, returns -1
     *
     * @param integer $offset
     * @param integer $whence
     * @return integer
     */
    public function seek($offset, $whence=SEEK_SET)
    {
        switch ($whence) {
            case SEEK_SET:
                $this->_position = $offset;
                break;

            case SEEK_CUR:
                $this->_position += $offset;
                break;

            case SEEK_END:
                $this->_position = strlen($this->_data);
                $this->_position += $offset;
                break;

            default:
                break;
        }
    }

    /**
     * Get file position.
     *
     * @return integer
     */
    public function tell()
    {
        return $this->_position;
    }

    /**
     * Flush output.
     *
     * Returns true on success or false on failure.
     *
     * @return boolean
     */
    public function flush()
    {
        // Do nothing

        return true;
    }

    /**
     * Writes $length number of bytes (all, if $length===null) to the end
     * of the file.
     *
     * @param string $data
     * @param integer $length
     */
    protected function _fwrite($data, $length=null)
    {
        // We do not need to check if file position points to the end of "file".
        // Only append operation is supported now

        if ($length !== null) {
            $this->_data .= substr($data, 0, $length);
        } else {
            $this->_data .= $data;
        }

        $this->_position = strlen($this->_data);
    }

    /**
     * Lock file
     *
     * Lock type may be a LOCK_SH (shared lock) or a LOCK_EX (exclusive lock)
     *
     * @param integer $lockType
     * @return boolean
     */
    public function lock($lockType, $nonBlockinLock = false)
    {
        // Memory files can't be shared
        // do nothing

        return true;
    }

    /**
     * Unlock file
     */
    public function unlock()
    {
        // Memory files can't be shared
        // do nothing
    }

    /**
     * Reads a byte from the current position in the file
     * and advances the file pointer.
     *
     * @return integer
     */
    public function readByte()
    {
        return ord($this->_data[$this->_position++]);
    }

    /**
     * Writes a byte to the end of the file.
     *
     * @param integer $byte
     */
    public function writeByte($byte)
    {
        // We do not need to check if file position points to the end of "file".
        // Only append operation is supported now

        $this->_data .= chr($byte);
        $this->_position = strlen($this->_data);

        return 1;
    }

    /**
     * Read num bytes from the current position in the file
     * and advances the file pointer.
     *
     * @param integer $num
     * @return string
     */
    public function readBytes($num)
    {
        $returnValue = substr($this->_data, $this->_position, $num);
        $this->_position += $num;

        return $returnValue;
    }

    /**
     * Writes num bytes of data (all, if $num===null) to the end
     * of the string.
     *
     * @param string $data
     * @param integer $num
     */
    public function writeBytes($data, $num=null)
    {
        // We do not need to check if file position points to the end of "file".
        // Only append operation is supported now

        if ($num !== null) {
            $this->_data .= substr($data, 0, $num);
        } else {
            $this->_data .= $data;
        }

        $this->_position = strlen($this->_data);
    }


    /**
     * Reads an integer from the current position in the file
     * and advances the file pointer.
     *
     * @return integer
     */
    public function readInt()
    {
        $str = substr($this->_data, $this->_position, 4);
        $this->_position += 4;

        return  ord($str[0]) << 24 |
                ord($str[1]) << 16 |
                ord($str[2]) << 8  |
                ord($str[3]);
    }


    /**
     * Writes an integer to the end of file.
     *
     * @param integer $value
     */
    public function writeInt($value)
    {
        // We do not need to check if file position points to the end of "file".
        // Only append operation is supported now

        settype($value, 'integer');
        $this->_data .= chr($value>>24 & 0xFF) .
                        chr($value>>16 & 0xFF) .
                        chr($value>>8  & 0xFF) .
                        chr($value     & 0xFF);

        $this->_position = strlen($this->_data);
    }


    /**
     * Returns a long integer from the current position in the file
     * and advances the file pointer.
     *
     * @return integer
     * @throws Zend_Search_Lucene_Exception
     */
    public function readLong()
    {
        $str = substr($this->_data, $this->_position, 8);
        $this->_position += 8;

        /**
         * Check, that we work in 64-bit mode.
         * fseek() uses long for offset. Thus, largest index segment file size in 32bit mode is 2Gb
         */
        if (PHP_INT_SIZE > 4) {
            return  ord($str[0]) << 56  |
                    ord($str[1]) << 48  |
                    ord($str[2]) << 40  |
                    ord($str[3]) << 32  |
                    ord($str[4]) << 24  |
                    ord($str[5]) << 16  |
                    ord($str[6]) << 8   |
                    ord($str[7]);
        } else {
            if ((ord($str[0])          != 0) ||
                (ord($str[1])          != 0) ||
                (ord($str[2])          != 0) ||
                (ord($str[3])          != 0) ||
                ((ord($str[0]) & 0x80) != 0)) {
                     throw new Zend_Search_Lucene_Exception('Largest supported segment size (for 32-bit mode) is 2Gb');
                 }

            return  ord($str[4]) << 24  |
                    ord($str[5]) << 16  |
                    ord($str[6]) << 8   |
                    ord($str[7]);
        }
    }

    /**
     * Writes long integer to the end of file
     *
     * @param integer $value
     * @throws Zend_Search_Lucene_Exception
     */
    public function writeLong($value)
    {
        // We do not need to check if file position points to the end of "file".
        // Only append operation is supported now

        /**
         * Check, that we work in 64-bit mode.
         * fseek() and ftell() use long for offset. Thus, largest index segment file size in 32bit mode is 2Gb
         */
        if (PHP_INT_SIZE > 4) {
            settype($value, 'integer');
            $this->_data .= chr($value>>56 & 0xFF) .
                            chr($value>>48 & 0xFF) .
                            chr($value>>40 & 0xFF) .
                            chr($value>>32 & 0xFF) .
                            chr($value>>24 & 0xFF) .
                            chr($value>>16 & 0xFF) .
                            chr($value>>8  & 0xFF) .
                            chr($value     & 0xFF);
        } else {
            if ($value > 0x7FFFFFFF) {
                throw new Zend_Search_Lucene_Exception('Largest supported segment size (for 32-bit mode) is 2Gb');
            }

            $this->_data .= chr(0) . chr(0) . chr(0) . chr(0) .
                            chr($value>>24 & 0xFF) .
                            chr($value>>16 & 0xFF) .
                            chr($value>>8  & 0xFF) .
                            chr($value     & 0xFF);
        }

        $this->_position = strlen($this->_data);
    }



    /**
     * Returns a variable-length integer from the current
     * position in the file and advances the file pointer.
     *
     * @return integer
     */
    public function readVInt()
    {
        $nextByte = ord($this->_data[$this->_position++]);
        $val = $nextByte & 0x7F;

        for ($shift=7; ($nextByte & 0x80) != 0; $shift += 7) {
            $nextByte = ord($this->_data[$this->_position++]);
            $val |= ($nextByte & 0x7F) << $shift;
        }
        return $val;
    }

    /**
     * Writes a variable-length integer to the end of file.
     *
     * @param integer $value
     */
    public function writeVInt($value)
    {
        // We do not need to check if file position points to the end of "file".
        // Only append operation is supported now

        settype($value, 'integer');
        while ($value > 0x7F) {
            $this->_data .= chr( ($value & 0x7F)|0x80 );
            $value >>= 7;
        }
        $this->_data .= chr($value);

        $this->_position = strlen($this->_data);
    }


    /**
     * Reads a string from the current position in the file
     * and advances the file pointer.
     *
     * @return string
     */
    public function readString()
    {
        $strlen = $this->readVInt();
        if ($strlen == 0) {
            return '';
        } else {
            /**
             * This implementation supports only Basic Multilingual Plane
             * (BMP) characters (from 0x0000 to 0xFFFF) and doesn't support
             * "supplementary characters" (characters whose code points are
             * greater than 0xFFFF)
             * Java 2 represents these characters as a pair of char (16-bit)
             * values, the first from the high-surrogates range (0xD800-0xDBFF),
             * the second from the low-surrogates range (0xDC00-0xDFFF). Then
             * they are encoded as usual UTF-8 characters in six bytes.
             * Standard UTF-8 representation uses four bytes for supplementary
             * characters.
             */

            $str_val = substr($this->_data, $this->_position, $strlen);
            $this->_position += $strlen;

            for ($count = 0; $count < $strlen; $count++ ) {
                if (( ord($str_val[$count]) & 0xC0 ) == 0xC0) {
                    $addBytes = 1;
                    if (ord($str_val[$count]) & 0x20 ) {
                        $addBytes++;

                        // Never used. Java2 doesn't encode strings in four bytes
                        if (ord($str_val[$count]) & 0x10 ) {
                            $addBytes++;
                        }
                    }
                    $str_val .= substr($this->_data, $this->_position, $addBytes);
                    $this->_position += $addBytes;
                    $strlen          += $addBytes;

                    // Check for null character. Java2 encodes null character
                    // in two bytes.
                    if (ord($str_val[$count])   == 0xC0 &&
                        ord($str_val[$count+1]) == 0x80   ) {
                        $str_val[$count] = 0;
                        $str_val = substr($str_val,0,$count+1)
                                 . substr($str_val,$count+2);
                    }
                    $count += $addBytes;
                }
            }

            return $str_val;
        }
    }

    /**
     * Writes a string to the end of file.
     *
     * @param string $str
     * @throws Zend_Search_Lucene_Exception
     */
    public function writeString($str)
    {
        /**
         * This implementation supports only Basic Multilingual Plane
         * (BMP) characters (from 0x0000 to 0xFFFF) and doesn't support
         * "supplementary characters" (characters whose code points are
         * greater than 0xFFFF)
         * Java 2 represents these characters as a pair of char (16-bit)
         * values, the first from the high-surrogates range (0xD800-0xDBFF),
         * the second from the low-surrogates range (0xDC00-0xDFFF). Then
         * they are encoded as usual UTF-8 characters in six bytes.
         * Standard UTF-8 representation uses four bytes for supplementary
         * characters.
         */

        // We do not need to check if file position points to the end of "file".
        // Only append operation is supported now

        // convert input to a string before iterating string characters
        settype($str, 'string');

        $chars = $strlen = strlen($str);
        $containNullChars = false;

        for ($count = 0; $count < $strlen; $count++ ) {
            /**
             * String is already in Java 2 representation.
             * We should only calculate actual string length and replace
             * \x00 by \xC0\x80
             */
            if ((ord($str[$count]) & 0xC0) == 0xC0) {
                $addBytes = 1;
                if (ord($str[$count]) & 0x20 ) {
                    $addBytes++;

                    // Never used. Java2 doesn't encode strings in four bytes
                    // and we dont't support non-BMP characters
                    if (ord($str[$count]) & 0x10 ) {
                        $addBytes++;
                    }
                }
                $chars -= $addBytes;

                if (ord($str[$count]) == 0 ) {
                    $containNullChars = true;
                }
                $count += $addBytes;
            }
        }

        if ($chars < 0) {
            throw new Zend_Search_Lucene_Exception('Invalid UTF-8 string');
        }

        $this->writeVInt($chars);
        if ($containNullChars) {
            $this->_data .= str_replace($str, "\x00", "\xC0\x80");

        } else {
            $this->_data .= $str;
        }

        $this->_position = strlen($this->_data);
    }


    /**
     * Reads binary data from the current position in the file
     * and advances the file pointer.
     *
     * @return string
     */
    public function readBinary()
    {
        $length = $this->readVInt();
        $returnValue = substr($this->_data, $this->_position, $length);
        $this->_position += $length;
        return $returnValue;
    }
}