<?php

class AssetManager extends BaseManager
{
    public function display_filesize($filesize)
    {
        if (is_numeric($filesize)) {
            $decr = 1024;
            $step = 0;
            $prefix = array('Byte','KB','MB','GB','TB','PB');

            while (($filesize / $decr) > 0.9) {
                $filesize = $filesize / $decr;
                ++$step;
            }

            return round($filesize, 0).' '.$prefix[$step];
        } else {
            return 'NaN';
        }
    }
    protected function rebuildPath($path)
    {
        $dir = dirname($path);
        $folder = substr($path, strlen($dir));
        $dir = realpath($dir);
        $folder = preg_replace('/[^a-z0-9\.\-_]/i', '', $folder);
        if (!$dir or !$folder or $folder === '.') {
            return false;
        }

        return $dir.DIRECTORY_SEPARATOR.$folder;
    }
    protected function is_sub_dir($path, $parent_folder)
    {
        $rebuild_path = $this->rebuildPath($path);
        $rebuild_parent_folder = $this->rebuildPath($parent_folder);
        if (!$rebuild_parent_folder || !$rebuild_path) {
            return false;
        }

        $parent = rtrim($rebuild_parent_folder, DIRECTORY_SEPARATOR);
        $sub = rtrim($rebuild_path, DIRECTORY_SEPARATOR);
        $parent = explode(DIRECTORY_SEPARATOR, $parent);
        $sub = explode(DIRECTORY_SEPARATOR, $sub);
        for ($i = 0;$i < count($parent);++$i) {
            if (sizeof($sub) <= $i || $parent[$i] != $sub[$i]) {
                //echo $parent[$i];
                return false;
            }
        }

        return true;
    }
    protected function checkUploadable($folder_size, $upload_size)
    {
        $max_upload_size = Yii::app()->site->model->getMaxUploadSize();

        return $folder_size + $upload_size <= $max_upload_size;
    }
    private function filesize_r($path)
    {
        if (!file_exists($path)) {
            return 0;
        }
        if (is_file($path)) {
            return filesize($path);
        }
        $ret = 0;
        foreach (glob($path.'/*') as $fn) {
            $ret += $this->filesize_r($fn);
        }

        return $ret;
    }
    public function getAssetFolderSize()
    {
        $pageObj = Yii::app()->site->model;

        return $pageObj->getUploadSize();
        $upload_directory = isset(Yii::app()->params['website_upload_directory']) ? Yii::app()->params['website_upload_directory'] : 'assets';
        $dir = $pageObj->model->getPhysicalLocation().DIRECTORY_SEPARATOR.$upload_directory;

        return $this->filesize_r($dir);
    }
    public function actiongetUploadSize()
    {
        $this->ajaxSuccess($this->getAssetFolderSize());
    }
    private function deleteDir($dirPath)
    {
        if (!is_dir($dirPath)) {
            throw new InvalidArgumentException("$dirPath must be a directory");
        }
        $size = 0;
        if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
            $dirPath .= '/';
        }
        $files = glob($dirPath.'*', GLOB_MARK);
        foreach ($files as $file) {
            if (is_dir($file)) {
                $size += self::deleteDir($file);
            } else {
                $size += filesize($file);
                unlink($file);
            }
        }
        rmdir($dirPath);

        return $size;
    }
    protected function full_copy($source, $target, $copy = true)
    {
        $size = 0;
        if (is_dir($source)) {
            if (!file_exists($target)) {
                @mkdir($target);
            }
            $d = dir($source);
            while (false !== ($entry = $d->read())) {
                if ($entry == '.' || $entry == '..') {
                    continue;
                }
                $Entry = $source.DIRECTORY_SEPARATOR.$entry;
                if (is_dir($Entry)) {
                    $size += $this->full_copy($Entry, $target.DIRECTORY_SEPARATOR.$entry, $copy);
                    continue;
                }
                $size += filesize($Entry);
                copy($Entry, $target.DIRECTORY_SEPARATOR.$entry);
                if (!$copy) {
                    @unlink($Entry);
                }
            }
            $d->close();
            if (!$copy) {
                @rmdir($source);
            }
        } else {
            $size += filesize($source);
            copy($source, $target);
            if (!$copy) {
                @unlink($source);
            }
        }

        return $size;
    }
    public function actionnewFolder()
    {
        $pageObj = Yii::app()->site->model;
        $upload_directory = isset(Yii::app()->params['website_upload_directory']) ? Yii::app()->params['website_upload_directory'] : 'assets';
        $dir = $pageObj->getPhysicalLocation().DIRECTORY_SEPARATOR.$upload_directory;
        if (isset($_POST['folder'])) {
            $dir = $dir.DIRECTORY_SEPARATOR.$_POST['folder'];
        }
        $name = $_POST['name'];
        $name = preg_replace('/[^a-z0-9\.\-_]/i', '', $name);
        $newdir = $dir.DIRECTORY_SEPARATOR.$name;
        if (!file_exists($newdir)) {
            @mkdir($newdir);
            $this->ajaxSuccess(1);
        } else {
            $this->ajaxError(1);
        }
    }
    protected function getFileInfo($file)
    {
        //	$file = str_replace('\\','/',$file);
        //$file = str_replace('//','/',$file);
        $file_name = basename($file);
        $name = substr($file_name, 0, strripos($file_name, '.'));
        $file_ext = substr($file_name, strripos($file_name, '.') + 1);
        $document_root = Yii::getPathofAlias('application_root');
        $relative_url = str_replace($document_root, '', $file);
        $relative_url = str_replace('\\', '/', $relative_url);
        $relative_url = str_replace('//', '/', $relative_url);
        $full_url = ''.$relative_url;
        $filesize = filesize($file);
        $thumbnail = $full_url;

        return array('full_path' => $file,'file_name' => $file_name, 'filesize' => $filesize,'size' => $this->display_filesize($filesize),'name' => $name, 'extension' => $file_ext, 'full_url' => ($full_url), 'url' => urlencode($full_url), 'thumbnail' => $thumbnail);
    }
    protected function getFolderInfo($path, $relative_parent_dir)
    {
        $name = basename($path);
        $document_root = Yii::getPathofAlias('application_root');
        $relative_url = str_replace($relative_parent_dir, '', $path);
        $relative_url = str_replace('\\', '/', $relative_url);
        $relative_url = str_replace('//', '/', $relative_url);

        return array('full_path' => $path,'name' => $name, 'path' => ($relative_url));
    }
    public function actionDeleteitems()
    {
        $size = 0;
        $folder_size = Yii::app()->site->model->getUploadSize();

        if (isset($_POST['folders'])) {
            $folders = $_POST['folders'];
            foreach ($folders as $folder) {
                $full_path = $folder['full_path'];
                $size += $this->deleteDir($full_path);
            }
        }
        if (isset($_POST['files'])) {
            $files = $_POST['files'];
            foreach ($files as $file) {
                $full_path = $file['full_path'];
                $size += filesize($full_path);
                unlink($full_path);
            }
        }
        Yii::app()->site->model->updateUploadSize($folder_size - $size);
        $this->ajaxSuccess($folder_size - $size);
    }
    public function getFolderContent($p_dir)
    {
        $extensions = array('*');
        if (isset($_REQUEST['extensions'])) {
            $extensions = array();
            foreach ($_REQUEST['extensions'] as $extension) {
                $extensions[] = trim($extension, '.');
            }
        }
        $relative_path = '';
        $dir = $p_dir;
        if (isset($_POST['folder'])) {
            $dir = $dir.DIRECTORY_SEPARATOR.$_POST['folder'];
            $relative_path = $_POST['folder'];
        }
        $images = array();
        $total = 0;
        $gfld = 1;
        if (isset($_POST['gfld']) && $_POST['gfld']) {
            //$gfld = $_POST['gfld'];
        }
        if ($gfld == 1) {
            $dirlist = array();
        }
        if (is_dir($dir)) {
            if ($dh = opendir($dir)) {
                while (($file = readdir($dh)) !== false) {
                    if (substr($file, 0, 1) !== '.') {
                        if (is_dir($dir.DIRECTORY_SEPARATOR.$file)) {
                            if ($gfld == 1) {
                                $dirlist[] = $this->getFolderInfo($dir.DIRECTORY_SEPARATOR.$file, $p_dir);
                            }
                        } else {
                            $name = substr($file, 0, strripos($file, '.'));
                            $file_ext = substr($file, strripos($file, '.') + 1);
                            $flag = false;
                            foreach ($extensions as $ext) {
                                if ($file_ext == $ext) {
                                    $flag = true;
                                    break;
                                }
                            }
                            if (!$flag) {
                                continue;
                            }
                            ++$total;

                            $images[] = $this->getFileInfo($dir.DIRECTORY_SEPARATOR.$file);
                        }
                    }
                }
                closedir($dh);
            }
        }
        $rs = array('files' => $images);
        if (isset($dirlist)) {
            $rs['folders'] = $dirlist;
        }
        $rs['dir'] = $_SERVER['DOCUMENT_ROOT'];
        $this->ajaxSuccess($rs);
    }

    public function actionupload()
    {
        Yii::import('application.components.image.ImageHelper');
        $filenames = array();
        header('Content-type: text/plain; charset=UTF-8');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');
        $targetDir = sys_get_temp_dir().DIRECTORY_SEPARATOR.'plupload';
        $cleanupTargetDir = false; // Remove old files
        $maxFileAge = 60 * 60; // Temp file age in seconds
        @set_time_limit(5 * 60);
        $chunk = isset($_REQUEST['chunk']) ? $_REQUEST['chunk'] : 0;
        $chunks = isset($_REQUEST['chunks']) ? $_REQUEST['chunks'] : 0;
        $fileName = isset($_REQUEST['name']) ? $_REQUEST['name'] : '';
        $user_id = Yii::app()->user->getId();
        $upload_directory = isset(Yii::app()->params['website_upload_directory']) ? Yii::app()->params['website_upload_directory'] : 'assets';
        $file_icon_directory = isset(Yii::app()->params['file_icon_directory']) ? Yii::app()->params['file_icon_directory'] : '';
        $fileName = preg_replace('/[^\w\._\s]+/', '', $fileName);
        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }
        if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
            while (($file = readdir($dir)) !== false) {
                $filePath = $targetDir.DIRECTORY_SEPARATOR.$file;
                if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge)) {
                    @unlink($filePath);
                }
            }
            closedir($dir);
        } else {
            throw new CHttpException(500, Yii::t('app', "Can't open temporary directory."));
        }
        if (isset($_SERVER['HTTP_CONTENT_TYPE'])) {
            $contentType = $_SERVER['HTTP_CONTENT_TYPE'];
        }

        if (isset($_SERVER['CONTENT_TYPE'])) {
            $contentType = $_SERVER['CONTENT_TYPE'];
        }
        if (strpos($contentType, 'multipart') !== false) {
            if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                $out = fopen($targetDir.DIRECTORY_SEPARATOR.$fileName, $chunk == 0 ? 'wb' : 'ab');
                if ($out) {
                    // Read binary input stream and append it to temp file
                  $in = fopen($_FILES['file']['tmp_name'], 'rb');
                    if ($in) {
                        while ($buff = fread($in, 4096)) {
                            fwrite($out, $buff);
                        }
                    } else {
                        throw new CHttpException(500, Yii::t('app', "Can't open input stream."));
                    }
                    fclose($out);
                    @unlink($_FILES['file']['tmp_name']);
                } else {
                    throw new CHttpException(500, Yii::t('app', "Can't open output stream."));
                }
            } else {
                throw new CHttpException(500, Yii::t('app', "Can't move uploaded file."));
            }
        } else {
            // Open temp file
              $out = fopen($targetDir.DIRECTORY_SEPARATOR.$fileName, $chunk == 0 ? 'wb' : 'ab');
            if ($out) {
                // Read binary input stream and append it to temp file
                 $in = fopen('php://input', 'rb');
                if ($in) {
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                } else {
                    throw new CHttpException(500, Yii::t('app', "Can't open input stream."));
                }
                fclose($out);
            } else {
                throw new CHttpException(500, Yii::t('app', "Can't open output stream."));
            }
        }
          //process the file
         $file_id = substr($fileName, 0, strripos($fileName, '.'));
        $filename = $_FILES['file']['name'];
        $file_ext = substr($filename, strripos($filename, '.'));
        $file_size = $_FILES['file']['size'];
        try {
            $dimension = getimagesize($targetDir.DIRECTORY_SEPARATOR.$fileName);
        } catch (Exception $e) {
            $dimension = array(0,0);
        }
        $file_size_str = $this->display_filesize($_FILES['file']['size']);
        $file_type = $_FILES['file']['type'];
        $file_error = $_FILES['file']['error'];

        if (intval($chunk) + 1 >= intval($chunks)) {
            $originalname = $fileName;
            if (isset($_SERVER['HTTP_CONTENT_DISPOSITION'])) {
                $arr = array();
                preg_match('@^attachment; filename="([^"]+)"@', $_SERVER['HTTP_CONTENT_DISPOSITION'], $arr);
                if (isset($arr[1])) {
                    $originalname = $arr[1];
                }
            }
            $temppath = $targetDir.DIRECTORY_SEPARATOR.$fileName;

            $file_id_p = $file_id;
            if (isset($_GET['f'])) {
                $upload_directory = $upload_directory.DIRECTORY_SEPARATOR.$_GET['f'];
            }
            $new_file_name = $file_id;
            if (isset($_GET['n'])) {
                $new_file_name = $_GET['n'];
            }
            if (isset($_GET['overwrite']) && $_GET['overwrite'] == 1) {
                $index = 1;
                while (Yii::app()->site->model->checkFileExist($upload_directory, $new_file_name, $file_ext)) {
                    $new_file_name = $new_file_name.'_'.$index;
                    ++$index;
                }
            }

            $dest = Yii::app()->site->model->getFilePath($upload_directory, $new_file_name, $file_ext);
            $folder_size = Yii::app()->site->model->getUploadSize();
            $rs = $this->checkUploadable($folder_size, $file_size);
            if (!$rs) {
                $this->ajaxError('Your upload execed. '.$folder_size);

                return;
            }
            @copy($temppath, $dest);
            $ret = $this->getFileInfo($dest);
            $ret['result'] = 1;
        }
          // Return response
          Yii::app()->site->model->updateUploadSize($folder_size + $file_size);
        die(json_encode($ret));
    }
    public function actiongetAssetList()
    {
        $pageObj = Yii::app()->site;
        $upload_directory = isset(Yii::app()->params['website_upload_directory']) ? Yii::app()->params['website_upload_directory'] : 'assets';
        $dir = $pageObj->model->getPhysicalLocation().DIRECTORY_SEPARATOR.$upload_directory;

        $this->getFolderContent($dir);
    }
    public function actiongetLiddst()
    {
        $this->actiongetAssetList();
    }
    public function actiongetBackgroundList()
    {
        $background_directory = isset(Yii::app()->params['background_directory']) ? Yii::app()->params['background_directory'] : 'background_images';
        $basePath = Yii::getPathofAlias('application_root');
        $basePath = rtrim($basePath, '/');
        $dir = $basePath.DIRECTORY_SEPARATOR.$background_directory;
        $this->getFolderContent($dir);
    }
    public function actiongetLibraryList()
    {
        $upload_directory = isset(Yii::app()->params['upload_directory']) ? Yii::app()->params['upload_directory'] : 'upload';
        $basePath = Yii::getPathofAlias('application_root');
        $dir = $basePath.DIRECTORY_SEPARATOR.$upload_directory;
        $relative_path = '';
        $this->getFolderContent($dir);
    }
}
