1:  2:  3:  4:  5:  6:  7:  8:  9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 
<?php
namespace Omeka\File;

use Omeka\Stdlib\ErrorStore;
use Omeka\Stdlib\Message;

/**
 * File validator service
 */
class Validator
{
    /**
     * @var array
     */
    protected $mediaTypes;

    /**
     * @var array
     */
    protected $extensions;

    /**
     * @var bool
     */
    protected $disable = false;

    /**
     * @param null|array $mediaTypes Media type whitelist
     * @param null|array $extensions Extension whitelist
     * @param bool $disable Whether to disable validation
     */
    public function __construct(array $mediaTypes = null, array $extensions = null, $disable = false)
    {
        $this->mediaTypes = $mediaTypes;
        $this->extensions = $extensions;
        $this->disable = $disable;
    }

    /**
     * Validate a file.
     *
     * Validates a file against the media type and extension whitelists. Prior
     * to calling this method the file must be saved to `TempFile::$tempPath`
     * and the file's original filename must be saved to `TempFile::$sourceName`.
     *
     * Pass the $errorStore object if an error should raise an API validation
     * error.
     *
     * @param TempFile $tempFile
     * @param null|ErrorStore $errorStore
     * @return bool
     */
    public function validate(TempFile $tempFile, ErrorStore $errorStore = null)
    {
        $isValid = true;
        if ($this->disable) {
            return $isValid;
        }
        if (null !== $this->mediaTypes) {
            $mediaType = $tempFile->getMediaType();
            if (!in_array($mediaType, $this->mediaTypes)) {
                $isValid = false;
                if ($errorStore) {
                    $message = new Message(
                        'Error validating "%s". Cannot store files with the media type "%s".', // @translate
                        $tempFile->getSourceName(), $mediaType
                        );
                    $errorStore->addError('file', $message);
                }
            }
        }
        if (null !== $this->extensions) {
            $extension = $tempFile->getExtension();
            if (!in_array($extension, $this->extensions)) {
                $isValid = false;
                if ($errorStore) {
                    $message = new Message(
                        'Error validating "%s". Cannot store files with the resolved extension "%s".', // @translate
                        $tempFile->getSourceName(), $extension
                        );
                    $errorStore->addError('file', $message);
                }
            }
        }
        return $isValid;
    }
}