<?php

defined('IN_SYSTEM') === false && exit('PHPnew Blog.');
switch($default_parem[2]){
    case 'jump':
        // TODO:跳转功能管理, 可实现各种跳转模式.
        $tid = $default_parem[3]+0;
        
        # 分发功能
        if(strpos($default_parem[3],'link_') !== false){
            $link_array = fun_source('enlink');
            $lid = fun_trim($default_parem[3],'link_');
            
            $enlink_count = fun_source('enlink_count');
            
            if($link_array[$lid]['lurl']){
                $enlink_count[$lid] += 1;
                fun_source('enlink_count', $enlink_count);
                fun_header($link_array[$lid]['lurl']);
            }else{
                fun_header('./');
            }
            exit();
        }
        $one = mysql::get_one("SELECT thread_id,thread_first,thread_history FROM DB_thread WHERE thread_id='{$tid}'");
        if($one['thread_first'] !== '0'){
            $url = './';
        }else{
            $threads = unserialize($one['thread_history']);
            $url = empty($threads['th_url']) === true? fun_parse_url("./index.php?main=read&{$one['thread_id']}.html"):$threads['th_url'];
            unset($threads, $one);
        }
        fun_header($url);
        break;
    case 'phpqrcode':
        // TODO: 二维码显示功能.
        include(DIR_CLASS.'PHPqrcode_class.php');
            $color = array(255,128,64,255,255,255);
        if($default_get['color'] == 0){
            $color = array(0,161,233,255,255,255);
        }
        
        # 放大之后, 背景去掉. 以便兼容各式各样的扫描软件.
        if($default_get['big']){
            $color = array(255,255,255,255,128,64);
            if($default_get['color'] == 0){
                $color = array(255,255,255,0,161,233);
            }
        }
        
        $url = URL_HOST;
        $tid = $default_get['tid']+0;
        if($tid){
            $url = fun_parse_url("./index.php?mobile=read&$tid.html");
            $url = strtr($url, array('./'=>URL_HOST));
        }
        
        // 二维码数据
        $data = $url;
        // 纠错级别：L、M、Q、H
        $level = 'M';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 1;
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
        //$path = "images/";
        // 生成的文件名
        //$fileName = $path.$size.'.png';
        if($default_get['big']){
            //$level = 'M';
            $size = $default_get['big']+ 0;
            if($default_get['big'] > 6 || $default_get['big'] < 1)
                $size = 2;
        }
        QRcode::png($data, false, $level, $size,1);
        exit();
        break;
    case 'upload':
        // TODO: 附件上传功能, 全局性.
        # 增加对权限判断
        if(empty($user_posts) === true || app_user(true) === false)
            exit('上传权限不足');
            
		# 删除附件功能.
		if(empty($default_get['delid']) === false){ //删除 附件
			$id = $default_get['delid'] + 0;
			$one = mysql::get_one("SELECT `atime`,`amname` FROM `DB_attachments` WHERE aid='$id'");
			$file_name = './Data/attachments/' . date('Ym', $one['atime']) . '/' . $one['amname'];
			if(is_file($file_name) === true){
				unlink($file_name);
			}
			mysql::query("DELETE FROM `DB_attachments` WHERE aid='$id'");
			echo 1;
			exit();
		}
        
        # 上传文件
        # 目录规律为当前月份201112, 文件名规律为 md5(文件名.微秒时间.乱数) 有效防止重复. 
        # 所有上传文件均通过这接口, 如果要更改, 直接修改即可.
		if(IS_FILES && empty($_FILES['Filedata']) === false){
			$file = $_FILES['Filedata'];
			$path = pathinfo($file['name']);
			$file_dir = './Data/attachments/' . date('Ym') . '/';
			$file_name = md5($file['name'] . GET_MICROTIME.rand(1,9999)) . '.' . strtolower($path['extension']);
            # 无论如何, 目录是要创建的.
			if(is_dir($file_dir) === false){
				 mkdir($file_dir, 0777);
                 file_put_contents($file_dir.'index.html','phpnew blog');
			}
            
            # 非管理员时, 判断容量值.
            if(!USER_ADMIN){
    			if(empty($file['size']) ===true || $file['size'] / 1024 > $attch['maxsize']){
                    exit('容量限制');
    			}
                if(empty($attch['attch_array']) === true || in_array(strtolower($path['extension']),$attch['attch_array']) === false){
                    exit('类型限制');
                }
            }
            
			if(empty($file['error']) === true && is_uploaded_file($file['tmp_name']) === true){
				move_uploaded_file($file['tmp_name'], $file_dir . $file_name);
				$times = GET_TIME;
                $file['type'] = fun_mimetype($path['extension']);
                
                // 检查附件的
                $aistype = 0;
                if(stripos($file['type'],'image/') !== false){
                    $aistype  = 1;
                }
                $file['name'] = fun_enhtml($file['name']);
                $file['type'] = fun_enhtml($file['type']);
				mysql::query("INSERT INTO `DB_attachments`(`aid`, `aname`, `atype`, `asize`, `amname`, `atime`, `adown`, `temp`, `aistype`) VALUES (NULL, '{$file['name']}', '{$file['type']}', {$file['size']}, '{$file_name}', '$times', '0', '0','$aistype')");
				$insert_id = mysql::insert_id();
                exit('itemid=0,aid='.$insert_id.',attachment='.$file_dir.$file_name);
			} else{
				exit('上传失败');
			}
		}else{
			     exit('上传过程未开始');
		}
        break;
     case 'down':
            // TODO: 附件下载功能, 可检测cookie.
			$id = $default_parem[3] + 0;
            $tid = $default_parem[4] + 0;
            if(md5($_config['default']['ankey'].$tid.$id) !== $default_parem[5]){
                fun_message('系统无法接收指令,请稍后再试！');
            }
			$attch_one = mysql::get_one("SELECT `aname`, `atype`, `asize`, `amname`,`tid`,`fid`, `atime`,`temp` FROM `DB_attachments` WHERE aid = '$id'");
            
            $cookie_thread_id = fun_getcookie('thread_id') + 0;
            
            if($cookie_thread_id !== $tid || $tid !== ($attch_one['tid']+0) ){
                $url = empty($attch_one['tid']) === false? fun_parse_url("./index.php?main=read&{$attch_one['tid']}.html"):fun_parse_url("./index.php?main=cat&{$attch_one['fid']}.html");
                fun_message('系统不支持从外部直接访问附件，请访问主题后下载！',$url);
            }
            
			$file_path = './Data/attachments/' . fun_date('Ym', $attch_one['atime']) . '/' . $attch_one['amname'];
			if (is_file($file_path) === false || $attch_one['temp'] != 1) {
				exit('文件丢失');
			}
            mysql::query("UPDATE `DB_attachments` SET adown = (adown + 1) WHERE aid = '$id'");
			header("Content-type: {$attch_one['atype']}");
			header("Expires: 0");
			header("Pragma: no-cache");
			header("Accept-Ranges: bytes");
			header("Accept-Length: " . filesize($file_path));
			header("Content-Disposition: attachment; filename=" . urlencode($attch_one['aname']));
			print fun_get_contents($file_path);
        break;  
     default:
        // TODO: 默认跳转至首页.
        fun_header();
        break;
}

# 函数开始
function temp_get_mimetype($filepre) {
	$a = array(
			'rar'=>'application/x-rar-compressed',
			'ez' => 'application/andrew-inset',
			'hqx' => 'application/mac-binhex40',
			'cpt' => 'application/mac-compactpro',
			'doc' => 'application/msword',
			'bin' => 'application/octet-stream',
			'dms' => 'application/octet-stream',
			'lha' => 'application/octet-stream',
			'lzh' => 'application/octet-stream',
			'exe' => 'application/octet-stream',
			'class' => 'application/octet-stream',
			'so' => 'application/octet-stream',
			'dll' => 'application/octet-stream',
			'oda' => 'application/oda',
			'pdf' => 'application/pdf',
			'ai' => 'application/postscrīpt',
			'eps' => 'application/postscrīpt',
			'ps' => 'application/postscrīpt',
			'smi' => 'application/smil',
			'smil' => 'application/smil',
			'mif' => 'application/vnd.mif',
			'xls' => 'application/vnd.ms-excel',
			'ppt' => 'application/vnd.ms-powerpoint',
			'wbxml' => 'application/vnd.wap.wbxml',
			'wmlc' => 'application/vnd.wap.wmlc',
			'wmlsc' => 'application/vnd.wap.wmlscrīptc',
			'bcpio' => 'application/x-bcpio',
			'vcd' => 'application/x-cdlink',
			'pgn' => 'application/x-chess-pgn',
			'cpio' => 'application/x-cpio',
			'csh' => 'application/x-csh',
			'dcr' => 'application/x-director',
			'dir' => 'application/x-director',
			'dxr' => 'application/x-director',
			'dvi' => 'application/x-dvi',
			'spl' => 'application/x-futuresplash',
			'gtar' => 'application/x-gtar',
			'hdf' => 'application/x-hdf',
			'js' => 'application/x-javascrīpt',
			'skp' => 'application/x-koan',
			'skd' => 'application/x-koan',
			'skt' => 'application/x-koan',
			'skm' => 'application/x-koan',
			'latex' => 'application/x-latex',
			'nc' => 'application/x-netcdf',
			'cdf' => 'application/x-netcdf',
			'sh' => 'application/x-sh',
			'shar' => 'application/x-shar',
			'swf' => 'application/x-shockwave-flash',
			'sit' => 'application/x-stuffit',
			'sv4cpio' => 'application/x-sv4cpio',
			'sv4crc' => 'application/x-sv4crc',
			'tar' => 'application/x-tar',
			'tcl' => 'application/x-tcl',
			'tex' => 'application/x-tex',
			'texinfo' => 'application/x-texinfo',
			'texi' => 'application/x-texinfo',
			't' => 'application/x-troff',
			'tr' => 'application/x-troff',
			'roff' => 'application/x-troff',
			'man' => 'application/x-troff-man',
			'me' => 'application/x-troff-me',
			'ms' => 'application/x-troff-ms',
			'ustar' => 'application/x-ustar',
			'src' => 'application/x-wais-source',
			'xhtml' => 'application/xhtml+xml',
			'xht' => 'application/xhtml+xml',
			'zip' => 'application/zip',
			'au' => 'audio/basic',
			'snd' => 'audio/basic',
			'mid' => 'audio/midi',
			'midi' => 'audio/midi',
			'kar' => 'audio/midi',
			'mpga' => 'audio/mpeg',
			'mp2' => 'audio/mpeg',
			'mp3' => 'audio/mpeg',
			'wma' => 'audio/mpeg',
			'aif' => 'audio/x-aiff',
			'aiff' => 'audio/x-aiff',
			'aifc' => 'audio/x-aiff',
			'm3u' => 'audio/x-mpegurl',
			'ram' => 'audio/x-pn-realaudio',
			'rm' => 'audio/x-pn-realaudio',
			'rpm' => 'audio/x-pn-realaudio-plugin',
			'ra' => 'audio/x-realaudio',
			'wav' => 'audio/x-wav',
			'pdb' => 'chemical/x-pdb',
			'xyz' => 'chemical/x-xyz',
			'bmp' => 'image/bmp',
			'gif' => 'image/gif',
			'ief' => 'image/ief',
			'jpeg' => 'image/jpeg',
			'jpg' => 'image/pjpeg',
			'jpe' => 'image/jpeg',
			'png' => 'image/png',
			'tiff' => 'image/tiff',
			'tif' => 'image/tiff',
			'djvu' => 'image/vnd.djvu',
			'djv' => 'image/vnd.djvu',
			'wbmp' => 'image/vnd.wap.wbmp',
			'ras' => 'image/x-cmu-raster',
			'pnm' => 'image/x-portable-anymap',
			'pbm' => 'image/x-portable-bitmap',
			'pgm' => 'image/x-portable-graymap',
			'ppm' => 'image/x-portable-pixmap',
			'rgb' => 'image/x-rgb',
			'xbm' => 'image/x-xbitmap',
			'xpm' => 'image/x-xpixmap',
			'xwd' => 'image/x-xwindowdump',
			'igs' => 'model/iges',
			'iges' => 'model/iges',
			'msh' => 'model/mesh',
			'mesh' => 'model/mesh',
			'silo' => 'model/mesh',
			'wrl' => 'model/vrml',
			'vrml' => 'model/vrml',
			'css' => 'text/css',
			'html' => 'text/html',
			'htm' => 'text/html',
			'asc' => 'text/plain',
			'txt' => 'text/plain',
			'rtx' => 'text/richtext',
			'rtf' => 'text/rtf',
			'sgml' => 'text/sgml',
			'sgm' => 'text/sgml',
			'tsv' => 'text/tab-separated-values',
			'wml' => 'text/vnd.wap.wml',
			'wmls' => 'text/vnd.wap.wmlscrīpt',
			'etx' => 'text/x-setext',
			'xsl' => 'text/xml',
			'xml' => 'text/xml',
			'mpeg' => 'video/mpeg',
			'mpg' => 'video/mpeg',
			'mpe' => 'video/mpeg',
			'qt' => 'video/quicktime',
			'mov' => 'video/quicktime',
			'mxu' => 'video/vnd.mpegurl',
			'avi' => 'video/x-msvideo',
			'movie' => 'video/x-sgi-movie',
			'wmv' => 'application/x-mplayer2',
			'ice' => 'x-conference/x-cooltalk',
		);
		$filepre = trim(strtolower($filepre),'.');
		if(empty($a[$filepre]) === true)
			return false;
		return $a[$filepre];
}