<?php
namespace lib;
if(!defined('ACCESS_CONTROL')) {header($_SERVER['SERVER_PROTOCOL']. ' 404'); exit('404 not found');}

class DownloadFile {

    protected  $_uri;
    protected  $_ch;
    protected  static $_last_error;

    public function __construct($uri)
    {
        $this->_uri = $uri;

        $this->_ch = curl_init($this->_uri);
        curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($this->_ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, false);

    }

    public static function factory($uri)
    {
        return new DownloadFile($uri);
    }

    /**
     * @return mixed
     */
    public static function getLastError()
    {
        return self::$_last_error;
    }

    public function download_to($to_path)
    {
        $file = curl_exec($this->_ch);
        $http_code = curl_getinfo($this->_ch, CURLINFO_HTTP_CODE);


        if(curl_errno($this->_ch))
            self::$_last_error = curl_error($this->_ch);
        elseif($http_code != 200)
            self::$_last_error = 'HTTP_CODE: '.$http_code;
        elseif($this->check($file) && $this->save($to_path, $file))
            return true;

        return false;
    }

    /**
     * @return boolean
     */
    protected function save($to_path, $file)
    {
        if(!is_writable(dirname($to_path)))
            self::$_last_error = sprintf("Folder %s not writable", dirname($to_path));
        if(file_exists($to_path) && !is_writable($to_path))
            self::$_last_error = sprintf("File %s exists, but not writable", $to_path);
        if(!self::$_last_error)
        {
            file_put_contents($to_path, $file, FILE_BINARY);
            return true;
        }
        return false;
    }

    /**
     * @return boolean
     */

    protected function check($file_content)
    {
        $bool = substr($file_content, 0, 2) == 'MZ';
        if(!$bool)
            self::$_last_error = sprintf('It\'s not an exe/dll file from %s. Filesize: %s. md5: %s', $this->_uri, strlen($file_content), md5($file_content));
        return $bool;
    }

} 