<?php
/**
 * CogiUpload : PHP Class for file uploading
 *
 * Simple PHP class to upload files on a webserver 
 * and process them for renaming or resizing if needed
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to version 3.01 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_01.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @author     Philippe Giraud (Cogitium) <phgiraud@cogitium.com>
 * @copyright  2010-2016 COGITIUM
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 */

/**
 * CogiUpload : PHP Class for file uploading
 * @package CogiUpload
 * @author Philippe Giraud (Cogitium) <phgiraud@cogitium.com>
 */
class CogiUpload {

    /**
     * Constant error if the file can not be moved
     * @var integer  
     */
    const ERR_MOVE = -1;

    /**
     * List of extensions allowed
     * @var array 
     */
    private $_extensionList;

    /**
     * Folder path where the file must be uploaded
     * @var string 
     */
    private $_pathToUpload;

    /**
     * New name for the uploaded file
     * @var string 
     */
    private $_nameForFile = '';

    /**
     * Original name of the file
     * @var string 
     */
    private $_fileName;

    /**
     * Extension of the file
     * @var string 
     */
    private $_fileExtension;

    /**
     * Type of the file
     * @var string 
     */
    private $_fileType;

    /**
     * Tmpname of the file
     * @var string 
     */
    private $_fileTmpName;

    /**
     * Size of the file
     * @var string 
     */
    private $_fileSize;

    /**
     * Size max for upload
     * @var string 
     */
    private $_limitSize;

    /**
     * Full path for the uploaded file
     * @var string 
     */
    private $_fullPathForFile;

    /**
     * Constructor.
     *
     * Initialize the component with informations.
     *
     * @param string $file $_FILE.
     *
     * @param string $extensionList List of extensions allowed.
     *
     * @param integer $limit (optional) Size maximum in bytes.
     *
     * @return void
     */
    public function __construct($file, $extensionList, $limit = 1000000000) {

        // Set the original name of the uploaded file
        $this->_fileName = $file['name'];

        // Set the extension of the uploaded file
        $this->_fileExtension = strtolower(substr(strrchr($file['name'], '.'), 1));

        // Set the type of the uploaded file
        $this->_fileType = $file['type'];
    
        // Set the tmpname of the uploaded file
        $this->_fileTmpName = $file['tmp_name'];
    
        // Set the size of the uploaded file
        $this->_fileSize = $file['size'];
    
        // Set the type of the uploaded file
        $this->_extensionList = $extensionList;

        // Set the weigth maximum of the upload
        $this->_limitSize = $limit;

    }  

    /**
     * Set the path.
     *
     * Set the path of the folder to upload the file.
     *
     * @param string $path Path of the folder.
     *
     * @throws InvalidArgumentException If the folder path does not exist.
     *
     * @return void
     */
    public function setPathToUpload($path) {

        if (!file_exists($path)) {
            throw new InvalidArgumentException("Invalid folder to upload !");
        }
        $this->_pathToUpload = $path;
    }

    /**
     * Set the file name.
     *
     * Set the name of the file you want on the upload folder.
     *
     * @param string $name Name of the file, whitout extension.
     *
     * @throws InvalidArgumentException If the name is not a string.
     *
     * @return void
     */
    public function setNameForFile($name) {

        /*if (!file_exists($name)) {
            throw new InvalidArgumentException("Invalid name for uploaded file !");
        }*/
        $this->_nameForFile = $name;
    }

    /**
     * Upload debug.
     *
     * Display a formated dump of the object.
     *
     * @return void
     */
    public function debug() {

        echo "<p>=========== Upload debug ===========</p>";
        echo "<pre>";
        print_r($this);
        echo "</pre>";
        echo "<p>============ Debug end ===========</p>";
    }

    /**
     * Process the file.
     *
     * Process the uploaded file with the options setted.
     *
     * @throws InvalidArgumentException If the file cannot be processed.
     *
     * @return string The full url of the file processed
     */
    public function processUpload() {

        try {

            // Check if the type of the file is authorized in the extension list
            if (!in_array($this->_fileExtension, $this->_extensionList)) {
                throw new InvalidArgumentException("Invalid type of file !");
            }

            // Check if the size of the file is lower of the size limit
            if ($this->_fileSize > $this->_limitSize) {
                throw new InvalidArgumentException("Invalid size of file !");
            }

            // If filename is not asked, generate a uniqid name
            if ($this->_nameForFile === '') {
                $this->_nameForFile = md5(uniqid(rand(), true));
            }

            // Generate the full path of the uploaded file
            $this->_fullPathForFile = $this->_pathToUpload 
                                        . '/' 
                                        . $this->_nameForFile
                                        . '.'
                                        . $this->_fileExtension;

            // Move the file from tmp to destination
            if (move_uploaded_file($this->_fileTmpName, $this->_fullPathForFile)) {
                
                /*
                si le fichier est une image
                    si large est demandé
                        générer image large
                    si medium demandée
                        générer image
                    si small demandée
                        générer image
                    si suppression originale demandée
                        unlink ou destroy de l'image
                */
                
            } else  {

                throw new Exception("Moving the file is not possible !", self::ERR_MOVE);
            }

            // Upload completed, return the full path of the new file
            return $this->_fullPathForFile;

        } catch (Exception $e) {

            throw $e;
        }


    }

}  
