<?php

class attachment
{

    var $contentid;
    var $module;
    var $catid;
    var $attachments;
    var $field;
    var $imageexts = array('xls,xlsx');
    var $alowexts = array();
    var $uploadedfiles = array();
    var $downloadedfiles = array();
    var $error;
    var $upload_root;
    var $siteid;
    var $site = array();
    var $upload_dir;
    var $uploadeds;

    function __construct($catid = 0, $upload_dir = 'data/')
    {
        $this->catid = intval($catid);
//	$this->siteid = intval($siteid) == 0 ? 1 : intval($siteid);
//	$this->module = $module ? $module : 'content';
//	pc_base::load_sys_func('dir');
//	pc_base::load_sys_class('image', '', '0');
        $this->upload_root = Doo::conf()->SITE_PATH;
        $this->upload_func = 'move_uploaded_file';
//	$this->upload_func = 'copy';
        $this->upload_dir = $upload_dir;
    }

    function setUploadDir($upload_dir = 'files/')
    {
        $this->upload_dir = $upload_dir;
    }

    /**
     * 附件上传方法
     * @param $field 上传字段
     * @param $alowexts 允许上传类型
     * @param $maxsize 最大上传大小
     * @param $overwrite 是否覆盖原有文件
     * @param $thumb_setting 缩略图设置
     * @param $watermark_enable  是否添加水印
     */
    function upload($field, $alowexts = '', $maxsize = 0, $overwrite = 0, $thumb_setting = array(), $watermark_enable = 1, $ip = '')
    {
        if (!isset($_FILES[$field])) {
            $this->error = UPLOAD_ERR_OK;
            return false;
        }
        $this->field = $field;
        $this->savepath = $this->upload_root . $this->upload_dir . date('Y/md/');
        $this->alowexts = $alowexts;
        $this->maxsize = $maxsize;
        $this->overwrite = $overwrite;
        $uploadfiles = array();
        $description = isset($GLOBALS[$field . '_description']) ? $GLOBALS[$field . '_description'] : array();
//	$this->uploads = count($_FILES[$field]['error']);
//	if ($this->uploads >= 2) {
        if (is_array($_FILES[$field]['error'])) {
            $this->uploads = count($_FILES[$field]['error']);
            foreach ($_FILES[$field]['error'] as $key => $error) {
                if ($error === UPLOAD_ERR_NO_FILE)
                    continue;
                if ($error !== UPLOAD_ERR_OK) {
                    $this->error = $error;
                    return false;
                }
                $uploadfiles[$key] = array('tmp_name' => $_FILES[$field]['tmp_name'][$key], 'name' => $_FILES[$field]['name'][$key], 'type' => $_FILES[$field]['type'][$key], 'size' => $_FILES[$field]['size'][$key], 'error' => $_FILES[$field]['error'][$key], 'description' => $description[$key]);
            }
        } else {
            $this->uploads = 1;
            if (!$description)
                $description = '';
            $uploadfiles[0] = array('tmp_name' => $_FILES[$field]['tmp_name'], 'name' => $_FILES[$field]['name'], 'type' => $_FILES[$field]['type'], 'size' => $_FILES[$field]['size'], 'error' => $_FILES[$field]['error'], 'description' => $description);
        }
        if (!$this->dir_create($this->savepath)) {
            $this->error = '8';
            return false;
        }
        if (!is_dir($this->savepath)) {
            $this->error = '8';
            return false;
        }
        @chmod($this->savepath, 0777);

        if (!is_writeable($this->savepath)) {
            $this->error = '9';
            return false;
        }
//	if (!$this->is_allow_upload()) {
//	    $this->error = '13';
//	    return false;
//	}
        $aids = array();
        foreach ($uploadfiles as $k => $file) {
            $fileext = $this->fileext($file['name']);
            if ($file['error'] != 0) {
                $this->error = $file['error'];
                return false;
            }
//	    if (!preg_match("/^(" . $this->alowexts . ")$/", $fileext)) {
//		$this->error = '10';
//		return false;
//	    }
            if ($this->maxsize && $file['size'] > $this->maxsize) {
                $this->error = '11';
                return false;
            }
            if (!$this->isuploadedfile($file['tmp_name'])) {
                $this->error = '12';
                return false;
            }
            $temp_filename = $this->getname($fileext);
            $savefile = $this->savepath . $temp_filename;

            $savefile = preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(\.|$)/i", "_\\1\\2", $savefile);
            $filepath = preg_replace($this->new_addslashes("|^" . $this->upload_root . "|"), "", $savefile);
            if (!$this->overwrite && file_exists($savefile))
                continue;
            $upload_func = $this->upload_func;
            if ($upload_func($file['tmp_name'], $savefile)) {
//		$this->uploadeds++;
                @chmod($savefile, 0777);
                @unlink($file['tmp_name']);
//		$file['name'] = iconv("utf-8", 'sdsdf', $file['name']);
                $uploadedfile = array('filename' => $file['name'], 'filepath' => $filepath, 'filesize' => $file['size'], 'fileext' => $fileext, 'uploadip' => $ip, 'uploadtime' => time());
//                error_log(var_export($uploadedfile, TRUE), 3, '/opt/WebRoot/wenku/data/upArray.txt');
//		$thumb_enable = is_array($thumb_setting) && ($thumb_setting[0] > 0 || $thumb_setting[1] > 0 ) ? 1 : 0;
//		$image = new image($thumb_enable, $this->siteid);
//		if ($thumb_enable) {
//		    $image->thumb($savefile, '', $thumb_setting[0], $thumb_setting[1]);
//		}
//		if ($watermark_enable) {
//		    $image->watermark($savefile, $savefile);
//		}
//		$aids[] = $this->add($uploadedfile);
            }
        }
        return $uploadedfile;
    }

    /**
     * 附件上传方法
     * @param $field 上传字段
     * @param $alowexts 允许上传类型
     * @param $maxsize 最大上传大小
     * @param $overwrite 是否覆盖原有文件
     */
    function uploadMut($field, $alowexts = '', $maxsize = 0, $overwrite = 0)
    {
        if (!isset($_FILES[$field])) {
            $this->error = UPLOAD_ERR_OK;
            return false;
        }
        $this->field = $field;
        $this->savepath = $this->upload_root . $this->upload_dir . date('Y/md/');
        $this->alowexts = $alowexts;
        $this->maxsize = $maxsize;
        $this->overwrite = $overwrite;
        $uploadfiles = array();
        $description = isset($GLOBALS[$field . '_description']) ? $GLOBALS[$field . '_description'] : array();
        if (is_array($_FILES[$field]['error'])) {
            $this->uploads = count($_FILES[$field]['error']);
            foreach ($_FILES[$field]['error'] as $key => $error) {
                if ($error === UPLOAD_ERR_NO_FILE)
                    continue;
                if ($error !== UPLOAD_ERR_OK) {
                    $this->error = $error;
                    return false;
                }
                $uploadfiles[$key] = array('tmp_name' => $_FILES[$field]['tmp_name'][$key], 'name' => $_FILES[$field]['name'][$key], 'type' => $_FILES[$field]['type'][$key], 'size' => $_FILES[$field]['size'][$key], 'error' => $_FILES[$field]['error'][$key]);
            }
        } else {
            $this->uploads = 1;
            if (!$description)
                $description = '';
            $uploadfiles[0] = array('tmp_name' => $_FILES[$field]['tmp_name'], 'name' => $_FILES[$field]['name'], 'type' => $_FILES[$field]['type'], 'size' => $_FILES[$field]['size'], 'error' => $_FILES[$field]['error'], 'description' => $description);
        }
        if (!$this->dir_create($this->savepath)) {
            $this->error = '8';
            return false;
        }
        if (!is_dir($this->savepath)) {
            $this->error = '8';
            return false;
        }
//	@chmod($this->savepath, 0777);

        if (!is_writeable($this->savepath)) {
            $this->error = '9';
            return false;
        }
        $aids = array();
        foreach ($uploadfiles as $k => $file) {
            $fileext = $this->fileext2($file['name']);
            if ($file['error'] != 0) {
                $this->error = $file['error'];
//		echo $this->error;
                return false;
            }
//	    if (!preg_match("/^(" . $this->alowexts . ")$/", $fileext)) {
//		$this->error = '10';
//		echo $this->error;
//		return false;
//	    }
            if ($this->maxsize && $file['size'] > $this->maxsize) {
                $this->error = '11';
//		echo $this->error;
                return false;
            }
            if (!$this->isuploadedfile($file['tmp_name'])) {
                $this->error = '12';
//		echo $this->error;
                return false;
            }
            $temp_filename = $this->getname($fileext);
            $savefile = $this->savepath . $temp_filename;
            $savefile = preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(\.|$)/i", "_\\1\\2", $savefile);
            $filepath = preg_replace($this->new_addslashes("|^" . $this->upload_root . "|"), "", $savefile);
            if (!$this->overwrite && file_exists($savefile))
                continue;
            $upload_func = $this->upload_func;
            if (@$upload_func($file['tmp_name'], $savefile)) {
                $this->uploadeds++;
                @chmod($savefile, 0777);
                @unlink($file['tmp_name']);
                $file['name'] = $this->safe_replace($file['name']);
                $uploadedfile = array('filename' => trim($file['name']), 'filepath' => $filepath, 'filesize' => $file['size'], 'fileext' => $fileext);
                $aids[] = $uploadedfile;
            }
        }
        return $aids;
    }

    /**
     * 取得文件扩展
     *
     * @param $filename 文件名
     * @return 扩展名
     */
    function fileext2($filename)
    {
        return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
    }

    /**
     * 安全过滤函数
     *
     * @param $string
     * @return string
     */
    function safe_replace($string)
    {
        $string = str_replace('%20', '', $string);
        $string = str_replace('%27', '', $string);
        $string = str_replace('%2527', '', $string);
        $string = str_replace('*', '', $string);
        $string = str_replace('"', '&quot;', $string);
        $string = str_replace("'", '', $string);
        $string = str_replace('"', '', $string);
        $string = str_replace(';', '', $string);
        $string = str_replace('<', '&lt;', $string);
        $string = str_replace('>', '&gt;', $string);
        $string = str_replace("{", '', $string);
        $string = str_replace('}', '', $string);
        return $string;
    }

    /**
     * 返回经addslashes处理过的字符串或数组
     * @param $string 需要处理的字符串或数组
     * @return mixed
     */
    function new_addslashes($string)
    {
        if (!is_array($string))
            return addslashes($string);
        foreach ($string as $key => $val)
            $string[$key] = new_addslashes($val);
        return $string;
    }

    /**
     * 取得文件扩展
     *
     * @param $filename 文件名
     * @return 扩展名
     */
    function fileext($filename)
    {
        $pathinfo = pathinfo($filename);
//	return strtolower(trim(substr(mb_strrchr($filename, '.'), 1, 10)));
        return $pathinfo['extension'];
    }

    /**
     * 创建目录
     *
     * @param    string $path 路径
     * @param    string $mode 属性
     * @return    string    如果已经存在则返回true，否则为flase
     */
    function dir_create($path, $mode = 0777)
    {
        if (is_dir($path))
            return TRUE;
//	$ftp_enable = 0;
        $path = $this->dir_path($path);
        $parent = dirname($path);
        if (!is_dir($parent))
            @mkdir($parent, 0777, true);
        @mkdir($path, 0777, true);
//	$temp = explode('/', $path);
//	$cur_dir = '';
//	$max = count($temp) - 1;
//	for ($i = 0; $i < $max; $i++) {
//	    if (empty($temp[$i]))
//		continue;
//	    $cur_dir .= $temp[$i] . '/';
//	    if (@is_dir($cur_dir))
//		continue;
////	    error_log($cur_dir, 3, '/opt/WebRoot/wenku/data/4mkdir.txt');
//	    @mkdir($cur_dir, 0777, true);
//	    @chmod($cur_dir, 0777);
//	}
        return is_dir($path);
    }

    /**
     * 转化 \ 为 /
     *
     * @param    string $path 路径
     * @return    string    路径
     */
    function dir_path($path)
    {
        $path = str_replace('\\', '/', $path);
        if (substr($path, -1) != '/')
            $path = $path . '/';
        return $path;
    }

    /**
     * 附件下载
     * Enter description here ...
     * @param $field 预留字段
     * @param $value 传入下载内容
     * @param $watermark 是否加入水印
     * @param $ext 下载扩展名
     * @param $absurl 绝对路径
     * @param $basehref
     */
    function download($field, $value, $watermark = '0', $ext = 'gif|jpg|jpeg|bmp|png', $absurl = '', $basehref = '')
    {
        global $image_d;
        $this->att_db = pc_base::load_model('attachment_model');
        $upload_url = pc_base::load_config('system', 'upload_url');
        $this->field = $field;
        $dir = date('Y/md/');
        $uploadpath = $upload_url . $dir;
        $uploaddir = $this->upload_root . $dir;
        $string = new_stripslashes($value);
        if (!preg_match_all("/(href|src)=([\"|']?)([^ \"'>]+\.($ext))\\2/i", $string, $matches))
            return $value;
        $remotefileurls = array();
        foreach ($matches[3] as $matche) {
            if (strpos($matche, '://') === false)
                continue;
            dir_create($uploaddir);
            $remotefileurls[$matche] = $this->fillurl($matche, $absurl, $basehref);
        }
        unset($matches, $string);
        $remotefileurls = array_unique($remotefileurls);
        $oldpath = $newpath = array();
        foreach ($remotefileurls as $k => $file) {
            if (strpos($file, '://') === false || strpos($file, $upload_url) !== false)
                continue;
            $filename = fileext($file);
            $file_name = basename($file);
            $filename = $this->getname($filename);

            $newfile = $uploaddir . $filename;
            $upload_func = $this->upload_func;
            if ($upload_func($file, $newfile)) {
                $oldpath[] = $k;
                $GLOBALS['downloadfiles'][] = $newpath[] = $uploadpath . $filename;
                @chmod($newfile, 0777);
                $fileext = fileext($filename);
                if ($watermark) {
                    watermark($newfile, $newfile, $this->siteid);
                }
                $filepath = $dir . $filename;
                $downloadedfile = array('filename' => $filename, 'filepath' => $filepath, 'filesize' => filesize($newfile), 'fileext' => $fileext);
                $aid = $this->add($downloadedfile);
                $this->downloadedfiles[$aid] = $filepath;
            }
        }
        return str_replace($oldpath, $newpath, $value);
    }

    /**
     * 附件删除方法
     * @param $where 删除sql语句
     */
    function delete($where)
    {
        $this->att_db = pc_base::load_model('attachment_model');
        $result = $this->att_db->select($where);
        foreach ($result as $r) {
            $image = $this->upload_root . $r['filepath'];
            @unlink($image);
            $thumbs = glob(dirname($image) . '/*' . basename($image));
            if ($thumbs)
                foreach ($thumbs as $thumb)
                    @unlink($thumb);
        }
        return $this->att_db->delete($where);
    }

    /**
     * 附件添加如数据库
     * @param $uploadedfile 附件信息
     */
    function add($Arrupfileinfo)
    {
        Doo::loadModel('attachment');
        $attaobj = new AttachmentModel();
        $aid = $attaobj->add_attachment($Arrupfileinfo);
        return $aid;
    }

    function set_userid($userid)
    {
        $this->userid = $userid;
    }

    /**
     * 获取缩略图地址..
     * @param $image 图片路径
     */
    function get_thumb($image)
    {
        return str_replace('.', '_thumb.', $image);
    }

    /**
     * 获取附件名称
     * @param $fileext 附件扩展名
     */
    function getname($fileext)
    {
        return date('Ymdhis') . rand(100, 999) . '.' . $fileext;
    }

    /**
     * 返回附件大小
     * @param $filesize 图片大小
     */
    function size($filesize)
    {
        if ($filesize >= 1073741824) {
            $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
        } elseif ($filesize >= 1048576) {
            $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
        } elseif ($filesize >= 1024) {
            $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
        } else {
            $filesize = $filesize . ' Bytes';
        }
        return $filesize;
    }

    /**
     * 判断文件是否是通过 HTTP POST 上传的
     *
     * @param    string $file 文件地址
     * @return    bool    所给出的文件是通过 HTTP POST 上传的则返回 TRUE
     */
    function isuploadedfile($file)
    {
        return is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file));
    }

    /**
     * 补全网址
     *
     * @param    string $surl 源地址
     * @param    string $absurl 相对地址
     * @param    string $basehref 网址
     * @return    string    网址
     */
    function fillurl($surl, $absurl, $basehref = '')
    {
        if ($basehref != '') {
            $preurl = strtolower(substr($surl, 0, 6));
            if ($preurl == 'http://' || $preurl == 'ftp://' || $preurl == 'mms://' || $preurl == 'rtsp://' || $preurl == 'thunde' || $preurl == 'emule://' || $preurl == 'ed2k://')
                return $surl;
            else
                return $basehref . '/' . $surl;
        }
        $i = 0;
        $dstr = '';
        $pstr = '';
        $okurl = '';
        $pathStep = 0;
        $surl = trim($surl);
        if ($surl == '')
            return '';
        $urls = @parse_url(SITE_URL);
        $HomeUrl = $urls['host'];
        $BaseUrlPath = $HomeUrl . $urls['path'];
        $BaseUrlPath = preg_replace("/\/([^\/]*)\.(.*)$/", '/', $BaseUrlPath);
        $BaseUrlPath = preg_replace("/\/$/", '', $BaseUrlPath);
        $pos = strpos($surl, '#');
        if ($pos > 0)
            $surl = substr($surl, 0, $pos);
        if ($surl[0] == '/') {
            $okurl = 'http://' . $HomeUrl . '/' . $surl;
        } elseif ($surl[0] == '.') {
            if (strlen($surl) <= 2)
                return '';
            elseif ($surl[0] == '/') {
                $okurl = 'http://' . $BaseUrlPath . '/' . substr($surl, 2, strlen($surl) - 2);
            } else {
                $urls = explode('/', $surl);
                foreach ($urls as $u) {
                    if ($u == "..")
                        $pathStep++;
                    else if ($i < count($urls) - 1)
                        $dstr .= $urls[$i] . '/';
                    else
                        $dstr .= $urls[$i];
                    $i++;
                }
                $urls = explode('/', $BaseUrlPath);
                if (count($urls) <= $pathStep)
                    return '';
                else {
                    $pstr = 'http://';
                    for ($i = 0; $i < count($urls) - $pathStep; $i++) {
                        $pstr .= $urls[$i] . '/';
                    }
                    $okurl = $pstr . $dstr;
                }
            }
        } else {
            $preurl = strtolower(substr($surl, 0, 6));
            if (strlen($surl) < 7)
                $okurl = 'http://' . $BaseUrlPath . '/' . $surl;
            elseif ($preurl == "http:/" || $preurl == 'ftp://' || $preurl == 'mms://' || $preurl == "rtsp://" || $preurl == 'thunde' || $preurl == 'emule:' || $preurl == 'ed2k:/')
                $okurl = $surl;
            else
                $okurl = 'http://' . $BaseUrlPath . '/' . $surl;
        }
        $preurl = strtolower(substr($okurl, 0, 6));
        if ($preurl == 'ftp://' || $preurl == 'mms://' || $preurl == 'rtsp://' || $preurl == 'thunde' || $preurl == 'emule:' || $preurl == 'ed2k:/') {
            return $okurl;
        } else {
            $okurl = preg_replace('/^(http:\/\/)/i', '', $okurl);
            $okurl = preg_replace('/\/{1,}/i', '/', $okurl);
            return 'http://' . $okurl;
        }
    }

    /**
     * 是否允许上传
     */
    function is_allow_upload()
    {
        if ($_groupid == 1)
            return true;
        $starttime = SYS_TIME - 86400;
        $site_setting = $this->_get_site_setting($this->siteid);
        return ($uploads < $site_setting['upload_maxsize']);
    }

    /**
     * 返回错误信息
     */
    function error()
    {
        return $this->error;
    }

    /**
     * ck编辑器返回
     * @param $fn
     * @param $fileurl 路径
     * @param $message 显示信息
     */
    function mkhtml($fn, $fileurl, $message)
    {
        $str = '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction(' . $fn . ', \'' . $fileurl . '\', \'' . $message . '\');</script>';
        exit($str);
    }

    /**
     * flash上传调试方法
     * @param $id
     */
    function uploaderror($id = 0)
    {
        file_put_contents(PHPCMS_PATH . 'xxx.txt', $id);
    }

    /**
     * 获取站点配置信息
     * @param  $siteid 站点id
     */
    private function _get_site_setting($siteid)
    {
        $siteinfo = getcache('sitelist', 'commons');
        return string2array($siteinfo[$siteid]['setting']);
    }

    /**
     * Get client's IP
     * @return string
     */
    public function clientIP()
    {
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            return getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            return getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            return getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            return $_SERVER['REMOTE_ADDR'];
        }
    }

}

?>