<?php
error_reporting(0); //4
$thiscolspan = 2 ;
$js_lightbox = 1 ;
$Gallery = TRUE;
session_start();

include("0sqlconnect.php");
include("0gallery.php");
require_once("0member.php");
require("0system.php");
require_once("0admins.php");

$Conf_IMGServer = CONFIG_IMAGE_SERVER3;
$session_time = date("Y-m-d H:i:s", gmmktime()+0) ;

$DBorFILE = 1; //1=DB , 0=FILE
$spLimit_Date = CONTINUE_DAYS; //續繪限制時間


/*
if($_GET['mode'] == "gopaint"){
	header ("Location: page_msg.php?eid=142");
}
if(count($_POST)>0){
	header ("Location: page_msg.php?eid=142");
}
*/

/*
//有新圖
				$syncfile = 'dat/sync.txt' ;
				$syncfh = fopen($syncfile, 'w');
				fwrite($syncfh, '1');
				fclose($syncfh);
				*/
//pp($_SESSION); exit;

//pp($admin_group['gallerys']); exit;
//檢查是否管理者
if( $get_ip_alll == "127.0.0.1" || $_SESSION['session_userid']==10001 || $_SESSION['session_userid']==83399	|| in_array($_SESSION['session_userid'], $admin_group['gallerys'])){
	$GalleryAdmin = 1;
}
//var_dump($GalleryAdmin); exit;

//自建快速刪除
if( $_GET['admin']=="del" && $_GET['delimg']==1 && !empty($_GET['delimgid']) ){
	$onlyimgdel = "on" ;
	$del[0]=$_GET['delimgid'];
	//admindel("12345");
}
//自建快速刪除 回覆留言
if( $_GET['admin']=="del" && $_GET['delcom']==1 && !empty($_GET['delimgid']) ){
	//$onlyimgdel = "on" ;
	$del[0]=$_GET['delimgid'];
	//admindel("12345");
}

// 作者刪除暫存
if( !empty($_GET['mid']) && !empty($_GET['gaid']) && $_GET['reqdel']==1 ){
	//
	if( !empty($_SESSION['session_userid']) && $_GET['mid']==$_SESSION['session_userid'] || $_SESSION['session_userid']==10001){
		$gaid = intval($_GET['gaid']);
		if(!empty($gaid)){
			treedel($gaid);
			echo '已刪除'; exit;
		}
	}else{
		echo 'Error!!';
		exit;
	}
}

	//會員登入
function login_check_name_poti($text){
	$text = addslashes($text) ;
	$sql = "SELECT `mem_name`,`mem_id` FROM `member` WHERE `mem_name`='$text' LIMIT 1" ;
	$rcd = mysql_fetch_array(mysql_query($sql)) ;
	if ( empty($rcd['mem_name']) || empty($rcd['mem_id']) ){
		$rnt = 1 ;
	}
	return $rnt ;
}

//名字查密碼
function login_check_passwd_poti($text){
	$text = addslashes($text) ;
	$sql = "SELECT `mem_passwd` FROM `member` WHERE `mem_name`='$text' LIMIT 1" ;
	$rcd = mysql_fetch_array(mysql_query($sql)) ;
	return $rcd['mem_passwd'] ;
}

//名字查ID
function member_user_to_id_poti($text){
	$text = addslashes($text) ;
	$sql = "SELECT `mem_id` FROM `member` WHERE `mem_name`='$text' LIMIT 1" ;
	$rcd = mysql_fetch_array(mysql_query($sql)) ;
	return $rcd['mem_id'] ;
}

//日期轉換
function dtimeShift($dtime, $shift){
	list($date, $time) = explode(' ', $dtime);
  list($year, $month, $day) = explode('-', $date);
  list($hour, $minute, $second) = explode(':', $time);
  $timestamp = mktime($hour, $minute, $second, $month, $day, $year);
	return date("Y-m-d H:i:s", $timestamp+$shift);
}


//自動登入
if ( empty($_SESSION['session_userid']) ){
	if ( $_COOKIE['mabi_autologin'] == 1 ){
		if ( !empty($_COOKIE['mabi_username']) ){
			if (login_check_name_poti($_COOKIE['mabi_username']) != 1){
				if ( !empty($_COOKIE['mabi_passwd']) ){
					if ( login_check_passwd_poti($_COOKIE['mabi_username']) === $_COOKIE['mabi_passwd'] ){
						//重新寫入會員 Cookies
						setcookie ("mabi_username", $_COOKIE['mabi_username'] ,time()+2592000) ;
						setcookie ("mabi_passwd", $_COOKIE['mabi_passwd'] ,time()+2592000) ;
						//寫入 Session
						$_SESSION['session_userid'] = member_user_to_id_poti($_COOKIE['mabi_username']) ;
						//寫入最後登入日期
						$sql_last_login = "UPDATE `member` SET `mem_lastlogin`='$session_time', `mem_login`=`mem_login`+1 WHERE `mem_id`='$_SESSION[session_userid]' LIMIT 1" ;
						mysql_query($sql_last_login) ;
						//重新寫入自動登入
						if ($_COOKIE['mabi_autologin'] == 1){
							setcookie ("mabi_autologin", 1 ,time()+2592000) ;
						}
					}else{
						$login_message_name = '自動登入失敗，請重新登入！' ;
					}
				}else{
					$login_message_name = '自動登入失敗，請重新登入！' ;
				}
			}else{
				$login_message_name = '自動登入失敗，請重新登入！' ;
			}
		}else{
			$login_message_name = '自動登入失敗，請重新登入！' ;
		}
	}
}

if($_GET['mode']=='piccom'||$_POST['mode']=='paint'||$_POST['mode']=='regist'||$_GET['mode']=='continue'||$_POST['mode']=='contpaint'){
	//非會員導出
	if ( empty($_SESSION['session_userid']) || $_SESSION['session_userid'] < 10000 ){
		header ("Location: page_msg.php?eid=pleaselogin");
		exit;
	}
}
if($_GET['mode']=='admin'||$_POST['mode']=='admin'){
	if ( $GalleryAdmin!=1 && $_SESSION['session_userid']!=50721 ){
		header ("Location: page_msg.php?eid=noauth");
		exit;
	}
}

function member_id_to_pass($id){
	$id = addslashes($id) ;
	$sql = "SELECT `mem_passwd` FROM `member` WHERE `mem_id`='$id' LIMIT 1" ;
	$rcd = mysql_fetch_array(mysql_query($sql)) ;
	return ($rcd[0]) ;
}

	//ID查名字
function member_id_to_users($text){
	$text = addslashes($text) ;
	$sql = "SELECT `mem_name` FROM `member` WHERE `mem_id`='$text' LIMIT 1" ;
	$rcd = mysql_fetch_array(mysql_query($sql)) ;
	return $rcd['mem_name'] ;
}

	//查詢愛心數量
function gallery_point($id){
	$cnt =  mysql_fetch_array(mysql_query("SELECT SUM(`point`) FROM `galleryp` WHERE `gid`='".$id."' ;"));
	//mysql_query("UPDATE `cosplayii` SET `volted`='".$VoltedCnt[0]."' WHERE `id`='".$rcd_cosii[0]."'");
	if ( $cnt[0] == NULL ) $cnt[0] = 0 ;
	return $cnt[0];
}

//暫存偵測設定
$arrTMP = array('tmp','TMP','暫存');
function tmpDetect($sub){
	global $arrTMP;
	foreach($arrTMP as $val){
		if(substr_count($sub, $val) > 0) return true;
	}
	return false;
}

$TMPSQL = " AND `title` NOT LIKE '%tmp%' AND `title` NOT LIKE '%暫存%'";

//更新新圖
function updateImgNew(){
	global $TMPSQL;
	include_once("ga_config.php");
	$data = array();
	$rst = mysql_query("SELECT * FROM `gallery` WHERE `title`!='re' ".$TMPSQL." ORDER BY `id` DESC LIMIT 4;");
	//echo "SELECT * FROM `gallery` WHRER `title`!='re' AND `title` NOT LIKE '%tmp%' AND `title` NOT LIKE '%暫存%' ORDER BY `id` DESC LIMIT 4;"; exit;
	while( $rcd = mysql_fetch_assoc($rst) ){
		$url = gallery_image($rcd);
		$data[] = array($rcd['id'], $url, $rcd['title']);
	}

	$file = 'cache/gallery_new.php' ;
	$fh = fopen($file, 'w');
	$i = 0 ;
	$str = '';
	foreach ( $data as $v1 ){
		$j = 0 ;
		foreach ( $v1 as $v2 ){
			$j++ ;
			$str .= '$GALNEW['.$i.']['.$j.'] = "'.addslashes(htmlspecialchars($v2))."\" ;\n" ;
		}
		$i++ ;
	}
	fwrite($fh, '<?php'."\r\n".$str.'?>');
	fclose($fh);
}


//寫入刪除檔案紀錄
function logDelFile($filename){
	$file = 'dat/gallery_del.txt' ;
	$fh = fopen($file, 'a+');
	fwrite($fh, $filename."\r\n");
	fclose($fh);
}


//讀取是否精華
function chkGalleryZ($id){
	$rcd =  mysql_fetch_row(mysql_query("SELECT `zid`,`zmapid` FROM `galleryzz` WHERE `zid`='".$id."' LIMIT 1;"));
	if( !empty($rcd[0]) ){
		return array('精華作品', $rcd[1]);
	}
}

//讀取是否活動
function chkGalleryEvent($id){
	$rcd =  mysql_fetch_row(mysql_query("SELECT * FROM `gallerykv` WHERE `id`='".$id."' LIMIT 1;"));
	if(!empty($rcd[1])){
		return GelleryEventName($rcd[1]);
	}
}

//讀取一張圖
function GetGallery($id)
{
	$rcd =  mysql_fetch_assoc(mysql_query("SELECT `id`,`dtime`,`title`,`img`,`imgsuf` FROM `gallery` WHERE `id`='".$id."' AND `title`!='re' LIMIT 1;"));
	if(count($rcd) > 0){
		$url = gallery_image($rcd);
		return '<a href="ac_gallery_poti.php?res='.$rcd['id'].'"><img src="'.$url.'" border="1" width="70" title="'.$rcd['title'].'" alt="'.$rcd['title'].'"></a>';
	}
}

/*
  *
  * Ami PaintBBS v060220
  *   (C)Ming >> http://ngol.demons.to/ming/
  *
  *----------------------------------------------------------------------------------
  * POTI-board v1.32 lot.050602
  *   (C)SakaQ >> http://www.punyu.net/
  *
  * ORIGINAL SCRIPT :
  *   futaba.php v0.8 lot.031015 (gazou.php v3.0 CUSTOM)
  *     (C)futaba >> http://www.2chan.net/ ((C)ToR >> http://php.s3.to/)
  *
  * OEKAKI APPLET :
  *   PaintBBS   (test by v2.22_8)
  *   ShiPainter (test by v1.081)
  *   PCHViewer  (test by v1.15)
  *     (C)shi-chan >> http://shichan.jp/
  *
  * USE FUNCTION :
  *   HTML template         (C)H.Ayukawa >> http://hoover.ktplan.ne.jp/kaihatsu/php/
  *   DynamicPalette        (C)NoraNeko  >> http://wondercatstudio.com/
  *   repng2jpeg            (C)SUGA      >> http://sugachan.dip.jp/
  *----------------------------------------------------------------------------------

このスクリプトは「レッツPHP!」<http://php.s3.to/>のgazou.phpを改造した、
「ふたば★ちゃんねる」<http://www.2chan.net/>のfutaba.phpを
さらにお絵かきもできるようにして、HTMLテンプレートでデザイン変更できるように改造したものです。

散佈條件以はレッツPHP!為準。可自由修改、再散佈。

關於此程式的相關問題請不要詢問「レッツPHP!」、「ふたば★ちゃんねる」等站。
*/

if(phpversion()>="4.1.0"){
	extract($_POST);
	extract($_GET);
	extract($_COOKIE);
	extract($_SERVER);
	$upfile_name=$_FILES["upfile"]["name"];
	$upfile=$_FILES["upfile"]["tmp_name"];
}
// 讀入外部設定檔案
include_once("ga_config.php");
// HTMLテンプレートクラス(htmltemplate_oo 0.3.1)
require("ga_htmltemplate.inc");
// Template 設定檔案
require("ga_template_ini.php");


// 快速重建 cache
if( isset($_GET['updateimg']) && $_GET['updateimg']==1 ){
	updateImgNew();
	//jslocation('ac_gallery.php');
	header ("Location: ac_gallery.php"); exit;
}

//匿名問題
//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");

$path = realpath("./").'/'.IMG_DIR;
$temppath = realpath("./").'/'.TEMP_DIR;

// thumbnail function
if((THUMB_SELECT==0 && gd_check()) || THUMB_SELECT==1){
	require("ga_thumbnail_gd.php");
	//echo 'GD';
}else{
	require("ga_thumbnail_re.php");
}

// cookie & mail通知でMB Function 使用:1 不使用:0
define(USE_MB , 1);

// 程式 Version
define(POTI_VER   , 'v1.32');
define(POTI_VERLOT, 'v1.32 lot.050602');

// mail 通知的 class 檔案
//define(NOTICEMAIL_FILE , 'ga_noticemail.inc');
// Paint Applet Help 的檔案
define(SIIHELP_FILE , 'ga_siihelp.php');

switch(CHARSET_OUT){
	case 1 : $charset="EUC-JP";break;
	case 2 : $charset="Shift_JIS";break;
	case 3 : $charset="ISO-2022-JP";break;
	case 4 : $charset="utf-8";break;
	default : $charset=CHARSET_OUT;
}
define(CHARSET_HTML, $charset);

//----------htmltemplate Tag定義
//{$hoge}
//rvalじゃ長いので$で定義
class tag_rval2 extends DataTag{
var $matchregexp='/\{\$([^\}]+)\}/i';
var $fromstring="{\$%s}";
var $tostring="<?php @print \$val%1\$s; ?>\n";
}
//<!--{def hoge}-->～<!--{/def}-->
//舊type再定義
class tag_def2 extends ArrayTag{
var $matchregexp='/<!--\{def ([^\}]+)\}-->/i';
var $fromstring="<!--{def %s}-->";
var $tostring="<?php
if(@\$val%1\$s &&((gettype(\$val%1\$s)!='array' && \$val%1\$s!=\"\") or (gettype(\$val%1\$s)=='array' && count(\$val%1\$s)>0))){ ?>";
var $closestring="<!--{/def}-->";
}
//<!--{ndef hoge}-->～<!--{/ndef}-->
//再定義(hogeが空(0も含む)の場合に、タグの間の～部分を表示する。defの逆)
class tag_ndef2 extends ArrayTag{
var $matchregexp='/<!--\{ndef ([^\}]+)\}-->/i';
var $fromstring="<!--{ndef %s}-->";
var $tostring="<?php
if(!(@\$val%1\$s &&((gettype(\$val%1\$s)!='array' && \$val%1\$s!=\"\") or (gettype(\$val%1\$s)=='array' && count(\$val%1\$s)>0)))){ ?>";
var $closestring="<!--{/ndef}-->";
}
//<!--{vdef hoge}-->～<!--{/vdef}-->
//新タイプ(0もある物とみなす)で再定義
class tag_vdef2 extends ArrayTag{
var $matchregexp='/<!--\{vdef ([^\}]+)\}-->/i';
var $fromstring="<!--{vdef %s}-->";
var $tostring="<?php
if(@count(\$val%1\$s) && (is_array(\$val%1\$s) || strlen(\$val%1\$s))){ ?>";
var $closestring="<!--{/vdef}-->";
}
//<!--{ifeq hoge:val}-->～<!--{/ifeq}-->
// hoge = val の場合、タグの間の～部分を表示する
class tag_ifeq extends DataTag{
var $matchregexp='/<!--\{ifeq ([^\}:]+):([^\}:]+)\}-->/i';
var $fromstring="<!--{ifeq %1\$s:%2\$s}-->";
var $tostring="<?php
if(\$val%1\$s == '%3\$s'){ ?>";
var $closestring="<!--{/ifeq}-->";
}
//<!--{ifne hoge:val}-->～<!--{/ifne}-->
// hoge != val の場合、タグの間の～部分を表示する
class tag_ifne extends DataTag{
var $matchregexp='/<!--\{ifne ([^\}:]+):([^\}:]+)\}-->/i';
var $fromstring="<!--{ifne %1\$s:%2\$s}-->";
var $tostring="<?php
if(\$val%1\$s != '%3\$s'){ ?>";
var $closestring="<!--{/ifne}-->";
}
//<!--{iflt hoge:val}-->～<!--{/iflt}-->
// hoge < val の場合、タグの間の～部分を表示する
class tag_iflt extends DataTag{
var $matchregexp='/<!--\{iflt ([^\}:]+):([^\}:]+)\}-->/i';
var $fromstring="<!--{iflt %1\$s:%2\$s}-->";
var $tostring="<?php
if(\$val%1\$s < '%3\$s'){ ?>";
var $closestring="<!--{/iflt}-->";
}
//<!--{ifgt hoge:val}-->～<!--{/ifgt}-->
// hoge > val の場合、タグの間の～部分を表示する
class tag_ifgt extends DataTag{
var $matchregexp='/<!--\{ifgt ([^\}:]+):([^\}:]+)\}-->/i';
var $fromstring="<!--{ifgt %1\$s:%2\$s}-->";
var $tostring="<?php
if(\$val%1\$s > '%3\$s'){ ?>";
var $closestring="<!--{/ifgt}-->";
}
//<!--{ifle hoge:val}-->～<!--{/ifle}-->
// hoge <= val の場合、タグの間の～部分を表示する
class tag_ifle extends DataTag{
var $matchregexp='/<!--\{ifle ([^\}:]+):([^\}:]+)\}-->/i';
var $fromstring="<!--{ifle %1\$s:%2\$s}-->";
var $tostring="<?php
if(\$val%1\$s <= '%3\$s'){ ?>";
var $closestring="<!--{/ifle}-->";
}
//<!--{ifge hoge:val}-->～<!--{/ifge}-->
// hoge >= val の場合、タグの間の～部分を表示する
class tag_ifge extends DataTag{
var $matchregexp='/<!--\{ifge ([^\}:]+):([^\}:]+)\}-->/i';
var $fromstring="<!--{ifge %1\$s:%2\$s}-->";
var $tostring="<?php
if(\$val%1\$s >= '%3\$s'){ ?>";
var $closestring="<!--{/ifge}-->";
}
//{?}
//通常は Escape させないでスルー
class q_escape extends DataTag{
var $matchregexp='/\{\?\}/i';
var $fromstring="{?}";
var $tostring="?";
}
//Main の書込み時のみ Escape
class q_escape2 extends DataTag{
var $matchregexp='/\{\?\}/i';
var $fromstring="{?}";
var $tostring="<?php @print '?'; ?>";
}
//<!--(～)-->
//～的部份不顯示(this portion is not displayed)
class tag_comment2 extends ArrayTag{
var $matchregexp='/<!--\(/i';
var $fromstring="<!--(";
var $tostring="<?php if(FALSE){?>";
var $closestring=")-->";
}

htmltemplate::removeTag("tag_rval");
htmltemplate::removeTag("tag_def");
htmltemplate::removeTag("tag_ndef");
htmltemplate::removeTag("tag_vdef");
htmltemplate::addTag("tag_rval2");
htmltemplate::addTag("tag_def2");
htmltemplate::addTag("tag_ndef2");
htmltemplate::addTag("tag_vdef2");
htmltemplate::addTag("tag_ifeq");
htmltemplate::addTag("tag_ifne");
htmltemplate::addTag("tag_iflt");
htmltemplate::addTag("tag_ifgt");
htmltemplate::addTag("tag_ifle");
htmltemplate::addTag("tag_ifge");
htmltemplate::addTag("q_escape");
htmltemplate::addTag("tag_comment2");

//GD版が使えるか check
function gd_check(){
	$flag = true;
	$check = array("ImageCreate","ImageCopyResized","ImageCreateFromJPEG","ImageJPEG","ImageDestroy");

  //最低限度的GD功能が使えるか check
	if(get_gd_ver() && (ImageTypes() & IMG_JPG)){
		foreach ( $check as $cmd ) {
			if(!function_exists($cmd)){$flag=false; break;}
		}
	}else{$flag=false;}

	return $flag;
}

//gd的版本を調べる
function get_gd_ver(){
	if(function_exists("gd_info")){
		$gdver=gd_info();
		$phpinfo=$gdver["GD Version"];
	}else{ //php4.3.0未満用
		ob_start();
		phpinfo(8);
		$phpinfo=ob_get_contents();
		ob_end_clean();
		$phpinfo=strip_tags($phpinfo);
		$phpinfo=stristr($phpinfo,"gd version");
		$phpinfo=stristr($phpinfo,"version");
	}
	$end=strpos($phpinfo,".");
	$phpinfo=substr($phpinfo,0,$end);
	$length = strlen($phpinfo)-1;
	$phpinfo=substr($phpinfo,$length);
	return $phpinfo;
}

/* Header */
function head(&$dat){
	$dat['title'] = TITLE;
	$dat['home']  = HOME;
	$dat['self']  = PHP_SELF;
	$dat['self2'] = PHP_SELF2;
	$dat['paint'] = USE_PAINT ? true : false;

	$dat['applet'] = APPLET ? true : false;
	$dat['usepbbs'] = APPLET!=1 ? true : false;

	$dat['ver'] = POTI_VER;
	$dat['verlot'] = POTI_VERLOT;
	$dat['tver'] = TEMPLATE_VER;

	$dat['userdel'] = USER_DEL;
	$dat['charset'] = CHARSET_HTML;

    //更新日期 start
    $dat['upver'] = UPDATE_VER;
    //更新日期 end
    $dat['userdel'] = USER_DEL;
    //banner 路徑 start
    $dat['banner'] = BANNER_URL;
    //banner 路徑 end
}

/* 投稿form */
function form(&$dat,$resno,$admin="",$tmp=""){
	global $addinfo,$stime;
	global $fontcolors,$undo,$undo_in_mg,$quality,$qualitys;

	$dat['form'] = true;
	if(USE_PAINT){
		$dat['palette'] = '';
		$lines = file(PALETTEFILE);
		foreach ( $lines as $line ) {
			$line=preg_replace("/[\t\r\n]/","",$line);
			list($pid,$pname,) = explode(",", $line);
			$dat['palette'] .= '<option value="'.$pid.'">'.CleanStr($pname)."</option>\n";
		}
		$dat['pdefw'] = PDEF_W;
		$dat['pdefh'] = PDEF_H;
		$dat['anime'] = USE_ANIME ? true : false;
		$dat['animechk'] = DEF_ANIME ? ' checked="checked"' : '';
		$dat['pmaxw'] = PMAX_W;
		$dat['pmaxh'] = PMAX_H;
		if(USE_PAINT==2 && !$resno && !$admin){
			$dat['paint2'] = true;
			$dat['form'] = false;
		}
	}

	if($resno){
		$dat['resno'] = $resno;
		$dat['userid'] = $_SESSION['session_userid'];
		if(RES_UPLOAD) $dat['paintform'] = true;
	}else{
		$dat['paintform'] = true;
		$dat['notres'] = true;
	}

	if($admin) $dat['admin'] = ADMIN_PASS;

	if($stime && DSP_PAINTTIME){
		//繪圖時間
		$ptime = '';
		if($stime){
			$psec = time()-$stime;
			if($psec >= 86400){
				$D = intval($psec/86400);
				$ptime .= $D.PTIME_D;
				$psec -= $D*86400;
			}
			if($psec >= 3600){
				$H = intval($psec/3600);
				$ptime .= $H.PTIME_H;
				$psec -= $H*3600;
			}
			if($psec >= 60){
				$M = intval($psec/60);
				$ptime .= $M.PTIME_M;
				$psec -= $M*60;
			}
			if($psec){
				$ptime .= $psec.PTIME_S;
			}
		}
		$dat['ptime'] = $ptime;
	}

	$dat['maxbyte'] = MAX_KB * 1024;
	$dat['usename'] = USE_NAME ? ' *' : '';
	$dat['usesub']  = USE_SUB ? ' *' : '';
	if(USE_COM||$resno) $dat['usecom'] = ' *';
	if((!$resno && !$tmp) || (RES_UPLOAD && !$tmp)) $dat['upfile'] = true;
	$dat['maxkb']   = MAX_KB;
	$dat['maxw']    = $resno ? MAX_RESW : MAX_W;
	$dat['maxh']    = $resno ? MAX_RESH : MAX_H;
	$dat['addinfo'] = $addinfo;
	$dat['potitag'] = USE_POTITAG ? true : false;

	//文字顏色
	if(USE_FONTCOLOR){
		foreach ( $fontcolors as $fontcolor ){
			list($color,$name) = explode(",", $fontcolor);
			$dat['fctable'][] = compact('color','name');
		}
	}

	//Applet 設定
	$dat['undo'] = $undo ? $undo : UNDO;
	$dat['undo_in_mg'] = $undo_in_mg ? $undo_in_mg : UNDO_IN_MG;
	$qline='';
	foreach ( $qualitys as $q ){
		$selq = ($q == $quality) ? ' selected' : '';
		$qline .= '<option value='.$q.$selq.'>'.$q."</option>\n";
	}
	$dat['qualitys'] = $qline;
}

/* 留言部份 */
function updatelog($resno=0){
	$resno = intval($resno);
	global $path;
	global $Conf_IMGServer;
	global $DBorFILE,$TMPSQL,$myadminnnn,$GalleryAdmin,$arrTMP;
	// 取得精華所有分區
	$rst_Gaz = mysql_query("SELECT `zMapid`,`zName` FROM `galleryzmap` ORDER BY `zid` ASC");
	while( $rcd = mysql_fetch_row($rst_Gaz) ){
		$GalzMap[$rcd[0]] = $rcd[1];
	}


	$find = false;
	if($resno){
		$rst = mysql_query("SELECT `id` FROM `gallerytree` WHERE `id`='$resno' OR `reid`='$resno' ORDER BY `id` ASC") ;
		//echo "SELECT `id` FROM `gallerytree` WHERE `id`='$resno' OR `reid`='$resno' ORDER BY `id` ASC";
		while( $rcd = mysql_fetch_row($rst) ){
			$dbtree[] = $rcd[0];
			$line[] = ' ';
		}
		if( count($dbtree) > 0 ){
			$find=true; $counttree=1;
		}
		foreach($dbtree as $val){
			$tree[$dbtree[0]] .= $val.',';
		}
		$st = $dbtree[0];
		//echo $tree[$i];
		//if( $myadminnnn==1 ) print_r($tree);
		if(!$find) error(MSG001);
	}else{
		//計算總 TREE
		$mi = 0;
		$sqlTMP = "";
		foreach($arrTMP as $val){
			$sqlTMP .= " AND `gallery`.`title` NOT LIKE '%".$val."%' ";
		}
		$rst = mysql_query("SELECT `gallerytree`.`id`, `gallery`.`title` FROM `gallerytree`,`gallery` WHERE `reid`=0 AND `gallerytree`.`id`=`gallery`.`id` ".$sqlTMP." ORDER BY `id` DESC LIMIT 166;");
		//echo "SELECT `gallerytree`.`id`, `gallery`.`title` FROM `gallerytree`,`gallery` WHERE `reid`=0 AND `gallerytree`.`id`=`gallery`.`id` ".$sqlTMP." ORDER BY `id` DESC LIMIT 166;"; exit;
		while( $rcd = mysql_fetch_row($rst) ){
			$rst2 = mysql_query("SELECT `id` FROM `gallerytree` WHERE `reid`=".$rcd[0]." ORDER BY `id` ASC;");
			//echo $rcd[0];
			unset($dbtree);
			while( $rcd2 = mysql_fetch_row($rst2) ){
				$dbtree[] = $rcd2[0];
			}
			//print_r($dbtree);
			$tree[$mi] = $rcd[0].','.join(',', $dbtree);
			$mi++;
		}
		//print_r($tree);
		//exit;
	}

	//print_r($tree);exit;

	// LOGFILE
	//while (!feof ($fd))
	if($resno){ //單查詢
		$rst = mysql_query("SELECT * FROM `gallery` WHERE `id` IN (".$tree[$resno]."0) ORDER BY `id` DESC") ;
		//echo "SELECT * FROM `gallery` WHERE `id` IN (".$tree[$resno]."0) ORDER BY `id` DESC";
		while( $rcd = mysql_fetch_row($rst) ){
			//$dblog[] = $rcd;
			$line[] = join(',', $rcd);
		}
		//print_r($line);
	}else{ //更新頁面 1~10 頁
		$rst = mysql_query("SELECT * FROM `gallery` ORDER BY `id` DESC LIMIT 0,2000") ;
		//echo "SELECT * FROM `gallery` WHERE `title`!='re' ".$TMPSQL." ORDER BY `id` DESC LIMIT 0,1000";exit;
		//echo "SELECT * FROM `gallery` WHERE `id` IN (".$tree[$resno]."0) ORDER BY `id` ASC"; exit;
		while( $rcd = mysql_fetch_row($rst) ){
			$line[] = join(',', $rcd);
		}
		//print_r($line); exit;
		updateImgNew();
	}

	//同步更新
	//updateImgNew(LOGFILE);
	//echo 'up';exit;
	//echo $_SESSION['session_userid'];exit;
	//echo cntMemberGallery($_SESSION['session_userid']);
	//更新留言者篇數
	//mysql_query("UPDATE `member` SET `mem_paint`='".cntMemberGallery($_SESSION['session_userid'])."' WHERE `mem_id`='".$_SESSION['session_userid']."' LIMIT 1;") ;

	//exit;
	if($resno) $countline=count($line);
	else $countline=2000;

	for($i = 0; $i < $countline; $i++){
		list($no,) = explode(",", $line[$i]);
		//echo $no;exit;
		$lineindex[$no]=$i + 1; //逆変換テーブル作成
	}
	//echo $lineindex[$no];

	//$counttree = count($tree);
	if($resno) $countline=count($line);
	else $counttree = 166;

	for($page=0;$page<$counttree;$page+=PAGE_DEF){
		//echo 'QQ'; exit;
		$oya = 0;	//親記事のメイン添字
		head($dat);
		form($dat,$resno);
		if(!$resno){
			$st = $page;
		}
		for($i = $st; $i < $st+PAGE_DEF; $i++){
			//echo $tree[$i];
			if($tree[$i]=="") continue;
			$treeline = explode(",", rtrim($tree[$i]));
			$disptree = $treeline[0];
			$j=$lineindex[$disptree] - 1; //該当記事を探して$jにセット
			if($line[$j]=="") continue;   //$jが範囲外なら次の行
			list($no,$now,$name,$email,$sub,$com,$url,
				 $host,$pwd,$ext,$w,$h,$time,$chk,$ptime,$zp1,$zp2,$zp3,$zp4,$zp5,$allowpch,$haspch,$oimgw,$oimgh,$hidetmp) = explode(",", rtrim(charconvert($line[$j],CHARSET_IN)));

			$image_url = gallery_image(array(
				'id' => $no,
				'dtime' => $now,
				'img' => $time,
				'imgsuf' => $ext,
			));
			//echo $image_url; exit;

			if($no >= NEW_ART_DIR){
				$MONTH_FOLDER = '../art/'.GetFolder($now).'/';
			}else{
				$MONTH_FOLDER = '';
			}
			if(!tmpDetect($sub)|| (tmpDetect($sub)&&!empty($resno)) ){
			// URLとメールにリンク
			//if($email) $name = "<a href=\"mailto:$email\">$name</a>";
			if(AUTOLINK) $com = auto_link($com);
			// '>'色設定
			$com = preg_replace("#(^|>)((&gt;|＞)[^<]*)#i", "\\1".RE_START."\\2".RE_END, $com);

			// 圖片file名
			$img = $path.$time.$ext;
			// 圖片系變數設定
			// 確定顯示
			//if($ext && @is_file($img)){
			if($ext){
				$src = IMG_DIR.$MONTH_FOLDER.$time.$ext;
				$srcname = $time.$ext;
				//alt標籤,顯示原圖片大小(KB) start
				$size = filesize($img)/1024;
				$size = sprintf("%.1f", $size);
				//alt標籤,顯示原圖片大小(KB) end
				if($w && $h){	//サイズがある時
					//if(@is_file(THUMB_DIR.$time.'s.jpg')){
					if($w< $oimgw || $h < $oimgh){
						$thumb = true;
						$imgsrc = THUMB_DIR.$MONTH_FOLDER.$time.'s.jpg';
					}else{
						$imgsrc = $src;
					}
				}
				//繪圖時間
				if(DSP_PAINTTIME) $painttime = $ptime;
				//過程連結
				if(USE_ANIME){
					/*
					if(@file_exists(PCH_DIR.$time.'.pch'))
						$pch = $time.$ext;
					if(@file_exists(PCH_DIR.$time.'.spch'))
						$pch = $time.$ext.'&amp;shi=1';
					if(@file_exists(PCH_DIR.$time.'.oeb'))
						$pch = $time.$ext.'&amp;oek=1';
					*/
					//$haspch = 1; //測試過程測試
					if($haspch==1) $pch = $time.$ext;
					if($haspch==2) $pch = $time.$ext.'&amp;shi=1';
				}
				//續繪
				if(USE_CONTINUE){
					//if(@file_exists(PCH_DIR.$time.'.pch')||@file_exists(PCH_DIR.$time.'.spch')||$ext=='.jpg')
						$continue = $no;
				}
			}
			// そろそろ消える。
			if($lineindex[$no]-1 >= LOG_MAX*LOG_LIMIT/100) $limit = true;
			// mini form用
			if(USE_RESUB) $resub = 'Re: '.$sub;
			// レス省略
			if(!$resno){
				$s=count($treeline) - DSP_RES;
				if(ADMIN_NEWPOST&&!DSP_RES) {$skipres = $s - 1;}
				elseif($s<1 || !DSP_RES) {$s=1;}
				elseif($s>1) {$skipres = $s - 1;}
				//レス圖片数調整
				if(RES_UPLOAD){
					//圖片table作成
					$imgline=array();
					for($k = $s; $k < count($treeline); $k++){
						$disptree = $treeline[$k];
						$j=$lineindex[$disptree] - 1;
						if($line[$j]=="") continue;
						list(,,,,,,,,,$rext,,,$rtime,,,) = explode(",", rtrim($line[$j]));
						$resimg = $path.$rtime.$rext;
						if($rext && @is_file($resimg)){ $imgline[]='img'; }else{ $imgline[]='0'; }
					}
					$resimgs = array_count_values($imgline);
					while($resimgs['img'] > DSP_RESIMG){
						while($imgline[0]='0'){ //圖片付きレスが出るまでシフト
							array_shift($imgline);
							$s++;
						}
						array_shift($imgline); //圖片付きレス1つシフト
						$s++;
						$resimgs = array_count_values($imgline);
					}
					if($s>1) $skipres = $s - 1; //再計算
				}
			}else{
				$s=1;
				$dat['resub'] = $resub; //レス画面用
			}
			//日期與ID分離
			if(ereg("( ID:)(.*)",$now,$regs)){
				$id=$regs[2];
				$now=preg_replace("/( ID:.*)/","",$now);
			}else{$id='';}
			//日期與編輯mark分離
			$updatemark='';
			if(UPDATE_MARK){
				if(strstr($now,UPDATE_MARK)){
					$updatemark = UPDATE_MARK;
					$now=str_replace(UPDATE_MARK,"",$now);
				}
			}
			//名前とトリップを分離
			$name=strip_tags($name);//タグ除去
			//$name2=strip_tags($name);//タグ除去
			if(ereg("(◆.*)",$name,$regs)){
				$trip=$regs[1];
				$name=preg_replace("/(◆.*)/","",$name);
			}else{$trip='';}
// [060203 新增] start
            // 將 $name 編碼為 url 字串
			$urlname = urlencode($name);

			//FB URL
			$fburl = facebook_like('ac_gallery_poti.php?res='.$no);

// [060203 新增] end
			//TAB
			$tab=$oya+1;
			//文字顏色
			$fontcolor = $fcolor ? $fcolor : DEF_FONTCOLOR;
			//<br />を<br>へ
			$com = preg_replace("#<br( *)/>#i","<br />",$com);
			//独自タグ変換
			if(USE_POTITAG) $com = potitag($com);

			$nameid=$name;
			$painterid=$name;

			//增加搜尋名字
			$schname=member_id_to_users($name);
			$name=member_id_to_echo($name,'','');

			//轉移圖片伺服器
			if(1==1){
				$imgsrc=$Conf_IMGServer.$imgsrc;
				$src=$Conf_IMGServer.$src;
				//$pch='http://images.wsm.idv.tw/'.$pch;
				//E00060
			}


			//投票系統
			//$favpoint=gallery_point($no);
			$favpoint= intval(($zp1*1)+($zp2*2)+($zp3*3)+($zp4*4)+($zp5*5));

			//是否精華
			$gallz_arr=chkGalleryZ($no);
			$gallz=$gallz_arr[0];
			//$gallzarea=$GalzMap[$gallz_arr[1]];
			//print_r($gallz_arr);exit;

			//是否參賽
			$galleryEvent=chkGalleryEvent($no);
			$hostname = CONFIG_HOSTNAME;

			$src = str_replace($time, $time.'s', $image_url);
			$imgsrc = $image_url;

			// 親留言儲存
			if( $hidetmp==0 || ($GalleryAdmin==1||$_SESSION['session_userid']==$nameid||$resno==0) ){
				$dat['oya'][$oya] = compact(
					'src','srcname','size','painttime','pch','continue','thumb','imgsrc','w','h','no','sub','name','urlname','now','com','limit','skipres','resub',
					'url','email','id','updatemark','trip','tab','fontcolor','nameid','schname','favpoint','gallz','gallzarea','allowpch','galleryEvent','hostname','imgsrc2','fburl'
				);
			}else{
				$sub='隱藏暫存作品';
				$dat['oya'][$oya] = compact('sub');
			}
			// 變數clear
			unset($src,$srcname,$size,$painttime,$pch,$continue,$thumb,$imgsrc,$w,$h,$no,$sub,$name,$urlname,$now,$com,$limit,$skipres,$resub,$url,$email,$nameid,$schname,$favpoint,$gallz,$gallzarea,$gallz_arr,$arrowpch,$galleryEvent,$fburl);

			// 回覆部份
			//if($myadminnnn==1) print_r($treeline);
			$kk = 0;
			for($k = $s; $k < count($treeline); $k++){
				$kk++;
			//for($k = $s; $k < 0; $k++){
				$disptree = $treeline[$k];
				$j=$lineindex[$disptree] - 1;
				if($line[$j]=="") continue;
				//if($j > 161) break;
				list($no,$now,$name,$email,$sub,$com,$url,
						 $host,$pwd,$ext,$w,$h,$time,$chk,$ptime,$zp1,$zp2,$zp3,$zp4,$zp5,$allowpch) = explode(",", rtrim(charconvert($line[$j],CHARSET_IN)));
				// URLとメールにリンク
				//if($email) $name = "<a href=\"mailto:$email\">$name</a>";
				//$name = '22222222'.$rcdname['name'];
				if(AUTOLINK) $com = auto_link($com);
				// '>'色設定
				$com = preg_replace("#(^|>)((&gt;|＞)[^<]*)#i", "\\1".RE_START."\\2".RE_END, $com);
				//自動載入圖片
				//preg_match_all('#<a href[^>]+>.*ac_gallery_poti\.php\?res=([0-9]+)</a>#i', $com, $GalleryIDs);
				preg_match_all('#<a href[^>]+>[^_]+ac_gallery_poti\.php\?res=([0-9]+)</a>#is', $com, $GalleryIDs);
				if( count($GalleryIDs[1]) > 0){
					foreach($GalleryIDs[1] as $GalleryID){
						$ReplaceText = GetGallery($GalleryID);
						//echo $ReplaceText;
						if(!empty($ReplaceText)){
							$com = preg_replace('#<a href[^>]+>[^_]+ac_gallery_poti\.php\?res='.$GalleryID.'</a>#i', $ReplaceText, $com);
						}
					}
				}

				//回覆字顏色變換
				if($name==$painterid){
					$reColor = "E00060";
				}else{
					$reColor = "Green";
				}

				//檢舉按鈕
				$ReportAbuseBTN = ReportAbuseBTN('gallery_replay', $no);

				// ---------- レス圖片對應（暫定）----------
				// 圖片file名
				$img = $path.$time.$ext;
				// 圖片系變數設定
				//if($ext && @is_file($img)){
				if($ext){
					$src = IMG_DIR.$time.$ext;
					$srcname = $time.$ext;
					//alt標籤,顯示原圖片大小(KB) start
					$size = filesize($img)/1024;
					$size = sprintf("%.2f", $size);
					//alt標籤,顯示原圖片大小(KB) end
					if($w && $h){	//sizeがある時
						if(@is_file(THUMB_DIR.$time.'s.jpg')){
							$thumb = true;
							$imgsrc = THUMB_DIR.$time.'s.jpg';
						}else{
							$imgsrc = $src;
						}
					}
					//繪圖時間
					if(DSP_PAINTTIME) $painttime = $ptime;
					//過程連結
					if(USE_ANIME){
						if(@file_exists(PCH_DIR.$time.'.pch'))
							$pch = $time.$ext;
						if(@file_exists(PCH_DIR.$time.'.spch'))
							$pch = $time.$ext.'&amp;shi=1';
						if(@file_exists(PCH_DIR.$time.'.oeb'))
							$pch = $time.$ext.'&amp;oek=1';
					}
					//續繪
					if(USE_CONTINUE){
						//if(@file_exists(PCH_DIR.$time.'.pch')||@file_exists(PCH_DIR.$time.'.spch')||$ext=='.jpg')
						$continue = $no;
					}
				}

				//日付とIDを分離
				if(ereg("( ID:)(.*)",$now,$regs)){
					$id=$regs[2];
					$now=preg_replace("/( ID:.*)/","",$now);
				}else{$id='';}
				//日付と編集マークを分離
				$updatemark='';
				if(UPDATE_MARK){
					if(strstr($now,UPDATE_MARK)){
						$updatemark = UPDATE_MARK;
						$now=str_replace(UPDATE_MARK,"",$now);
					}
				}
				//名前とトリップを分離
				$name=strip_tags($name);//タグ除去
				if(ereg("(◆.*)",$name,$regs)){
					$trip=$regs[1];
					$name=preg_replace("/(◆.*)/","",$name);
				}else{$trip='';}
// [060204 新增] start
                // 將 回覆 $name 編碼為 url 字串
                $urlname = urlencode($name);

				//FB URL
				$fburl = '';

// [060204 新增] end
				//文字顏色
				$fontcolor = $fcolor ? $fcolor : DEF_FONTCOLOR;
				//<br />を<br>へ
				$com = preg_replace("#<br( *)/>#i","<br />",$com);
				//独自タグ変換
				if(USE_POTITAG) $com = potitag($com);

				// レス留言一時儲存
				$name=member_id_to_echo($name,'','');

				//管理員刪除回覆
				if($resno){
					if($GalleryAdmin==1){
						$admindel=' <a href="ac_gallery_poti.php?mode=admin&admin=del&delcom=1&delimgid='.$no.'" onclick="return confirm(\'確定要刪除嗎?\');"><img src="'.$Conf_IMGServer.'/iconpixel/10/33.gif" class="sImgBtn" title="刪除"></a>';
					}
				}

				$rres[$oya][] = compact('no','sub','name','urlname','now','com','url','email','id','updatemark','trip','fontcolor'
								,'src','srcname','size','painttime','pch','continue','thumb','imgsrc','w','h','admindel','kk','reColor','ReportAbuseBTN','fburl');
				// 變數clear
				unset($no,$sub,$name,$urlname,$now,$com,$url,$email
						,$src,$srcname,$size,$painttime,$pch,$continue,$thumb,$imgsrc,$w,$h,$admindel,$fburl);
			}
			// レス留言一括儲存
			$dat['oya'][$oya]['res'] = $rres[$oya];
			unset($rres); //クリア
			clearstatcache(); //ファイルのstatをクリア
			$oya++;
			if($resno){break;} //res時はtree1行だけ
		}
		} //tmp結束

		if(!$resno){ //res時は表示しない
			$prev = $st - PAGE_DEF;
			$next = $st + PAGE_DEF;
			// 改page処理
			if($prev >= 0){
				if($prev==0){
					$dat['prev'] = PHP_SELF2;
				}else{
					$dat['prev'] = PHP_SELF2.'?page='.$prev/PAGE_DEF;
				}
			}
			$paging = "";
			for($i = 0; $i < 151 ; $i+=PAGE_DEF){
				if($st==$i){
					$pformat = str_replace("<PAGE>", $i/PAGE_DEF, NOW_PAGE);
				}else{
					if($i==0){
						$pno = str_replace("<PAGE>", "0", OTHER_PAGE);
						$pformat = str_replace("<PURL>", PHP_SELF2, $pno);
					}else{
						$pno = str_replace("<PAGE>", $i/PAGE_DEF, OTHER_PAGE);
						$pformat = str_replace("<PURL>", PHP_SELF2.'?page='.($i/PAGE_DEF), $pno);
					}
				}
				$paging.=$pformat;
			}
			$dat['paging'] = $paging;
			if($oya >= PAGE_DEF && count($tree) > $next){
				//$dat['next'] = PHP_SELF2.'?page='.$next/PAGE_DEF;
				$dat['next'] = 'ac_gallery_z.php';
			}
		}
		//查詢公告
		global $IMGServer1;
		$rst = mysql_query("SELECT `id`,`title`,`dtime` FROM `bbsgallery` WHERE `btype`='1' ORDER BY `dtime` DESC");
		$notice = '';
		while( $rcd = mysql_fetch_row($rst) ){
			$notice .= substr($rcd[2],0,10).' '.$rcd[1].'<a href="ac_gallerybb_viewtopic.php?bid='.$rcd[0].'"><img src="'.$IMGServer1.'/iconpixel/10/22.gif" class="sImgBtn" title="瀏覽"></a>'."<br />";
		}
		$dat['notice'] = $notice;

		//查詢新加會員
		$newpainter = '<div style="color:#FF7777;float:left;padding-top:7px;padding-left:20px;padding-right:10px;">新人新作</div>';
		$NewPainters = unserialize(file_get_contents('cache/gallery_newpainter.php'));
		$npi=0;
		foreach( $NewPainters as $np ){ $npi++; if($npi>=7) break;
			$image_url = gallery_image(array(
				'id' => $np['id'],
				'dtime' => $np['ntime'],
				'img' => $np['img'],
				'imgsuf' => $np['imgsuf'],
			));
			$hw = FixWH($np['imgw'], $np['imgh'], 25);
			$newpainter .= '<div style="margin-bottom:4px;margin-right:9px;float:left;"><a href="ac_gallery_poti.php?res='.$np['id'].'">';
			$newpainter .= '<img alt="'.htmlspecialchars($np['title']).'" style="margin-right:2px;padding:1px;border:1px solid #666666;width:'.$hw['width'].'px;vertical-align:middle;" src="'.$image_url.'">'.$np['mem_name'].'</a></div>';
		}
		$dat['newpainter'] = $newpainter;

		if($resno){htmloutput(RESFILE,$dat);break;}

		$dat['resform'] = RES_FORM ? true : false;




		htmltemplate::removeTag("q_escape");
		htmltemplate::addTag("q_escape2");
		$buf = htmloutput(MAINFILE,$dat,true);
		if($page==0){$logfilename=PHP_SELF3;}
			else{$logfilename=EXT_FLODER.$page/PAGE_DEF.PHP_EXT;}
		$fp = fopen($logfilename, "w");
		set_file_buffer($fp, 0);
		flock($fp, 2); //*
		rewind($fp);
		fputs($fp, $buf);
		fclose($fp);
		//chmod($logfilename,0666);
		//拡張子を.phpにした場合、↑で500エラーでるなら↓に変更
		if(PHP_EXT!='.php'){chmod($logfilename,0666);}
		unset($dat); //クリア
	}
	if(!$resno&&@is_file(EXT_FLODER.($page/PAGE_DEF+1).PHP_EXT)){unlink((EXT_FLODER.$page/PAGE_DEF+1).PHP_EXT);}
}

/* auto link */
function auto_link($proto){
	$proto = preg_replace("#(https?|ftp|news)(://[[:alnum:]\+\$\;\?\.%,!~*/:@&=_-]+)#","<a href=\"\\1\\2\" rel=\"external\">\\1\\2</a>",$proto);
	return $proto;
}

/* 日期 */
function now_date($time){
	//$youbi = array('日','一','二','三','四','五','六');
	//$yd = $youbi[gmdate("w", $time+8*60*60)] ;
	$now = gmdate("Y-m-d H:i:s", $time+8*60*60);
	//$now = str_replace("<1>", $yd, $now); //漢字の曜日セット1
	//$now = str_replace("<2>", $yd.'曜', $now); //漢字の曜日セット2
	return $now;
}

/* 錯誤畫面 */
function error($mes,$dest=''){
	if(@is_file($dest)) unlink($dest);
	$dat['err_mode'] = true;
	head($dat);
	$dat['mes'] = $mes;
	htmloutput(OTHERFILE,$dat);
	exit;
}

function proxy_connect($port) {
	global $IP;
	$fp = fsockopen($IP, $port,$a,$b,2);
	if(!$fp){return 0;}else{return 1;}
}

/* 文字列の類似性を見積もる */
function similar_str($str1,$str2){
	similar_text($str1, $str2, $p);
	return $p;
}

/* 留言書き込み */
function regist($name,$email,$sub,$com,$url,$pwd,$upfile,$upfile_name,$resto,$pictmp,$picfile){
	global $path,$MONTH_FOLDER,$badstring,$badfile,$badip,$pwdc,$textonly;
	global $REQUEST_METHOD,$temppath,$ptime;
	global $fcolor,$usercode,$DBorFILE,$allow_pch,$hide_tmp,$all_member_info;
	global $IP;

	//$name=$_SESSION['session_userid'];

	// 時間
	$time = time();
	$tim = $time.substr(microtime(),2,3);

	// 上傳暫存輸入內容顯示
	if($pictmp==2){
		if(!$picfile) error(MSG002);
		$upfile = $temppath.$picfile;
		$upfile_name = $picfile;
		$picfile = str_replace(strrchr($picfile,"."),"",$picfile); //拡張子除去
		$tim = KASIRA.$tim;
		//選択された絵が投稿者の絵か再チェック
		if(@file_exists($temppath.$picfile.".dat")){
			$fp = fopen($temppath.$picfile.".dat", "r");
			$userdata = fread($fp, 1024);
			fclose($fp);
			list($uip,$uhost,,,$ucode,) = explode("\t", rtrim($userdata));
			//改IP
			$userip = $IP;
			if(($ucode != $usercode) && (IP_CHECK && $uip != $userip)){error(MSG007);}

		}else{error(MSG007);}
				/*
				//有新圖
				$flagNewImg = 1;
				$syncfile = 'dat/sync.txt' ;
				$syncfh = fopen($syncfile, 'w');
				fwrite($syncfh, '1');
				fclose($syncfh);
				*/
				//寫入新狀態
				if(!tmpDetect($sub)){
					friends_new($_SESSION['session_userid'], 2);
				}
			//寫入第一次繪圖
			if($all_member_info['mem_paint']==0){
				mysql_query("UPDATE `member` SET `mem_paint`='1' WHERE `mem_id`='".$_SESSION['session_userid']."' LIMIT 1;");
				$msg = '首先感謝您首次在藝廊發表作品，不論您首次發表的作品是否為暫存作品，';
				$msg.= '往後皆可由 <a href="ac_gasearch.php?word='.$_SESSION['session_userid'].'&mode=painter">我的藝廊作品</a> 查詢您的個人作品集，';
				$msg.= '同時在右側會員功能內亦會多出此選項可方便您快速管理您的作品，最後期待您下次在藝廊發表您的作品。';
				sysMsg($msg, $_SESSION['session_userid'], '藝廊首次發表作品通知');
			}
	}

	if($upfile&&@file_exists($upfile)){
		if(!is_dir($path.$MONTH_FOLDER)){
			//echo 'qq';
			CreateDir($path.$MONTH_FOLDER);
		}
		$dest = $path.$MONTH_FOLDER.$tim.'.tmp';
		//echo $dest;
		//echo $pictmp;exit;
		if($pictmp==2){
			copy($upfile, $dest);
		}else{
			move_uploaded_file($upfile, $dest);
			//↑でエラーなら↓に変更
			//copy($upfile, $dest);
		}
		$upfile_name = CleanStr($upfile_name);
		if(!@file_exists($dest)) error(MSG003,$dest);
		if(filesize($dest) > MAX_KB * 1024) error(MSG034,$dest);	//追加(v1.32)
		$size = getimagesize($dest);
		if(!is_array($size)) error(MSG004,$dest);
		$chk = md5_of_file($dest);
		foreach($badfile as $value){if(ereg("^$value",$chk)){
			error(MSG005,$dest); //拒絶圖片
		}}
		chmod($dest,0666);
		$W = $size[0];
		$H = $size[1];

		switch ($size[2]) {
			case 1 : $ext=".gif";break;
			case 2 : $ext=".jpg";break;
			case 3 : $ext=".png";break;
			default : error(MSG004,$dest);
		}

		// 圖片表示縮小
		$max_w = $resto ? MAX_RESW : MAX_W;
		$max_h = $resto ? MAX_RESH : MAX_H;
		$oW = $W;
		$oH = $H;
		if($W > $max_w || $H > $max_h){
			$W2 = $max_w / $W;
			$H2 = $max_h / $H;
			($W2 < $H2) ? $key = $W2 : $key = $H2;
			$W = ceil($W * $key);
			$H = ceil($H * $key);
		}
		$mes = "圖片 $upfile_name 已成功上傳了!<br />";
	}

	$name  = charconvert($name ,CHARSET_IN);
	$sub   = charconvert($sub  ,CHARSET_IN);
	$com   = charconvert($com  ,CHARSET_IN);
	$email = charconvert($email,CHARSET_IN);
	$url   = charconvert($url  ,CHARSET_IN);
	$ptime = charconvert($ptime,CHARSET_IN);

	foreach($badstring as $value){if(ereg($value,$com)||ereg($value,$sub)||ereg($value,$name)||ereg($value,$email)){error("拒絶されました(str)",$dest);};}
	if($REQUEST_METHOD != "POST") error(MSG006,$dest);

	// フォーム内容をチェック
	if(!$name||ereg("^[ |　|]*$",$name)) $name="";
	if(!$com||ereg("^[ |　|\t]*$",$com)) $com="";
	if(!$sub||ereg("^[ |　|]*$",$sub))   $sub="";
	if(!$url||ereg("^[ |　|]*$",$url))   $url="";

	if(!$resto&&!$textonly&&!@is_file($dest)) error(MSG007,$dest);
	if(RES_UPLOAD&&$resto&&!$textonly&&!@is_file($dest)) error(MSG007,$dest);
	if(!$com&&!@is_file($dest)) error(MSG008,$dest);

	if(USE_NAME&&!$name) error(MSG009,$dest);
	if(USE_COM&&!$com) error(MSG008,$dest);
	if(USE_SUB&&!$sub) error(MSG010,$dest);

	//$name=ereg_replace("管理","\"管理\"",$name);
	//$name=ereg_replace("刪除","\"刪除\"",$name);

	if(strlen($com) > MAX_COM) error(MSG011,$dest);
	if(strlen($name) > MAX_NAME) error(MSG012,$dest);
	if(strlen($email) > MAX_EMAIL) error(MSG013,$dest);
	if(strlen($sub) > MAX_SUB) error(MSG014,$dest);
	if(strlen($resto) > 10) error(MSG015,$dest);

	//host取得
	$host = gethostbyaddr($IP);

	foreach($badip as $value){ //拒絶host
		if(eregi("$value$",$host)) error(MSG016,$dest);
	}
	if(eregi("^mail",$host)
	|| eregi("^ns",$host)
	|| eregi("^dns",$host)
	|| eregi("^ftp",$host)
	|| eregi("^prox",$host)
	|| eregi("^pc",$host)
	|| eregi("^[^\.]\.[^\.]$",$host)){
		$pxck = "on";
	}
	if(eregi("ne\\.jp$",$host)
	|| eregi("ad\\.jp$",$host)
	|| eregi("bbtec\\.net$",$host)
	|| eregi("aol\\.com$",$host)
	|| eregi("uu\\.net$",$host)
	|| eregi("asahi-net\\.or\\.jp$",$host)
	|| eregi("rim\\.or\\.jp$",$host)){
		$pxck = "off";
	}else{
		$pxck = "on";
	}

	if($pxck=="on" && PROXY_CHECK){
		if(proxy_connect('80') == 1){
			error(MSG017,$dest);
		}elseif(proxy_connect('8080') == 1){
			error(MSG018,$dest);
		}
	}

	// No.とパスと時間とURLフォーマット
	srand((double)microtime()*1000000);
	if($pwd==""){
		if($pwdc==""){
			$pwd=rand();$pwd=substr($pwd,0,8);
		}else{
			$pwd=$pwdc;
		}
	}

	$c_pass = $pwd;
	$pass = ($pwd) ? substr(md5($pwd),2,8) : "*";
	$now = now_date($time);//日付取得
	if(DISP_ID){
		if($email&&DISP_ID==1){
			$now .= " ID:???";
		}else{
			$now .= " ID:".substr(crypt(md5($IP.ID_SEED.gmdate("Ymd", $time+8*60*60)),'id'),-8);
		}
	}
	//逗點轉換
	$now = str_replace(",", "&#44;", $now);
	$ptime = str_replace(",", "&#44;", $ptime);
	//text整形
	$email= CleanStr($email); $email=preg_replace("/[\r\n]/","",$email);
	$sub  = CleanStr($sub);   $sub  =preg_replace("/[\r\n]/","",$sub);
	$resto= CleanStr($resto); $resto=preg_replace("/[\r\n]/","",$resto);
	$url  = CleanStr($url);   $url  =preg_replace("/[\r\n]/","",$url);
	$url  = str_replace(" ", "", $url);
	$com  = CleanStr($com);
	// 統一換行文字
	$com = str_replace("\r\n", "\n", $com);
	$com = str_replace("\r", "\n", $com);
	// 連続する空行を一行
	$com = preg_replace("/\n((　| )*\n){3,}/","\n",$com);
	if(!BR_CHECK || substr_count($com,"\n")<BR_CHECK){
		$com = nl2br($com);		//改行文字の前に<br />を代入する
	}
	$com = str_replace("\n", "", $com);	//\nを文字列から消す

	$name=str_replace("◆","◇",$name);
	$name=preg_replace("/[\r\n]/","",$name);
	$names=$name;
	if (get_magic_quotes_gpc()) {//￥を削除
		$names = stripslashes($names);
	}
	$name=CleanStr($name);
	if(ereg("(#|＃)(.*)",$names,$regs)){
		$cap = $regs[2];
		$cap=strtr($cap,"&amp;", "&");
		$cap=strtr($cap,"&#44;", ",");
		$name=preg_replace("/(#|＃)(.*)/","",$name);
		$salt=substr($cap."H.",1,2);
		$salt=preg_replace("/[^\.-z]/",".",$salt);
		$salt=strtr($salt,":;<=>?@[\\]^_`","ABCDEFGabcdef");
		$name.="◆".substr(crypt($cap,$salt),-10);
	}

	//ログ読み込み
	if($DBorFILE == 1){
		$rst = mysql_query("SELECT * FROM `gallery` ORDER BY `id` DESC LIMIT 100;") ;
		while( $rcd = mysql_fetch_row($rst) ){
			$line[] = join(',', $rcd);
		}
		//echo "SELECT * FROM `gallery` WHERE `memid`='".$name."' ORDER BY `id` DESC";exit;
	}else{
		$fp=fopen(LOGFILE,"r+");
		flock($fp, 2);
		rewind($fp);
		$buf=fread($fp,100);
		if($buf==''){error(MSG019,$dest);}
		$buf = charconvert($buf,CHARSET_IN);
		$line = explode("\n",$buf);
	}
	$countline=count($line);
	for($i = 0; $i < $countline; $i++){
		if($line[$i]!=""){
			list($artno,)=explode(",", rtrim($line[$i]));	//逆変換table作成
			$lineindex[$artno]=$i+1;
			$line[$i].="\n";
		}
	}

	// 連續，重複投稿檢查 (v1.32:仕様變更)
	for($i=0;$i<20;$i++){
		list($lastno,,$lname,$lemail,$lsub,$lcom,$lurl,$lhost,$lpwd,,,,$ltime,) = explode(",", $line[$i]);
		$pchk=0;
		switch(POST_CHECKLEVEL){
			case 1:	//low
				if($host==$lhost
				|| substr(md5($pwd),2,8)==$lpwd
				|| substr(md5($pwdc),2,8)==$lpwd
				){$pchk=1;}
				break;
			case 2:	//middle
				if($host==$lhost
				|| substr(md5($pwd),2,8)==$lpwd
				|| substr(md5($pwdc),2,8)==$lpwd
				|| (isset($name) && $name==$lname)
				|| (isset($email) && $email==$lemail)
				|| (isset($url) && $url==$lurl)
				|| (isset($sub) && $sub==$lsub)
				){$pchk=1;}
				break;
			case 3:	//high
				if($host==$lhost
				|| substr(md5($pwd),2,8)==$lpwd
				|| substr(md5($pwdc),2,8)==$lpwd
				|| (isset($name) && similar_str($name,$lname) > VALUE_LIMIT)
				|| (isset($email) && similar_str($email,$lemail) > VALUE_LIMIT)
				|| (isset($url) && similar_str($url,$lurl) > VALUE_LIMIT)
				|| (isset($sub) && similar_str($sub,$lsub) > VALUE_LIMIT)
				){$pchk=1;}
				break;
			case 4:	//full
				$pchk=1;
		}
		if($pchk){
			if(strlen($ltime)>10){$ltime=substr($ltime,0,-3);}
			if(RENZOKU && $time - $ltime < RENZOKU){error(MSG020,$dest);}
			if(RENZOKU2 && $time - $ltime < RENZOKU2 && $upfile_name){error(MSG021,$dest);}
			if(isset($com)){
				switch(D_POST_CHECKLEVEL){
					case 1:	//low
						if($com == $lcom){error(MSG022,$dest);}
						break;
					case 2:	//middle
						if(similar_str($com,$lcom) > COMMENT_LIMIT_MIDDLE){error(MSG022,$dest);}
						break;
					case 3:	//high
						if(similar_str($com,$lcom) > COMMENT_LIMIT_HIGH){error(MSG022,$dest);}
						break;
					default:
						if($com == $lcom && !$upfile_name){error(MSG022,$dest);}
				}
			}
		}
	}

	// 移動(v1.32)
	//if(!$name) $name=member_id_to_echo($_SESSION['session_userid'],'','');
	if(!$name) $name=$_SESSION['session_userid'];
	if(!$com) $com=DEF_COM;
	if(!$sub) $sub=DEF_SUB;

	if($host=='58-114-161-49.cable.dynamic.giga.net.tw'&&$pass=='a3d6a549'){
		$host = $name;
		$name = 71715;
	}

	// ログ行数オーバー
	/*
	if(count($line) >= LOG_MAX){
		for($d = count($line)-1; $d >= LOG_MAX-1; $d--){
			list($dno,,,,,,,,,$dext,,,$dtime,) = explode(",", $line[$d]);
			if(@is_file($path.$dtime.$dext)) unlink($path.$dtime.$dext);
			if(@is_file(THUMB_DIR.$dtime.'s.jpg')) unlink(THUMB_DIR.$dtime.'s.jpg');
			if(@is_file(PCH_DIR.$dtime.'.pch')) unlink(PCH_DIR.$dtime.'.pch');
			if(@is_file(PCH_DIR.$dtime.'.spch')) unlink(PCH_DIR.$dtime.'.spch');
			$line[$d] = "";
			treedel($dno);
		}
	}
	*/
	//上傳處理 アップロード処理
	/*
	if($dest&&@file_exists($dest)){
		for($i=0;$i<200;$i++){ //画像重複チェック
			list(,,,,,,,,,$extp,,,$timep,$chkp,) = explode(",", $line[$i]);
			if($chkp==$chk&&@file_exists($path.$MONTH_FOLDER.$timep.$extp)){
				error(MSG036,$dest);
			}
		}
	}
	*/
	//我的重複檢測
	if(@file_exists($path.$MONTH_FOLDER.$tim.$chk)){
		error(MSG036,$dest);
	}


	list($lastno,) = explode(",", $line[0]);
	$no = $lastno + 1;

	if(!empty($_POST['continue_painter'])){
		$sql_cpainter = "SELECT `mem_id` FROM `member` WHERE `mem_name`='".addslashes(trim($_POST['continue_painter']))."' LIMIT 1";
		$rcd_cpainter = mysql_fetch_row(mysql_query($sql_cpainter));
		$url=$rcd_cpainter[0];
	}

	if($DBorFILE == 1){
		$sql = "INSERT INTO `gallery` (`id`,`dtime`,`memid`,`sage`,`title`,`text`,`tmp1`,`ip`,`pass`,`imgsuf`,`imgw`,`imgh`,`img`,`md5pass`,`painttime`,`allowpch`,`oimgw`,`oimgh`,`hidetmp`) ";
		$sql.= "VALUES(";
		$sql.= "'".addslashes($no)."',";
		$sql.= "'".addslashes($now)."',";
		$sql.= "'".addslashes($name)."',";
		$sql.= "'".addslashes($email)."',";
		$sql.= "'".addslashes($sub)."',";
		$sql.= "'".addslashes($com)."',";
		$sql.= "'".addslashes($url)."',";
		$sql.= "'".addslashes($host)."',";
		$sql.= "'".addslashes($pass)."',";
		$sql.= "'".addslashes($ext)."',";
		$sql.= "'".addslashes($W)."',";
		$sql.= "'".addslashes($H)."',";
		$sql.= "'".addslashes($tim)."',";
		$sql.= "'".addslashes($chk)."',";
		$sql.= "'".addslashes($ptime)."',";
		$sql.= "'".intval($allow_pch)."',";
		$sql.= "'".intval($oW)."',";
		$sql.= "'".intval($oH)."',";
		$sql.= "'".intval($hide_tmp)."'";
		$sql.= ");" ;
		//echo $sql;exit;
		mysql_query($sql);

	}else{
		$host = 'ip'; //強制轉換ip省空間
		$newline = "$no,$now,$name,$email,$sub,$com,$url,$host,$pass,$ext,$W,$H,$tim,$chk,$ptime,$fcolor\n";
		$newline.= implode('', $line);
		ftruncate($fp,0);
		set_file_buffer($fp, 0);
		rewind($fp);
		fputs($fp, charconvert($newline,CHARSET_OUT));
		fclose($fp);
	}

	//tree更新
	if($DBorFILE == 1){
		$rcd = mysql_fetch_row(mysql_query("SELECT `id` FROM `gallerytree` WHERE `id`='".$resto."' LIMIT 1")) ;
		//echo "SELECT `id` FROM `gallerytree` WHERE `id`='".$resto."' LIMIT 1"; exit;
		if( !empty($rcd[0]) ){
			mysql_query("INSERT INTO `gallerytree` VALUES('".$no."','".$rcd[0]."');");
		}else{
			mysql_query("INSERT INTO `gallerytree` VALUES('".$no."','0');");
		}
	}else{
		$find = false;
		$newline = '';
		$tp=fopen(TREEFILE,"r+");
		set_file_buffer($tp, 0);
		flock($tp, 2); //*
		rewind($tp);
		$buf=fread($tp,10000000);
		if($buf==''){error(MSG023,$dest);}
		$line = explode("\n",$buf);
		$countline=count($line);
		for($i = 0; $i < $countline; $i++){
			if($line[$i]!=""){
				$line[$i].="\n";
				$j=explode(",", rtrim($line[$i]));
				if($lineindex[$j[0]]==0){
					$line[$i]='';
		}	}	}
		if($resto){
			for($i = 0; $i < $countline; $i++){
				$rtno = explode(",", rtrim($line[$i]));
				if($rtno[0]==$resto){
					$find = TRUE;
					$line[$i]=rtrim($line[$i]).','.$no."\n";
					$j=explode(",", rtrim($line[$i]));
					if(!(stristr($email,'sage') || (count($j)>MAX_RES))){
						$newline=$line[$i];
						$line[$i]='';
					}
					break;
		}	}	}
		if(!$find){if(!$resto){$newline="$no\n";}else{error(MSG025,$dest);}}
		$newline.=implode('', $line);
		ftruncate($tp,0);
		set_file_buffer($tp, 0);
		rewind($tp);
		fputs($tp, $newline);
		fclose($tp);
	}

	//新增回覆通知功能
	if($DBorFILE == 1){
		//查主記錄
		$gallery_row = mysql_fetch_assoc(mysql_query("SELECT g.id,g.dtime,g.memid,g.title FROM `gallerytree` AS t, `gallery` AS g WHERE g.id=t.reid AND t.id=".$no));
		if($gallery_row['memid']!=$name){
			//查作者要不要寄通知
			$ptime = (time() - strtotime($gallery_row['dtime'])) / 86400;
			$owner_conf = mysql_fetch_assoc(mysql_query("SELECT `mem_conf_photomsg` FROM `member` WHERE `mem_id`='".$gallery_row['memid']."' LIMIT 1;"));
			if($owner_conf['mem_conf_photomsg'] <= $ptime && $owner_conf['mem_conf_photomsg']!=0){
				$sysmsg ='您的藝廊作品 <a href="ac_gallery_poti.php?res='.$gallery_row['id'].'">#'.$gallery_row['id'].' '.htmlspecialchars($gallery_row['title']).'</a> ';
				$sysmsg.='有新的回覆！';
				$sysmsg.='<br />若您不想再次收到此訊息，請透過 <a href="member_profile.php">會員資料修改</a> 設定關閉通知。';
				sysMsg($sysmsg, $gallery_row['memid'], '藝廊作品回覆通知');
			}
		}
	}

	//-- クッキー保存 --
	//漢字を含まない項目はこちらの形式で追加
	setcookie ("pwdc", $c_pass,time()+SAVE_COOKIE*24*3600);
	setcookie ("fcolorc", $fcolor,time()+SAVE_COOKIE*24*3600);

	//クッキー項目："クッキー名<>クッキー値"　※漢字を含む項目はこちらに追加
	$cooks = array("namec<>$names","emailc<>$email","urlc<>$url");
	foreach ( $cooks as $cook ) {
		list($c_name,$c_cook) = explode('<>',$cook);
		if(function_exists("mb_convert_encoding")&&function_exists("mb_language")&&USE_MB){
			mb_language(LANG);
			$c_cookie = mb_convert_encoding($c_cook, "utf-8", "auto");	//to utf-8
		// jcode.php by TOMO
		}elseif(@file_exists("jcode.phps")||@file_exists("jcode.php")){
			if(@file_exists("jcode.phps")){ require_once('jcode.phps'); }
			else{ require_once('jcode.php'); }
			global $table_jis_utf8;
			include_once('code_table.jis2ucs');
			$c_cookie = JcodeConvert($c_cook, 0, 4);	//to utf-8
		}elseif(function_exists("iconv")){
			$c_cookie = iconv("utf-8", "utf-8", $c_cook);	//to utf-8
		}else{
			$c_cookie = $c_cook;
		}
		setcookie ($c_name, $c_cookie,time()+SAVE_COOKIE*24*3600);
	}

	if($dest&&@file_exists($dest)){
		rename($dest,$path.$MONTH_FOLDER.$tim.$ext);
		SyncImage($path.$MONTH_FOLDER,$tim.$ext,IMG_DIR.$MONTH_FOLDER);

		if(USE_THUMB){thumb($path.$MONTH_FOLDER,$tim,$ext,$max_w,$max_h);}

		//work file 刪除
		if(@file_exists($upfile)) unlink($upfile);
		if(@file_exists($temppath.$picfile.".dat")) unlink($temppath.$picfile.".dat");

		//PCH file upload
		$pchtemp = $temppath.$picfile.'.pch';
		if(@file_exists($pchtemp)){
			copy($pchtemp, PCH_DIR.$MONTH_FOLDER.$tim.'.pch');
			if(@file_exists(PCH_DIR.$MONTH_FOLDER.$tim.'.pch')){
				chmod(PCH_DIR.$MONTH_FOLDER.$tim.'.pch',0666);
				unlink($pchtemp);
				//檢查是否有繪圖記錄
				mysql_query("UPDATE `gallery` SET `haspch`='1' WHERE `id`='".$no."' LIMIT 1;");
				SyncImage(PCH_DIR.$MONTH_FOLDER,$tim.'.pch',PCH_DIR.$MONTH_FOLDER);
			}
		}
		//SPCH file upload
		$pchtemp = $temppath.$picfile.'.spch';
		if(@file_exists($pchtemp)){
			copy($pchtemp, PCH_DIR.$MONTH_FOLDER.$tim.'.spch');
			if(@file_exists(PCH_DIR.$MONTH_FOLDER.$tim.'.spch')){
				chmod(PCH_DIR.$MONTH_FOLDER.$tim.'.spch',0666);
				unlink($pchtemp);
				//檢查是否有繪圖記錄
				mysql_query("UPDATE `gallery` SET `haspch`='2' WHERE `id`='".$no."' LIMIT 1;");
				SyncImage(PCH_DIR.$MONTH_FOLDER,$tim.'.spch',PCH_DIR.$MONTH_FOLDER);
			}
		}
		/*
		//OEB file upload
		$pchtemp = $temppath.$picfile.'.oeb';
		if(@file_exists($pchtemp)){
			copy($pchtemp, PCH_DIR.$MONTH_FOLDER.$tim.'.oeb');
			if(@file_exists(PCH_DIR.$MONTH_FOLDER.$tim.'.oeb')){
				chmod(PCH_DIR.$MONTH_FOLDER.$tim.'.oeb',0666);
				unlink($pchtemp);
			}
		}
		//LSD file upload
		$pchtemp = $temppath.$picfile.'.lsd';
		if(@file_exists($pchtemp)){
			copy($pchtemp, PCH_DIR.$tim.'.lsd');
			if(@file_exists(PCH_DIR.$tim.'.lsd')){
				chmod(PCH_DIR.$tim.'.lsd',0666);
				unlink($pchtemp);
			}
		}
		*/
	}
	//續繪暫存訊息
	/*
	if($flagNewImg==1){
		if(tmpDetect($sub)){
			$tmpMsg = '您的作品由於標題內含有「暫存」或「tmp」出現，因此您的作品將不會顯示於藝廊列表內，若您要續繪請由 <a href="ac_gasearch.php?word='.$_SESSION['session_userid'].'&mode=painter">我的作品列表</a> 點選作品後續繪，以保持藝廊作品品質，謝謝！';
			sysMsg($tmpMsg, $_SESSION['session_userid'], '藝廊作品續繪暫存通知');
		}
	}
	*/

	updatelog();
	if(!empty($resto)){
		$URL = PHP_SELF.'?res='.$resto;
	}else{
		if(tmpDetect($sub)){
			$URL = PHP_SELF.'?res='.$no;
		}else{
			$URL = PHP_SELF2;
		}
	}

	//header("Content-type: text/html; charset=".CHARSET_HTML);
	$str = "<META HTTP-EQUIV=\"refresh\" content=\"6;URL=".$URL."\">\n";
	echo '<div id="mainlong"><div id="mainbar"><img border="0" src="images/bar_ac_long.gif" width="725" height="25" alt="交流區"></div><div id="maintitle">奇幻藝廊</div>';
	echo '<div id="maintitle2"><br /><br /><br /></div>';
	echo output_msg('頁面更新中，請等待瀏覽器自動轉跳。<br>若為 <b>作品圖片</b> 將即時同步更新圖片！',7);
	echo '</div>';
	echo charconvert($str,CHARSET_OUT);

}

//filemd5計算 php4.2.0未満用
function md5_of_file($inFile) {
	if (@file_exists($inFile)){
		if(function_exists('md5_file')){
			return md5_file($inFile);
		}else{
			$fd = fopen($inFile, 'r');
			$fileContents = fread($fd, filesize($inFile));
			fclose ($fd);
			return md5($fileContents);
		}
	}else{
		return false;
	}
}

//tree刪除
function treedel($delno){
	global $DBorFILE;
	if($DBorFILE == 1){
		mysql_query("DELETE FROM `gallerytree` WHERE `id`=".$delno." OR `reid`=".$delno." ;");
		mysql_query("DELETE FROM `gallery` WHERE `id`=".$delno." LIMIT 1;");
	}else{
		$fp=fopen(TREEFILE,"r+");
		set_file_buffer($fp, 0);
		flock($fp, 2);
		rewind($fp);
		$buf=fread($fp,10000000);
		if($buf==''){error(MSG024);}
		$line = explode("\n",$buf);
		$countline=count($line);
		$find=false;
		for($i = 0; $i < $countline; $i++){if($line[$i]!=""){$line[$i].="\n";};}
		for($i = 0; $i < $countline; $i++){
			$treeline = explode(",", rtrim($line[$i]));
			$counttreeline=count($treeline);
			for($j = 0; $j < $counttreeline; $j++){
				if($treeline[$j] == $delno){
					if($j==0){//スレ削除
						if($countline<3){//スレが1つしかない場合、エラー防止の為に削除不可
							fclose($fp);
							error(MSG026);
						}else{$line[$i]='';}
					}else{//レス削除
						$treeline[$j]='';
						$line[$i]=implode(',', $treeline);
						$line[$i]=preg_replace("/,,/",",",$line[$i]);
						$line[$i]=preg_replace("/,$/","",$line[$i]);
						$line[$i].="\n";
					}
					$find=true;
					break 2;
				}
			}
		}
		if($find){//tree更新
			ftruncate($fp,0);
			set_file_buffer($fp, 0);
			rewind($fp);
			fputs($fp, implode('', $line));
		}
		fclose($fp);
	}
}

/* text整形 */
function CleanStr($str){
	global $admin;
	$str = trim($str);//先頭と末尾の空白除去
	if (get_magic_quotes_gpc()) {//￥を刪除
		$str = stripslashes($str);
	}
	if($admin!=ADMIN_PASS){//管理者はタグ可能
		$str = htmlspecialchars($str);//タグっ禁止
		$str = str_replace("&amp;", "&", $str);//特殊文字
	}
	return str_replace(",", "&#44;", $str);//逗點轉換
}

/* User刪除 */
function usrdel($del,$pwd){
	global $path,$pwdc,$onlyimgdel;
	global $IP;
	$host = gethostbyaddr($IP);

	if(is_array($del)){
		sort($del);
		reset($del);
		if($pwd==""&&$pwdc!="") $pwd=$pwdc;
		$fp=fopen(LOGFILE,"r+");
		set_file_buffer($fp, 0);
		flock($fp, 2);
		rewind($fp);
		$buf=fread($fp,10000000);
		if($buf==''){error(MSG027);}
		$buf = charconvert($buf,CHARSET_IN);
		$line = explode("\n",$buf);
		$countline=count($line);
		for($i = 0; $i < $countline; $i++){if($line[$i]!=""){$line[$i].="\n";};}
		$flag = false;
		$find = false;
		for($i = 0; $i<count($line); $i++){
			list($no,,,,,,,$dhost,$pass,$ext,,,$tim,,) = explode(",",$line[$i]);
			if(in_array($no,$del) && (substr(md5($pwd),2,8) == $pass /*|| $dhost == $host*/ || ADMIN_PASS == $pwd)){
				if(!$onlyimgdel){	//留言刪除
					treedel($no);
					if(USER_DEL > 2){$line[$i] = "";$find = true;}
				}
				if(USER_DEL > 1){
					$delfile = $path.$tim.$ext;	//刪除file
					if(@is_file($delfile)) unlink($delfile);//刪除
					if(@is_file(THUMB_DIR.$tim.'s.jpg')) unlink(THUMB_DIR.$tim.'s.jpg');//刪除
					if(@is_file(PCH_DIR.$tim.'.pch')) unlink(PCH_DIR.$tim.'.pch');//刪除
					if(@is_file(PCH_DIR.$tim.'.spch')) unlink(PCH_DIR.$tim.'.spch');//刪除
				}
				$flag = true;
			}
		}
		if(!$flag)error(MSG028);
		if($find){//ログ更新
			ftruncate($fp,0);
			set_file_buffer($fp, 0);
			rewind($fp);
			$newline = implode('', $line);
			fputs($fp, charconvert($newline,CHARSET_OUT));
		}
		fclose($fp);
	}
}

/* パス認證 */
function valid($pass){
	global $GalleryAdmin;
	if($_SESSION['session_userid']==10001 || $GalleryAdmin==1){
		//$admin="del";
	}else{
		if($pass && $pass != ADMIN_PASS) error(MSG029);

		if(!$pass){
			$dat['admin_in'] = true;
			head($dat);
			htmloutput(OTHERFILE,$dat);
			exit;
		}
	}
}

/* 管理者刪除 */
function admindel($pass){
	global $path,$onlyimgdel,$del,$DBorFILE;

	if(is_array($del)){
		sort($del);
		reset($del);
		// LOGFILE
		if($DBorFILE == 1){ //讀取DB
			//while (!feof ($fd))
			$rst = mysql_query("SELECT * FROM `gallery` WHERE `id` IN (".join(",", $del).") ORDER BY `id` DESC") ;
			while( $rcd = mysql_fetch_row($rst) ){
				$line[] = join(',', $rcd);
			}
			//print_r($line);exit;
		}else{
			$fp=fopen(LOGFILE,"r+");
			set_file_buffer($fp, 0);
			flock($fp, 2);
			rewind($fp);
			$buf=fread($fp,10000000);
			if($buf==''){error(MSG030);}
			$buf = charconvert($buf,CHARSET_IN);
			$line = explode("\n",$buf);
		}

		$countline=count($line);
		for($i = 0; $i < $countline; $i++){if($line[$i]!=""){$line[$i].="\n";};}
		$find = false;
		for($i = 0; $i < $countline; $i++){
			list($no,$date,$nameid,,,,,,,$ext,,,$tim,,) = explode(",",$line[$i]);
			if(in_array($no,$del)){

				if(!$onlyimgdel){	//留言刪除
					$cont = 'id='.$no;
					admins_addAction(139, $_SESSION['session_userid'], $cont); //管理員動作
					treedel($no);
					$line[$i] = "";
					$find = true;
				}

				//echo $nameid;exit;

				if($no >= NEW_ART_DIR){
					$MONTH_FOLDER = '../art/'.GetFolder($date).'/';
				}else{
					$MONTH_FOLDER = '';
				}

				$delfile = $path.$MONTH_FOLDER.$tim.$ext;	//刪除file
				if(@is_file($delfile)){
					unlink($delfile);//刪除
					//原作者請求刪除
					if(!empty($_GET['reqdel'])){
						//$oksysMsg  = '您所請求刪除的作品已經刪除！' ;
						//執行請求完成 SQL
						//mysql_query("UPDATE `galleryd` SET `del`=1 WHERE `id`='".$_GET['delimgid']."'");
					}else{
						$oksysMsg  = '首先感謝您在藝廊發表分享您的作品，但您的作品可能違反了 <a href="ac_gallery_poti.php?mode=rule">繪圖規則</a> 所規範的情況，';
						$oksysMsg .= '因此依照規則刪除了您的作品，提醒您下次發表前請詳閱相關規則並請見諒，謝謝。' ;
						admins_addAction(134,$_SESSION['session_userid']);
						//送出刪除訊息
						sysMsg($oksysMsg, $nameid, '藝廊作品刪除通知');
					}
					logDelFile($delfile);
					treedel($no);
					$line[$i] = "";
					$find = true;
				}else{
					//echo '檔案已刪除!!';
					/*
					if(!empty($_GET['reqdel'])){
						$oksysMsg  = '您所請求刪除的作品已經刪除！' ;
						//執行請求完成 SQL
						mysql_query("UPDATE `galleryd` SET `del`=1 WHERE `id`='".$_GET['delimgid']."'");
					}
					admins_addAction(135,$_SESSION['session_userid']);
					*/
				}
				if(@is_file(THUMB_DIR.$MONTH_FOLDER.$tim.'s.jpg')){
					unlink(THUMB_DIR.$MONTH_FOLDER.$tim.'s.jpg');//刪除
					logDelFile($tim.'s.jpg');
				}
				if(@is_file(PCH_DIR.$MONTH_FOLDER.$tim.'.pch')){
					unlink(PCH_DIR.$MONTH_FOLDER.$tim.'.pch');//刪除
					logDelFile($tim.'.pch');
				}
				if(@is_file(PCH_DIR.$MONTH_FOLDER.$tim.'.spch')){
					unlink(PCH_DIR.$MONTH_FOLDER.$tim.'.spch');//刪除
					logDelFile($tim.'.spch');
				}

			}
		}
		if($DBorFILE == 1){ //讀取DB
			//something
		}else{
			if($find){//ログ更新
				ftruncate($fp,0);
				set_file_buffer($fp, 0);
				rewind($fp);
				$newline = implode('', $line);
				fputs($fp, charconvert($newline,CHARSET_OUT));
			}
			fclose($fp);
		}
	}

	if(!empty($_GET['reqdel'])) exit;

	// 刪除画面を表示
	$dat['admin_del'] = true;
	head($dat);
	$dat['pass'] = $pass;

	if($DBorFILE == 1){ //讀取DB
		//while (!feof ($fd))
		$rst = mysql_query("SELECT * FROM `gallery` ORDER BY `id` DESC LIMIT 0,2") ;
		//echo "SELECT * FROM `gallery` WHERE `id` IN (".$tree[$resno]."0) ORDER BY `id` ASC";
		while( $rcd = mysql_fetch_row($rst) ){
			$line[] = join(',', $rcd);
		}
	}else{
		$line = file(LOGFILE);
	}
	//for($j = 0; $j < count($line); $j++){
	//改只讀50筆紀錄
	$k=0;
	for($j = 0; $j < 2; $j++){
		$img_flag = FALSE;
		list($no,$now,$name,$email,$sub,$com,$url,
			 $host,$pw,$ext,$w,$h,$time,$chk,) = explode(",",charconvert($line[$j],CHARSET_IN));
		// フォーマット
		//$now=ereg_replace('.{2}/(.*)$','\1',$now);
		//$now=ereg_replace('\(.*\)',' ',$now);
		$now  = preg_replace("/( ID:.*)/","",$now);//ID以降除去
		//$name = strip_tags($name);//タグ除去
		$name = member_id_to_echo($name,'1','');//タグ除去

		//if(strlen($name) > 10) $name = substr($name,0,9).".";
		//if(strlen($sub) > 10) $sub = substr($sub,0,9).".";
		//if($email) $name="<a href=\"mailto:$email\">$name</a>";
		$com = preg_replace("#<br(( *)|( *)/)>#i"," ",$com);
		//$com = str_replace("<br />"," ",$com);
		$com = htmlspecialchars($com);
		//if(strlen($com) > 20) $com = substr($com,0,18) . ".";
		// 画像があるときはリンク
		/*原本的
		if($ext && @is_file($path.$time.$ext)){
			$img_flag = TRUE;
			//$clip = "<a href=\"".IMG_DIR.$time.$ext."\" target=_blank>".$time.$ext."</a><br />";
			$clip = "<a href=\"".IMG_DIR.$time.$ext."\" target=_blank>圖片</a><br />";
			$size = filesize($path.$time.$ext);
			$all += $size;	//合計計算
			$chk= substr($chk,0,10);
		}else{
			$clip = "";
			$size = 0;
			$chk= "";
		}
		$bg = ($j % 2) ? ADMIN_DELGUSU : ADMIN_DELKISU;//背景色
		if($sub!='re'){
			$bg='#9999CC';
		}
		*/
		if( ($ext && @is_file($path.$time.$ext)) || ($sub1='re')){
			$img_flag = TRUE;
			//$clip = "<a href=\"".IMG_DIR.$time.$ext."\" target=_blank>".$time.$ext."</a><br />";
			//$clip = "<a href=\"".IMG_DIR.$time.$ext."\" target=_blank>圖片</a><br />";
			//$clip = "<a href=\"http://images.wsm.idv.tw/".IMG_DIR.$time.$ext."\" target=_blank><img src=\"http://images.wsm.idv.tw/".IMG_DIR.$time.$ext."\" width=\"40\" border=\"0\"></a><br />";
			$clip = '';
			$size = filesize($path.$time.$ext);
			$all += $size;	//合計計算
			$chk= substr($chk,0,10);

			$bg = ($j % 2) ? ADMIN_DELGUSU : ADMIN_DELKISU;//背景色
			if($sub!='re'){
				$bg='#9999CC';
			}
			$dat['del'][$k] = compact('bg','no','now','sub','name','com','host','clip','size','chk');
			$k++;

		}

	}

	$dat['all'] = (int)($all / 1024);
	htmloutput(OTHERFILE,$dat);
	exit;
}

function init(){
	$chkfile=array(LOGFILE,TREEFILE);
	//if(!is_writable(realpath("./")))error("カレントディレクトリに書けません<br />");
	foreach($chkfile as $value){
		if(!@file_exists(realpath($value))){
			$fp = fopen($value, "w");
			set_file_buffer($fp, 0);
			$now = now_date(time());//日付取得
			if(DISP_ID) $now .= " ID:???";
			$testmes="1,".$now.",".DEF_NAME.",,".DEF_SUB.",".DEF_COM.",,\n";
			if($value==LOGFILE)fputs($fp,charconvert($testmes,CHARSET_OUT));
			if($value==TREEFILE)fputs($fp,"1\n");
			fclose($fp);
			if(@file_exists(realpath($value)))@chmod($value,0666);
		}
		if(!is_writable(realpath($value)))$err.=$value."を書けません<br />";
		if(!is_readable(realpath($value)))$err.=$value."を読めません<br />";
	}
	@mkdir(IMG_DIR,0777);@chmod(IMG_DIR,0777);
	if(!is_dir(realpath(IMG_DIR)))$err.=IMG_DIR."がありません<br />";
	if(!is_writable(realpath(IMG_DIR)))$err.=IMG_DIR."を書けません<br />";
	if(!is_readable(realpath(IMG_DIR)))$err.=IMG_DIR."を読めません<br />";
	if(USE_THUMB){
		@mkdir(THUMB_DIR,0777);@chmod(THUMB_DIR,0777);
		if(!is_dir(realpath(THUMB_DIR)))$err.=THUMB_DIR."がありません<br />";
		if(!is_writable(realpath(THUMB_DIR)))$err.=THUMB_DIR."を書けません<br />";
		if(!is_readable(realpath(THUMB_DIR)))$err.=THUMB_DIR."を読めません<br />";
	}
	if(USE_PAINT){
		@mkdir(TEMP_DIR,0777);@chmod(TEMP_DIR,0777);
		if(!is_dir(realpath(TEMP_DIR)))$err.=TEMP_DIR."がありません<br />";
		if(!is_writable(realpath(TEMP_DIR)))$err.=TEMP_DIR."を書けません<br />";
		if(!is_readable(realpath(TEMP_DIR)))$err.=TEMP_DIR."を読めません<br />";
	}
	if($err)error($err);
	//if(!@file_exists(realpath(PHP_SELF3)))updatelog();
	realpath(PHP_SELF3);
	updatelog();
}

/* 主繪版畫面 お絵描き画面 */
function paintform($picw,$pich,$palette,$anime,$pch=""){
	global $admin,$shi,$ctype,$type,$no,$pwd,$ext,$date;
	global $resto,$mode,$savetype,$quality,$qualitys,$usercode,$myadminnnn;
	global $IP;

	if($picw < 100) $picw = 100;
	if($pich < 100) $pich = 100;
	if($picw > PMAX_W) $picw = PMAX_W;
	if($pich > PMAX_H) $pich = PMAX_H;
	$w = $picw + 150;
	$h = $pich + 170;
	if($w < 400){$w = 400;}
	if($h < 420){$h = 420;}
	if($w < 500 && $shi){$w = 500;}
	if($h < 500 && $shi==2){$h = 500;}

	if($no >= NEW_ART_DIR){
		$MONTH_FOLDER = '../art/'.GetFolder($date).'/';
	}
	//echo PCH_DIR.$MONTH_FOLDER.$pch;

	$dat['paint_mode'] = true;
	head($dat);
	form($dat,$resto);
	$dat['mode2'] = $mode;
	if($mode=="contpaint"){
		$dat['no'] = $no;
		$dat['pch'] = $pch;
		$dat['ctype'] = $ctype;
		$dat['type'] = $type;
		$dat['pwd'] = $pwd;
		$dat['ext'] = $ext;

		if(@file_exists(PCH_DIR.$MONTH_FOLDER.$pch.'.pch') || @file_exists(PCH_DIR.$MONTH_FOLDER.$pch.'.lsd') || @file_exists(PCH_DIR.$MONTH_FOLDER.$pch.'.oeb')){
			$dat['applet'] = false;
		}elseif(@file_exists(PCH_DIR.$MONTH_FOLDER.$pch.'.spch')){
			$dat['applet'] = true;
			$dat['usepbbs'] = false;
		}elseif(@file_exists(IMG_DIR.$MONTH_FOLDER.$pch.$ext)){
			$dat['applet'] = true;
			$dat['usepbbs'] = true;
		}
		if((C_SECURITY_CLICK || C_SECURITY_TIMER) && SECURITY_URL){
			$dat['security'] = true;
			$dat['security_click'] = C_SECURITY_CLICK;
			$dat['security_timer'] = C_SECURITY_TIMER;
		}
	}else{
		if((SECURITY_CLICK || SECURITY_TIMER) && SECURITY_URL){
			$dat['security'] = true;
			$dat['security_click'] = SECURITY_CLICK;
			if($myadminnnn==1) $dat['security_click'] = 1;
			$dat['security_timer'] = SECURITY_TIMER;
		}
		$dat['newpaint'] = true;
	}
	$dat['security_url'] = SECURITY_URL;
	switch($savetype){
		case 'PNG':
			$dat['image_jpeg'] = 'false';
			$dat['image_size'] = IMAGE_SIZE;
			$savepng = ' selected';
			break;
		case 'JPEG':
			$dat['image_jpeg'] = 'true';
			$dat['image_size'] = 1;
			$savejpeg = ' selected';
			break;
		default:
			$dat['image_jpeg'] = 'true';
			$dat['image_size'] = IMAGE_SIZE;
			$saveauto = ' selected=\"selected\"';
	}
	$dat['savetypes'] = "<option value=\"AUTO\"".$saveauto.">AUTO</option>\n";
	$dat['savetypes'].= "<option value=\"PNG\"".$savepng.">PNG</option>\n";
	$dat['savetypes'].= "<option value=\"JPEG\"".$savejpeg.">JPEG</option>\n";
	$dat['compress_level'] = COMPRESS_LEVEL;
	$dat['layer_count'] = LAYER_COUNT;
	//Check Animations
	if (@file_exists(PCH_DIR.$pch.'.oeb')) {
		$dat['imgfile'] = './'.PCH_DIR.$pch.$ext;
		$shi=3;
	}elseif(@file_exists(PCH_DIR.$pch.'.lsd')) {
		$shi=4;
	}
	//End-Check Animations
	if($shi) $dat['quality'] = $quality ? $quality : $qualitys[0];
	if($shi==1){ $dat['normal'] = true; }
	elseif($shi==2){ $dat['pro'] = true; }
	elseif($shi==3){ $dat['oekakibbs']=true; }
	elseif($shi==8){ $dat['shi1114'] = true; }
	elseif($shi==9){ $dat['shi1114_pro'] = true; }
	//elseif($shi>=4){ $dat['applet'.$shi]=true;}
	else{ $dat['paintbbs'] = true; }
	//if ($shi<3) {$dat['Pallette']=true; } //wason
	if (1) {$dat['Pallette']=true; }
	$dat['palettes'][0] = 'Palettes[0] = "#000000\n#FFFFFF\n#B47575\n#888888\n#FA9696\n#C096C0\n#FFB6FF\n#8080FF\n#25C7C9\n#E7E58D\n#E7962D\n#99CB7B\n#FCECE2\n#F9DDCF";'."\n";
	$pal=array();
	$DynP=array();
	$p_cnt=1;
	$lines = file(PALETTEFILE);
	foreach ( $lines as $line ) {
		$line=preg_replace("/[\t\r\n]/","",$line);
		list($pid,$pname,$pal[0],$pal[2],$pal[4],$pal[6],$pal[8],$pal[10],$pal[1],$pal[3],$pal[5],$pal[7],$pal[9],$pal[11],$pal[12],$pal[13]) = explode(",", $line);
		$DynP[]=CleanStr($pname);
		$palettes = 'Palettes['.$p_cnt.'] = "#'.$pal[0];
		ksort($pal);
		array_shift($pal);
		foreach ( $pal as $p ) {
			$palettes.='\n#'.$p;
		}
		$palettes.='";'."\n";
		$dat['palettes'][$p_cnt] = $palettes;
		$p_cnt++;
		if($pid==$palette){
			$C_Palette = explode(",", $line);
			array_shift($C_Palette); array_shift($C_Palette);
		}
	}

	$dat['w'] = ($dat['Pallette']) ? $w : $w+256;
	$dat['h'] = $h;
	$dat['picw'] = $picw;
	$dat['pich'] = $pich;
	$stime = time();
	$dat['stime'] = $stime;
	if($pwd) $pwd = substr(md5($pwd),2,8);
	$resto = ($resto) ? '&amp;resto='.$resto : '';
	$dat['mode'] = 'piccom'.$resto;
	$dat['animeform'] = true;
	$dat['anime'] = ($anime) ? true : false;
	if($ctype=='pch'){
		if(@file_exists(PCH_DIR.$MONTH_FOLDER.$pch.'.pch')) $dat['pchfile'] = './'.PCH_DIR.$MONTH_FOLDER.$pch.'.pch';
		if(@file_exists(PCH_DIR.$MONTH_FOLDER.$pch.'.spch')) $dat['pchfile'] = './'.PCH_DIR.$MONTH_FOLDER.$pch.'.spch';
		//if(@file_exists(PCH_DIR.$pch.'.lsd')) $dat['pchfile'] = './'.PCH_DIR.$pch.'.lsd';
		//if(@file_exists(PCH_DIR.$pch.'.oeb')) $dat['pchfile'] = './'.PCH_DIR.$pch.'.oeb';
	}
	if($ctype=='img'){
		$dat['animeform'] = false;
		$dat['anime'] = false;
		$dat['imgfile'] = './'.PCH_DIR.$MONTH_FOLDER.$pch.$ext;
	}
	if(ADMIN_NEWPOST&&$admin==ADMIN_PASS) $dat['admin'] = 'picpost';

	if(isset($C_Palette)){
		for ($n = 1;$n < 7;++$n)
			$cpal[$n*2-1] = $C_Palette[$n-1];
		for ($n = 7;$n < 13;++$n)
			$cpal[$n-(13-$n)+1] = $C_Palette[$n-1];
		for ($n = 13;$n < 15;++$n)
			$cpal[$n] = $C_Palette[$n-1];
		ksort($cpal);
		$no = 1;
		foreach ($cpal as $pal){
			$dat['cpal'][] = compact('no','pal');
			$no++;
		}
	}

	$dat['palsize'] = count($DynP) + 1;
	foreach ($DynP as $p){
		$dat['dynp'][] = $p;
	}
	$dat['usercode'] = $usercode;

	//差し換え時の認識コード追加
	if($type=='rep'){
		$repcode = substr(crypt(md5($no.$IP.$pwd.date("Ymd", time()))),-8);
		//念の為にエスケープ文字があればアルファベットに変換
		$repcode = strtr($repcode,"!\"#$%&'()+,/:;<=>?@[\\]^`/{|}~","ABCDEFGHIJKLMNOabcdefghijklmn");
		$dat['mode'] = 'picrep&amp;no='.$no.'&amp;pwd='.$pwd.'&amp;repcode='.$repcode;
		$dat['usercode'] = $usercode.'&amp;repcode='.$repcode;
	}

	$buf = htmloutput(PAINTFILE,$dat,true);

	list($buf1,$buf2) = explode('<SIIHELP>', $buf);
	echo $buf1;
	if(@file_exists(SIIHELP_FILE)){
		$help = implode('', file(SIIHELP_FILE));
		echo charconvert($help,CHARSET_OUT);
	}
	echo $buf2;
}

/* お絵かきコメント */
function paintcom($resto=''){
	global $admin,$usercode;
	global $IP;

	if(USE_RESUB && $resto) {
		$lines = file(LOGFILE);
		$flag = FALSE;
		foreach($lines as $line){
			list($cno,,,,$sub,,,,,,,,,,) = explode(",", charconvert($line,CHARSET_IN));
			if($cno == $resto){
				$dat['sub'] = 'Re: '.$sub;
				$flag = TRUE;
				break;
			}
		}
		if(!$flag) $resto=''; //スレが刪除されていた場合、新規投稿
	}
	$dat['nameid']=$_SESSION['session_userid'];
	$dat['passwd']=member_id_to_pass($_SESSION['session_userid']);

	//temp圖片list作成
	$tmplist = array();
	$handle = @opendir(TEMP_DIR);
	while ($file = readdir($handle)) {
		if(!is_dir($file) && preg_match("/\.(dat)$/i",$file)) {
			$fp = fopen(TEMP_DIR.$file, "r");
			$userdata = fread($fp, 1024);
			fclose($fp);
			list($uip,$uhost,$uagent,$imgext,$ucode,) = explode("\t", rtrim($userdata));
			$file_name = eregi_replace("\.(dat)$","",$file);
			if(@file_exists(TEMP_DIR.$file_name.$imgext)) //圖片があればlistに追加
				$tmplist[] = $ucode."\t".$uip."\t".$file_name.$imgext;
		}
	}
	closedir($handle);
	$tmp = array();
	if(count($tmplist)!=0){
		//user-codeでチェック
		foreach($tmplist as $tmpimg){
			list($ucode,$uip,$ufilename) = explode("\t", $tmpimg);
			if($ucode == $usercode)
				$tmp[] = $ufilename;
		}
		//user-codeでhitしなければIPで再チェック
		if(count($tmp)==0){
			$userip = $IP;
			foreach($tmplist as $tmpimg){
				list($ucode,$uip,$ufilename) = explode("\t", $tmpimg);
				if(!IP_CHECK || $uip == $userip)
					$tmp[] = $ufilename;
			}
		}
	}

	$dat['post_mode'] = true;
	$dat['regist'] = true;
	head($dat);
	if(IP_CHECK) $dat['ipcheck'] = true;
	if(count($tmp)==0){
		$dat['notmp'] = true;
		$dat['pictmp'] = 1;
	}else{
		$dat['pictmp'] = 2;
		sort($tmp);
		reset($tmp);
		foreach($tmp as $tmpfile){
			$src = TEMP_DIR.$tmpfile;
			$srcname = $tmpfile;
			$date = gmdate("Y/m/d H:i", filemtime($src)+8*60*60);
			$dat['tmp'][] = compact('src','srcname','date');
		}
	}
	if(ADMIN_NEWPOST&&$admin=='picpost') $dat['admin'] = $admin;
	form($dat,$resto,'',$tmp);
	htmloutput(OTHERFILE,$dat);
}

/* 過程表示 */
function openpch($pch,$sp=""){
	global $shi,$no,$date,$HTTP_GET_VARS;

	if($no >= NEW_ART_DIR){
		$MONTH_FOLDER = '../art/'.GetFolder($date).'/';
	}

	$picfile = IMG_DIR.$MONTH_FOLDER.$pch;

	//從資料庫讀取寬度高度
	$sqlpch = explode('.', $pch);
	$sql = "SELECT `oimgh`,`oimgw`,`allowpch`,`haspch`,`title`,`memid` FROM `gallery` WHERE `img`='".preg_replace('#[^a-z0-9\.]#i', '', $sqlpch[0])."' LIMIT 1;";
	$rcd = mysql_fetch_array(mysql_query($sql));
	//print_r($rcd); echo $sql; exit;
	//OB1218533133954
	if( empty($rcd[0]) ) error("查無此作品的過程記錄");
	if( empty($rcd[2]) ) error("此作品並未開放過程瀏覽");

	$pch = str_replace( strrchr($pch,"."), "", $pch); //拡張子除去
	$dat['shiani']=true;
	if($shi==1){
		$dat['normal'] = true;
		$pchfile = PCH_DIR.$MONTH_FOLDER.$pch.'.spch';
	}elseif($HTTP_GET_VARS['oek']==1) {
		$dat['shiani']=false;
		$dat['oekani']=true;
		$pchfile = PCH_DIR.$MONTH_FOLDER.$pch.'.oeb';
	}else{
		$dat['paintbbs'] = true;
		$pchfile = PCH_DIR.$MONTH_FOLDER.$pch.'.pch';
	}
	$datasize = filesize($pchfile);
	$size = getimagesize($picfile);

	if(!$sp) $sp = PCH_SPEED;
	/*
	$picw = $size[0];
	$pich = $size[1];
	*/
	$picw = $rcd['oimgw'];
	$pich = $rcd['oimgh'];
	$w = $picw;
	$h = $pich + 26;
	if($w < 200){$w = 200;}
	if($h < 226){$h = 226;}

	head($dat);

	$dat['w'] = $w;
	$dat['h'] = $h;
	$dat['picw'] = $picw;
	$dat['pich'] = $pich;
// 過程對照組
	$dat['picfile'] = './'.$picfile;
// 過程對照組
	$dat['pchfile'] = './'.$pchfile;
	$dat['speed'] = $sp;
	$dat['datasize'] = $datasize;

	if($datasize==0){
		$dat['movemsg'] = '過程播放檔案已轉移，請由分流伺服器點選觀看過程記錄檔。';
		$data = array($picw,$pich,str_replace("gallery/src/", "", $picfile),str_replace("gallery/src/", "", $pchfile),$rcd[5],member_id_to_users($rcd[5]),$rcd[4]);
		//echo serialize($data);exit;
		$dat['movelink'] = urlencode(base64_encode(serialize($data)));
		$dat['pch_jump'] = true;
	}else{
		$dat['pch_mode'] = true;
	}

	htmloutput(PAINTFILE,$dat);
}

/* temp内のgarbage除去 */
function deltemp(){
	$handle = @opendir(TEMP_DIR);
	while ($file = readdir($handle)) {
		if(!is_dir($file)) {
			$lapse = time() - filemtime(TEMP_DIR.$file);
			if($lapse > (TEMP_LIMIT*24*3600)){
				unlink(TEMP_DIR.$file);
			}
		}
	}
	closedir($handle);
}

/* 續繪前画面 */
function incontinue($no){
  jslocation('ac_gallery.php', '奇幻藝廊上傳功能已關閉，請改用奇幻繪圖館'); exit;
	global $addinfo;
	global $DBorFILE;
	global $Conf_IMGServer, $myadminnnn;

	if($DBorFILE == 1){ //讀取DB
		//while (!feof ($fd))
		$rst = mysql_query("SELECT * FROM `gallery` WHERE `id`=".$no." LIMIT 1;") ;
		//test("SELECT * FROM `gallery` WHERE `id`=".$no." LIMIT 1;");
		while( $rcd = mysql_fetch_row($rst) ){
			//$dblog[] = $rcd;
			$lines[] = join(',', $rcd);
		}
	}else{ //讀取檔案
		$lines = file(LOGFILE);
	}
	//$lines = file(LOGFILE);
	$countline=count($line);
	$flag = FALSE;
	foreach($lines as $line){
		list($cno,$dtime,$painter,,,,$conpainter,,,$cext,$picw,$pich,$ctim,,$cptime,,,,,,,,$oimgw,$oimgh) = explode(",", rtrim(charconvert($line,CHARSET_IN)));
		if($cno == $no){
			$flag = TRUE;
			break;
		}
	}
	if(!$flag) error(MSG001);

	$dat['continue_mode'] = true;
	head($dat);
	if(CONTINUE_PASS) $dat['passflag'] = true;

	if($no >= NEW_ART_DIR){
		$MONTH_FOLDER = '../art/'.GetFolder($dtime).'/';
	}

	$dat['picfile'] = IMG_DIR.$MONTH_FOLDER.$ctim.$cext;

	$dat['date'] = $dtime;

	$size = getimagesize($dat['picfile']);
	$dat['picw'] = $size[0];
	$dat['pich'] = $size[1];

	$dat['picw'] = $oimgw;
	$dat['pich'] = $oimgh;

	$dat['no'] = $no;
	$dat['pch'] = $ctim;
	$dat['ext'] = $cext;

	//允許續繪
	$dat['cancontinue'] = member_id_to_echo($painter,1,'');
	if( !empty($conpainter) ){
		//$dat['cont_painter'] = member_id_to_user($conpainter);
		$dat['cancontinue'] .= '、'.member_id_to_echo($conpainter,1,'');
	}
	if( $painter==$_SESSION['session_userid'] || $myadminnnn==1 ){
		$dat['painter_edit'] = 'xxx';
	}

	//繪圖時間
	if(DSP_PAINTTIME) $dat['painttime'] = $cptime;

	if(CONTINUE_LIMIT){
		@include("dat/gallery_limit.php");
		//續繪期限
		global $spLimit_Date;
		if(in_array($no, $spLimit)){
			$spShift = $spLimit_Date;
		}
		$dat['dtimelimit'] = dtimeShift($dtime, 3600*24*(30+$spShift));
	}else{
		$dat['dtimelimit'] = '無限制';
	}
	//$dat['painttime'] =	'qq';

	if(@file_exists(PCH_DIR.$MONTH_FOLDER.$ctim.'.pch') || @file_exists(PCH_DIR.$ctim.'.lsd') || @file_exists(PCH_DIR.$ctim.'.oeb')){
		$dat['applet'] = false;
		$dat['ctype_pch'] = true;
	}elseif(@file_exists(PCH_DIR.$MONTH_FOLDER.$ctim.'.spch')){
		$dat['applet'] = true;
		$dat['usepbbs'] = false;
		$dat['ctype_pch'] = true;
	}elseif(@file_exists(IMG_DIR.$MONTH_FOLDER.$ctim.$cext)){
		$dat['applet'] = true;
		$dat['usepbbs'] = true;
	}
	//if(@file_exists(IMG_DIR.$ctim.'.jpg')) $dat['ctype_jpg'] = true;
	$dat['ctype_img'] = true;

	$lines = file(PALETTEFILE);
	foreach ( $lines as $line ) {
		$line=preg_replace("/[\t\r\n]/","",$line);
		list($pid,$pname,) = explode(",", $line);
		$dat['palette'] .= '<option value="'.$pid.'">'.CleanStr($pname)."</option>\n";
	}

	$dat['addinfo'] = $addinfo;
	htmloutput(PAINTFILE,$dat);
}

/* 續繪認證 */
function usrchk($no,$pwd){
	global $DBorFILE;
	global $myadminnnn;
	// LOGFILE
	if($DBorFILE == 1){ //讀取DB
		//while (!feof ($fd))
		$rst = mysql_query("SELECT * FROM `gallery` WHERE `id`=".$no." LIMIT 1;") ;
		//test("SELECT * FROM `gallery` WHERE `id`=".$no." LIMIT 1;");
		//echo "SELECT * FROM `gallery` WHERE `id` IN (".$tree[$resno]."0) ORDER BY `id` DESC";
		while( $rcd = mysql_fetch_row($rst) ){
			//$dblog[] = $rcd;
			$lines[] = join(',', $rcd);
		}
	}else{ //讀取檔案
		$lines = file(LOGFILE);
	}
	$countline=count($line);
	$flag = FALSE;
	foreach($lines as $line){
		list($cno,$dtime,$user,,,,$url,,$cpwd,) = explode(",", charconvert($line,CHARSET_IN));
		//test($cno);
		//test($no);
		//if($cno == $no && substr(md5($pwd),2,8) == $cpwd){
		if( ($cno == $no && ($user==$_SESSION['session_userid']||$url==$_SESSION['session_userid'])) || $myadminnnn==1 ){

			if(CONTINUE_LIMIT){
				//偵測此作品發表日期
				@include("dat/gallery_limit.php");
				//續繪期限
				global $spLimit_Date;
				if(in_array($no, $spLimit)){
					$spShift = $spLimit_Date;
				}
				//$dat['dtimelimit'] = dtimeShift($dtime, 3600*24*(30+$spShift));
				$post_time_old = dtimeShift($dtime, 3600*24*(30+$spShift));
				$now = date("Y-m-d H:i:s");
				//echo $now."<BR>".$post_time_old; exit;
				if($now > $post_time_old){
					if($myadminnnn!=1){
						error(MSG035);
						break;
					}
				}
			}
			$flag = TRUE;
			break;
		}
	}
	if(!$flag) error(MSG028);
}

/* 編輯畫面 */
function editform($del,$pwd){
	global $pwdc,$addinfo;
	global $fontcolors;
	global $IP;

	$host = gethostbyaddr($IP);
	if(is_array($del)){
		sort($del);
		reset($del);
		if($pwd==""&&$pwdc!="") $pwd=$pwdc;
		$fp=fopen(LOGFILE,"r");
		flock($fp, 2);
		$buf=fread($fp,10000000);
		fclose($fp);
		if($buf==''){error(MSG019);}
		$buf = charconvert($buf,CHARSET_IN);
		$line = explode("\n",$buf);
		$countline=count($line);
		for($i = 0; $i < $countline; $i++){if($line[$i]!=""){$line[$i].="\n";};}
		$flag = FALSE;

		for($i = 0; $i<count($line); $i++){
			list($no,,$name,$email,$sub,$com,$url,$ehost,$pass,,,,,,,$fcolor) = explode(",", rtrim($line[$i]));
			if($no == $del[0] && (substr(md5($pwd),2,8) == $pass /*|| $ehost == $host*/ || ADMIN_PASS == $pwd)){
				$flag = TRUE;
				break;
			}
		}
		if(!$flag) error(MSG028);

		head($dat);
		$dat['post_mode'] = true;
		$dat['rewrite'] = $no;
		if(ADMIN_PASS == $pwd) $dat['admin'] = ADMIN_PASS;
		$dat['maxbyte'] = MAX_KB * 1024;
		$dat['maxkb']   = MAX_KB;
		$dat['addinfo'] = $addinfo;
		$dat['name'] = strip_tags($name);
		$dat['email'] = $email;
		$dat['sub'] = $sub;
		$com = eregi_replace("<br(( *)|( *)/)>","\n",$com); // <br />または<br />を改行へ戻す
		$dat['com'] = $com;
		$dat['url'] = $url;
		$dat['pwd'] = $pwd;

		//文字顏色
		if(USE_FONTCOLOR){
			foreach ( $fontcolors as $fontcolor ){
				list($color,$name) = explode(",", $fontcolor);
				$chk = ($color == $fcolor) ? true : false;
				$dat['fctable'][] = compact('color','name','chk');
			}
			if(!$fcolor) $dat['fctable'][0]['chk'] = true; //値が無い場合、先頭にチェック
		}

		htmloutput(OTHERFILE,$dat);
	}else{ error(MSG031); }
}

/* 留言上書き */
function rewrite($no,$name,$email,$sub,$com,$url,$pwd,$admin){
	global $badstring,$badip;
	global $REQUEST_METHOD;
	global $fcolor;
	global $IP;

	// 時間
	$time = time();

	$name  = charconvert($name ,CHARSET_IN);
	$sub   = charconvert($sub  ,CHARSET_IN);
	$com   = charconvert($com  ,CHARSET_IN);
	$email = charconvert($email,CHARSET_IN);
	$url   = charconvert($url  ,CHARSET_IN);

	foreach($badstring as $value){if(ereg($value,$com)||ereg($value,$sub)||ereg($value,$name)||ereg($value,$email)){error(MSG032,$dest);};}
	if($REQUEST_METHOD != "POST") error(MSG006);

	// form內容check
	if(!$name||ereg("^[ |　|]*$",$name)) $name="";
	if(!$com||ereg("^[ |　|\t]*$",$com)) $com="";
	if(!$sub||ereg("^[ |　|]*$",$sub))   $sub="";
	if(!$url||ereg("^[ |　|]*$",$url))   $url="";

	//$name=ereg_replace("管理","\"管理\"",$name);
	//$name=ereg_replace("刪除","\"刪除\"",$name);

	if(strlen($com) > MAX_COM) error(MSG011);
	if(strlen($name) > MAX_NAME) error(MSG012);
	if(strlen($email) > MAX_EMAIL) error(MSG013);
	if(strlen($sub) > MAX_SUB) error(MSG014);

	//host取得
	foreach($badip as $value){ //拒絶host
		if(eregi("$value$",$host)) error(MSG016);
	}
	if(eregi("^mail",$host)
	|| eregi("^ns",$host)
	|| eregi("^dns",$host)
	|| eregi("^ftp",$host)
	|| eregi("^prox",$host)
	|| eregi("^pc",$host)
	|| eregi("^[^\.]\.[^\.]$",$host)){
		$pxck = "on";
	}
	if(eregi("ne\\.jp$",$host)
	|| eregi("ad\\.jp$",$host)
	|| eregi("bbtec\\.net$",$host)
	|| eregi("aol\\.com$",$host)
	|| eregi("uu\\.net$",$host)
	|| eregi("asahi-net\\.or\\.jp$",$host)
	|| eregi("rim\\.or\\.jp$",$host)){
		$pxck = "off";
	}else{
		$pxck = "on";
	}

	if($pxck=="on" && PROXY_CHECK){
		if(proxy_connect('80') == 1){
			error(MSG017);
		}elseif(proxy_connect('8080') == 1){
			error(MSG018);
		}
	}

	// パスと時間とURLフォーマット
	$pass = ($pwd) ? substr(md5($pwd),2,8) : "*";
	$now = now_date($time);//日付取得
	$now .= UPDATE_MARK;
	if(DISP_ID){
		if($email&&DISP_ID==1){
			$now .= " ID:???";
		}else{
			$now.=" ID:".substr(crypt(md5($IP.ID_SEED.gmdate("Ymd", $time+8*60*60)),'id'),-8);
		}
	}
	$now = str_replace(",", "&#44;", $now);//逗點轉換
	//text整形
	$email= CleanStr($email);  $email=preg_replace("/[\r\n]/","",$email);
	$sub  = CleanStr($sub);    $sub  =preg_replace("/[\r\n]/","",$sub);
	$url  = CleanStr($url);    $url  =preg_replace("/[\r\n]/","",$url);
	$url  = str_replace(" ", "", $url);
	$com  = CleanStr($com);
	// 統一換行文字
	$com = str_replace("\r\n", "\n", $com);
	$com = str_replace("\r", "\n", $com);
	// 連続する空行を一行
	$com = preg_replace("/\n((　| )*\n){3,}/","\n",$com);
	if(!BR_CHECK || substr_count($com,"\n")<BR_CHECK){
		$com = nl2br($com);		//改行文字の前に<br />を代入する
	}
	$com = str_replace("\n", "", $com);	//\nを文字列から消す。

	$name=str_replace("◆","◇",$name);
	$name=preg_replace("/[\r\n]/","",$name);
	$names=$name;
	$name = CleanStr($name);
	if(ereg("(#|＃)(.*)",$names,$regs)){
		$cap = $regs[2];
		$cap=strtr($cap,"&amp;", "&");
		$cap=strtr($cap,"&#44;", ",");
		$name=preg_replace("/(#|＃)(.*)/","",$name);
		$salt=substr($cap."H.",1,2);
		$salt=preg_replace("/[^\.-z]/",".",$salt);
		$salt=strtr($salt,":;<=>?@[\\]^_`","ABCDEFGabcdef");
		$name.="◆".substr(crypt($cap,$salt),-10);
	}

	//ログ読み込み
	$fp=fopen(LOGFILE,"r+");
	flock($fp, 2);
	rewind($fp);
	$buf=fread($fp,10000000);
	if($buf==''){error(MSG019);}
	$buf = charconvert($buf,CHARSET_IN);
	$line = explode("\n",$buf);
	$countline=count($line);
	for($i = 0; $i < $countline; $i++){if($line[$i]!=""){$line[$i].="\n";};}

	// 留言上書き
	$flag = FALSE;
	for($i = 0; $i<count($line); $i++){
		list($eno,,$ename,,$esub,$ecom,$eurl,$ehost,$epwd,$ext,$W,$H,$tim,$chk,$ptime,$efcolor) = explode(",", rtrim($line[$i]));
		if($eno == $no && ($pass == $epwd /*|| $ehost == $host*/ || ADMIN_PASS == $admin)){
			if(!$name) $name = $ename;
			if(!$sub)  $sub  = $esub;
			if(!$com)  $com  = $ecom;
			if(!$url)  $url  = $eurl;
			if(!$fcolor) $fcolor = $efcolor;
			$line[$i] = "$no,$now,$name,$email,$sub,$com,$url,$host,$epwd,$ext,$W,$H,$tim,$chk,$ptime,$fcolor\n";
			$flag = TRUE;
			break;
		}
	}
	if(!$flag){
		fclose($fp);
		error(MSG028);
	}

	ftruncate($fp,0);
	set_file_buffer($fp, 0);
	rewind($fp);
	$newline = implode('', $line);
	fputs($fp, charconvert($newline,CHARSET_OUT));
	fclose($fp);

	updatelog();

	header("Content-type: text/html; charset=".CHARSET_HTML);
	$str = "<html><head><META HTTP-EQUIV=\"refresh\" content=\"1;URL=".PHP_SELF2."\">\n";
	$str.= "<META HTTP-EQUIV=\"Content-type\" CONTENT=\"text/html; charset=".CHARSET_HTML."\"></head>\n";
	$str.= "<body>$mes 頁面正在更新中 請稍等一下</body></html>";
	echo charconvert($str,CHARSET_OUT);
}

/* 圖片差し換え */
function replace($no,$pwd,$stime){
	global $path,$temppath,$badip,$badfile,$repcode;
	global $IP;

	//host取得
	$host = gethostbyaddr($IP);

	foreach($badip as $value){ //拒絶host
		if(eregi("$value$",$host)) error(MSG016);
	}
	if(eregi("^mail",$host)
	|| eregi("^ns",$host)
	|| eregi("^dns",$host)
	|| eregi("^ftp",$host)
	|| eregi("^prox",$host)
	|| eregi("^pc",$host)
	|| eregi("^[^\.]\.[^\.]$",$host)){
		$pxck = "on";
	}
	if(eregi("ne\\.jp$",$host)
	|| eregi("ad\\.jp$",$host)
	|| eregi("bbtec\\.net$",$host)
	|| eregi("aol\\.com$",$host)
	|| eregi("uu\\.net$",$host)
	|| eregi("asahi-net\\.or\\.jp$",$host)
	|| eregi("rim\\.or\\.jp$",$host)){
		$pxck = "off";
	}else{
		$pxck = "on";
	}

	if($pxck=="on" && PROXY_CHECK){
		if(proxy_connect('80') == 1){
			error(MSG017);
		}elseif(proxy_connect('8080') == 1){
			error(MSG018);
		}
	}

  /*--- Find the bloody picture and related shit.---*/
	$find=false;
	$handle = @opendir(TEMP_DIR);
	while ($file = readdir($handle)) {
		if(!is_dir($file) && preg_match("/\.(dat)$/i",$file)) {
			$fp = fopen(TEMP_DIR.$file, "r");
			$userdata = fread($fp, 1024);
			fclose($fp);
			list($uip,$uhost,$uagent,$imgext,$ucode,$urepcode) = explode("\t", rtrim($userdata));
			$file_name = eregi_replace("\.(dat)$","",$file);
			//画像があり、認識コードがhitすれば抜ける
			if(@file_exists(TEMP_DIR.$file_name.$imgext) && $urepcode == $repcode || @file_exists(TEMP_DIR.$file_name.$imgext)){$find=true;break;}
		}
	}
	closedir($handle);
	if(!$find){
		header("Content-type: text/html; charset=".CHARSET_HTML);
		$str = "<html><head><title>沒有找到圖片</title>\n";
		$str.= "<META HTTP-EQUIV=\"Content-type\" CONTENT=\"text/html; charset=".CHARSET_HTML."\"></head>\n";
		$str.= '<body>沒有找到圖片，請稍待一會再試<br /><br />或者可以到「<a href="'.PHP_SELF.'?mode=piccom">暫存區的圖片</a>」找你要的圖片。</body></html>';
		echo charconvert($str,CHARSET_OUT);
		exit;
	}

	// 時間
	$time = time();
	$tim = KASIRA.$time.substr(microtime(),2,3);
	$now = now_date($time);//日付取得
	$now .= UPDATE_MARK;
	//繪圖時間
	if($stime && DSP_PAINTTIME){
		$ptime = '';
		if($stime){
			$psec = $time-$stime;
			if($psec >= 86400){
				$D = intval($psec/86400);
				$ptime .= $D.PTIME_D;
				$psec -= $D*86400;
			}
			if($psec >= 3600){
				$H = intval($psec/3600);
				$ptime .= $H.PTIME_H;
				$psec -= $H*3600;
			}
			if($psec >= 60){
				$M = intval($psec/60);
				$ptime .= $M.PTIME_M;
				$psec -= $M*60;
			}
			if($psec){
				$ptime .= $psec.PTIME_S;
			}
		}
	}

	//ログ読み込み
	$fp=fopen(LOGFILE,"r+");
	flock($fp, 2);
	rewind($fp);
	$buf=fread($fp,10000000);
	if($buf==''){error(MSG019);}
	$buf = charconvert($buf,CHARSET_IN);
	$line = explode("\n",$buf);
	$countline=count($line);
	for($i = 0; $i < $countline; $i++){if($line[$i]!=""){$line[$i].="\n";};}

	// 留言上書き
	$flag = false;
	for($i = 0; $i<count($line); $i++){
		list($eno,,$name,$email,$sub,$com,$url,$ehost,$epwd,$ext,$W,$H,$etim,,$eptime,$fcolor) = explode(",", rtrim($line[$i]));
		if($eno == $no && ($pwd == $epwd /*|| $ehost == $host*/ || $pwd == substr(md5(ADMIN_PASS),2,8))){
			$upfile = $temppath.$file_name.$imgext;
			$dest = $path.$tim.$imgext;
			copy($upfile, $dest);
			if(!@file_exists($dest)) error(MSG003,$dest);
			$size = getimagesize($dest);
			if(!is_array($size)) error(MSG004,$dest);
			$chk = md5_of_file($dest);
			foreach($badfile as $value){if(ereg("^$value",$chk)){
				error(MSG005,$dest); //拒絶画像
			}}
			chmod($dest,0666);
			$mes = "圖片已經成功了送出<br />";
			//差し換え前と同じ大きさのサムネイル作成
			if(USE_THUMB) thumb($path,$tim,$imgext,$W,$H);
			//ワークファイル削除
			if(@file_exists($upfile)) unlink($upfile);
			if(@file_exists($temppath.$file_name.".dat")) unlink($temppath.$file_name.".dat");
			//PCH Animation file Replacing
			$pchtemp = $temppath.$file_name.'.pch';
			if(@file_exists($pchtemp)){
				copy($pchtemp, PCH_DIR.$tim.'.pch');
				if(@file_exists(PCH_DIR.$tim.'.pch')){
					chmod(PCH_DIR.$tim.'.pch',0666);
					unlink($pchtemp);
				}
			}
			//SPCH Animation file Replacing
			$pchtemp = $temppath.$file_name.'.spch';
			if(@file_exists($pchtemp)){
				copy($pchtemp, PCH_DIR.$tim.'.spch');
				if(@file_exists(PCH_DIR.$tim.'.spch')){
					chmod(PCH_DIR.$tim.'.spch',0666);
					unlink($pchtemp);
				}
			}
			//OEB Animation file Replacing
			$pchtemp = $temppath.$file_name.'.oeb';
			if(@file_exists($pchtemp)){
				copy($pchtemp, PCH_DIR.$tim.'.oeb');
				if(@file_exists(PCH_DIR.$tim.'.oeb')){
					chmod(PCH_DIR.$tim.'.oeb',0666);
					unlink($pchtemp);
				}
			}
			//LSD Animation file Replacing
			$pchtemp = $temppath.$file_name.'.lsd';
			if(@file_exists($pchtemp)){
				copy($pchtemp, PCH_DIR.$tim.'.lsd');
				if(@file_exists(PCH_DIR.$tim.'.lsd')){
					chmod(PCH_DIR.$tim.'.lsd',0666);
					unlink($pchtemp);
				}
			}
			//舊file刪除
			if(@is_file($path.$etim.$ext)) unlink($path.$etim.$ext);
			if(@is_file(THUMB_DIR.$etim.'s.jpg')) unlink(THUMB_DIR.$etim.'s.jpg');
			if(@is_file(PCH_DIR.$etim.'.pch')) unlink(PCH_DIR.$etim.'.pch');
			if(@is_file(PCH_DIR.$etim.'.spch')) unlink(PCH_DIR.$etim.'.spch');
			if(@is_file(PCH_DIR.$etim.'.spch')) unlink(PCH_DIR.$etim.'.oeb');
			if(@is_file(PCH_DIR.$etim.'.spch')) unlink(PCH_DIR.$etim.'.lsd');
			//ID附加
			if(DISP_ID){
				if($email&&DISP_ID==1){
					$now .= " ID:???";
				}else{
					$now.=" ID:".substr(crypt(md5($IP.ID_SEED.gmdate("Ymd", $time+8*60*60)),'id'),-8);
				}
			}
			//繪圖時間追加
			if($eptime) $ptime=$eptime.'+'.$ptime;
			//逗點轉換
			$now = str_replace(",", "&#44;", $now);
			$ptime = str_replace(",", "&#44;", $ptime);

			$line[$i] = "$no,$now,".strip_tags($name).",$email,$sub,$com,$url,$host,$epwd,$imgext,$W,$H,$tim,$chk,$ptime,$fcolor\n";
			$flag = true;
			break;
		}
	}
	if(!$flag){
		fclose($fp);
		error(MSG028);
	}

	ftruncate($fp,0);
	set_file_buffer($fp, 0);
	rewind($fp);
	$newline = implode('', $line);
	fputs($fp, charconvert($newline,CHARSET_OUT));
	fclose($fp);

	updatelog();

	header("Content-type: text/html; charset=".CHARSET_HTML);
	$str = "<html><head><META HTTP-EQUIV=\"refresh\" content=\"1;URL=".PHP_SELF2."\">\n";
	$str.= "<META HTTP-EQUIV=\"Content-type\" CONTENT=\"text/html; charset=".CHARSET_HTML."\"></head>\n";
	$str.= "<body>$mes  頁面正在更新中 請稍等一下</body></html>";

	echo '<META HTTP-EQUIV="refresh" content="1;URL='.PHP_SELF2.'">';
	echo '<div id="mainlong"><div id="mainbar"><img border="0" src="images/bar_ac_long.gif" width="725" height="25" alt="交流區"></div><div id="maintitle">奇幻藝廊</div>';
	echo '<div id="maintitle2"><hr class="hr1" size="1"><br /><br /><br /></div>';
	echo output_msg($mes.'頁面更新中，請等待瀏覽器自動轉跳。',7);
	echo '</div>';
	//echo charconvert($str,CHARSET_OUT);
}

/* 目錄 */
function catalog(){
	global $path,$page;

	$line = file(LOGFILE);
	$countline=count($line);
	for($i = 0; $i < $countline; $i++){
		list($no,) = explode(",", $line[$i]);
		$lineindex[$no]=$i + 1; //逆変換table作成
  }

	$tree = file(TREEFILE);
	$counttree = count($tree);
	$x = 0;
	$y = 0;
	$pagedef = CATALOG_X * CATALOG_Y;//1pageに表示する件数
	head($dat);
	form($dat,'');
	if(!$page) $page=0;
	for($i = $page; $i < $page+$pagedef; $i++){
		if($tree[$i]==""){
			$dat['y'][$y]['x'][$x]['noimg'] = true;
		}else{
			$treeline = explode(",", rtrim($tree[$i]));
			$disptree = $treeline[0];
			$j=$lineindex[$disptree] - 1; //該当記事を探して$jにセット
			if($line[$j]=="") continue; //$jが範囲外なら次の行
			list($no,$now,$name,,$sub,,,,,$ext,$w,$h,$time,,) = explode(",", rtrim(charconvert($line[$j],CHARSET_IN)));
			// 圖片file名
			$img = $path.$time.$ext;
			// 圖片系變數設定
			if($ext && @is_file($img)){
				$src = IMG_DIR.$time.$ext;
				if($w){	//sizeがある時
					if($w > CATALOG_W) $w=CATALOG_W; //圖片幅を揃える
					if(@is_file(THUMB_DIR.$time.'s.jpg')){
						$imgsrc = THUMB_DIR.$time.'s.jpg';
					}else{
						$imgsrc = $src;
					}
				}else{$w=CATALOG_W;}
				//過程連結
				if(USE_ANIME){
					if(@file_exists(PCH_DIR.$time.'.pch'))
						$pch = $time.$ext;
					if(@file_exists(PCH_DIR.$time.'.spch'))
						$pch = $time.$ext.'&amp;shi=1';
					if(@file_exists(PCH_DIR.$time.'.oeb'))
						$pch = $time.$ext.'&amp;oek=1';
				}
			}else{$txt=true;}
			//日付とIDを分離
			if(ereg("( ID:)(.*)",$now,$regs)){
				$id=$regs[2];
				$now=preg_replace("/( ID:.*)/","",$now);
			}else{$id='';}
			//日付と編集markを分離
			$updatemark='';
			if(UPDATE_MARK){
				if(strstr($now,UPDATE_MARK)){
					$updatemark = UPDATE_MARK;
					$now=str_replace(UPDATE_MARK,"",$now);
				}
			}
			//名前とトリップを分離
			$name=strip_tags($name);//タグ除去
			if(ereg("(◆.*)",$name,$regs)){
				$trip=$regs[1];
				$name=preg_replace("/(◆.*)/","",$name);
			}else{$trip='';}

			// 留言儲存
			$dat['y'][$y]['x'][$x] = compact('imgsrc','w','no','sub','name','now','pch','txt','id','updatemark','trip');
			// 變數clear
			unset($img,$src,$imgsrc,$w,$no,$sub,$name,$now,$pch,$txt);
		}

		$x++;
		if($x == CATALOG_X){$y++; $x=0;}
	}

	$prev = $page - $pagedef;
	$next = $page + $pagedef;
	// 改page処理
	if($prev >= 0) $dat['prev'] = PHP_SELF.'?mode=catalog&amp;page='.$prev;
	$paging = "";
	for($i = 0; $i < count($tree) ; $i+=$pagedef){
		if($page==$i){
			$pformat = str_replace("<PAGE>", $i/$pagedef, NOW_PAGE);
		}else{
			$pno = str_replace("<PAGE>", $i/$pagedef, OTHER_PAGE);
			$pformat = str_replace("<PURL>", PHP_SELF."?mode=catalog&amp;page=".$i, $pno);
		}
		$paging.=$pformat;
	}
	$dat['paging'] = $paging;
	if(count($tree) > $next){
		$dat['next'] = PHP_SELF.'?mode=catalog&amp;page='.$next;
	}

	htmloutput(CATALOGFILE,$dat);
}

/* PaintBBS info */

function info(){
	head($dat);

	//投稿功能 start
	if(ADMIN_NEWPOST < 1) {
		$adnewpost = "開啟";
		} else {
		$adnewpost = "關閉";
		}
	//投稿功能 end
	//選擇文字顏色 start
	if(USE_FONTCOLOR < 1) {
		$fcolor = "否";
		} else {
		$fcolor = "可";
		}
	//選擇文字顏色 end
	//URL自動產生連結 start
	if(AUTOLINK < 1) {
		$autolink = "關閉";
		} else {
		$autolink = "開啟";
		}
	//URL自動產生連結 end
	//Tag start
	if(USE_POTITAG < 1) {
		$mtag = "關閉";
		} else {
		$mtag = "開啟";
		}

	if(CONTINUE_LIMIT){
		$continue_limit = CONTINUE_DAYS." 天";
	}else{
		$continue_limit = "無限制";
	}

	//Tag end
	$dat['tomail'] = TO_MAIL;                //管理人mail
	$dat['all'] = (int)($all / 1024);
	$dat['logmax'] = LOG_MAX;                //留言保存數
	$dat['logdel'] = LOG_MAX*LOG_LIMIT/100;  //自動刪除舊留言警示
	$dat['maxkb'] = MAX_KB;                  //上傳圖片檔限制大小
	$dat['maxw'] = MAX_W;                    //圖片最大尺寸
	$dat['maxh'] = MAX_H;
	$dat['pmaxw'] = PMAX_W;                  //瀏覽頁面圖片最大尺寸
	$dat['pmaxh'] = PMAX_H;
	$dat['pagedef'] = PAGE_DEF;              //單頁顯示主題數
	$dat['renzoku2'] = RENZOKU2;             //圖片重複投稿等待時間
	$dat['adnewpost'] = $adnewpost;          //投稿功能
	$dat['fcolor'] = $fcolor;                //是否開啟文字顏色
	$dat['mtag'] = $mtag;                    //是否開啟特殊標籤
	$dat['autolink'] = $autolink;            //URL自動產生連結
	$dat['continue_limit'] = $continue_limit;

  htmloutput(INFO,$dat);
}


function rule(){
  jslocation('ac_gallery.php', '奇幻藝廊上傳功能已關閉，請改用奇幻繪圖館'); exit;
	jslocation('ac_gallery_rule.php');
	$dat['POINTS'] = GALLERY_POINTS;
	head($dat);
  htmloutput(RULE,$dat);
}

function gopaint(){
  jslocation('ac_gallery.php', '奇幻藝廊上傳功能已關閉，請改用奇幻繪圖館'); exit;
	$dat['POINTS'] = GALLERY_POINTS;
	head($dat);
  htmloutput(GOPAINT,$dat);
}


/* 独自タグ */
function potitag($str){
	global $tags1,$tags2,$ryfont1,$ryfont2;

	$tagrp = 0;
	$tagrps1 = array();
	$tagrps2 = array();

	while(preg_match('/\[([^\]:]+):([^\]]*)\]/',$str,$match)){
		$str = str_replace($match[0],'<com'.$tagrp.'>',$str);
		array_push($tagrps1,'/<com'.$tagrp.'>/');

		$tag_ex = array();
		$tag_ed = array();
		$base_tags = explode("&#44;",$match[1]);
		$com = $match[2];

		foreach($base_tags as $base_tag){
			$base_tag = trim($base_tag);
			if(ereg('^F',$base_tag)){
				if(ereg('s\(([^\)]+)\)',$base_tag,$m)){$size = $m[1];}
				if(ereg('c\(([^\)]+)\)',$base_tag,$m)){$color = $m[1];}
				if(ereg('f\(([^\)]+)\)',$base_tag,$m)){
					$face = $m[1];
					for($i = 0; $i < count($ryfont1); $i++){
						if($face == $ryfont1[$i]){$face = $ryfont2[$i];}
					}
				}
				$font_ex = 1;
			}
			if($base_tag=='RB'){
				array_push($tag_ex,'<ruby>');
				array_push($tag_ed,'</ruby>');
				$rb_chk = 1;
			}else{
				for($i = 0; $i < count($tags1); $i++){
					if($base_tag==$tags1[$i]){
						array_push($tag_ex,'<'.$tags2[$i].'>');
						$endtag = preg_replace("/^([[:alpha:]]+)(.*)/",'\\1',$tags2[$i]);
						array_push($tag_ed,'</'.$endtag.'>');
						break;
					}
				}
			}
		}

		if($rb_chk){
			if(preg_match('/\(([^\):]+):([^\)]+)\)$/',$com,$m)){
				$com = str_replace($m[0],'('.$m[2].')',$com);
				$rb_color = ' style="color:'.$m[1].'"';
			}
			$com = preg_replace('/\(([^\)]+)\)$/','<rp>(</rp><rt'.$rb_color.'>\\1</rt><rp>)</rp>',$com);
		}

		if($font_ex){
			$size  = ($size)  ? ' size="'.$size.'"' : '';
			$color = ($color) ? ' color="'.$color.'"' : '';
			$face  = ($face)  ? ' face="'.$face.'"' : '';
			array_unshift($tag_ex,"<font$size$color$face>");
			array_unshift($tag_ed,"</font>");
		}

		for($i = 0; $i < count($tag_ex); $i++){
			$com = $tag_ex[$i].$com.$tag_ed[$i];
		}
		array_push($tagrps2,$com);
		++$tagrp;
		unset($tag_ex,$tag_ed,$base_tags,$com,$font_ex,$size,$color,$face,$rb_chk,$rb_color);
	}

	return preg_replace($tagrps1, $tagrps2, $str);
}

/* 独自タグ説明 */
function potitagview(){
	global $tags1,$tags2,$ryfont1,$ryfont2;

	head($dat);
	$dat['potitag_mode'] = true;
	htmloutput(OTHERFILE,$dat);
	exit;
}

/* 文字コード変換 */
function charconvert($str,$charset){
	if(CHARSET_CONVERT) return $str;
	switch($charset){
		case 1 : $charset_mb="EUC-JP";break;
		case 2 : $charset_mb="SJIS";break;
		case 3 : $charset_mb="ISO-2022-JP";break;
		case 4 : $charset_mb="utf-8";break;
		default : $charset_mb=$charset;
	}
	if(function_exists("mb_convert_encoding")&&function_exists("mb_language")&&USE_MB){
		mb_language(LANG);
		return mb_convert_encoding($str, $charset_mb, "auto");

	// jcode.php by TOMO
	}elseif((@file_exists("jcode.phps")||@file_exists("jcode.php"))&&is_numeric($charset)){
		if(@file_exists("jcode.phps")){ require_once('jcode.phps'); }
		else{ require_once('jcode.php'); }
		$jc_from = AutoDetect($str);
		if($charset == 4){
			global $table_jis_utf8;
			include_once('code_table.jis2ucs');
		}
		if($jc_from == 4){
			global $table_utf8_jis;
			include_once('code_table.ucs2jis');
		}
		return JcodeConvert($str, $jc_from, $charset);

	}else{
		return $str;
	}
}

/* HTML出力 */
function htmloutput($template,$dat,$buf_flag=''){
	$buf = charconvert(HtmlTemplate::t_buffer($template,$dat), CHARSET_OUT);
	if($buf_flag){
		return $buf;
	}else{
		header("Content-type: text/html; charset=".CHARSET_HTML);
		echo $buf;
	}
}

function CreateDir($path){
	mkdir($path, 0777);
	chmod($path, 0777);
}



/*-----------Main-------------*/
//init();		//←■■初期設定後は不要なので刪除可■■
deltemp();

//user-code的發行
if(!isset($usercode)){
	$usercode = substr(crypt(md5($IP.ID_SEED.gmdate("Ymd", time()+8*60*60)),'id'),-12);
	//念の為にエスケープ文字があればアルファベットに変換
	$usercode = strtr($usercode,"!\"#$%&'()+,/:;<=>?@[\\]^`/{|}~","ABCDEFGHIJKLMNOabcdefghijklmn");
}
setcookie("usercode", $usercode, time()+86400*365);//1年間

//$email='sage';
/*
switch($mode){
	case 'regist':
		if(ADMIN_NEWPOST && !$resto){
			if($pwd != ADMIN_PASS){ error(MSG029);
			}else{ $admin=$pwd; }
		}
		regist($name,$email,$sub,$com,$url,$pwd,$upfile,$upfile_name,$resto,$pictmp,$picfile);
		break;
	case 'aaddmmiinn':
		valid($pass);
		if($admin=="del") admindel($pass);
		if($admin=="post"){
			$dat['post_mode'] = true;
			$dat['regist'] = true;
			head($dat);
			form($dat,$res,1);
			htmloutput(OTHERFILE,$dat);
		}
		if($admin=="update"){
			updatelog();
			echo "<META HTTP-EQUIV=\"refresh\" content=\"0;URL=".PHP_SELF2."\">";
		}
		break;
	case 'usrdel':
		if(USER_DEL){
			usrdel($del,$pwd);
			updatelog();
			echo "<META HTTP-EQUIV=\"refresh\" content=\"0;URL=".PHP_SELF2."\">";
		}else{error(MSG033);}
		break;
	case 'paint':
		paintform($picw,$pich,$palette,$anime);
		break;
	case 'piccom':
		paintcom($resto);
		break;
	case 'openpch':
		openpch($pch,$sp);
		break;
	case 'continue':
		incontinue($no);
		break;
	case 'contpaint':
		$getpwd=member_id_to_pass($_SESSION['session_userid']);
		echo $getpwd;exit;
		if(CONTINUE_PASS) usrchk($no,$pwd);
		if(ADMIN_NEWPOST) $admin=$pwd;
		paintform($picw,$pich,$palette,$anime,$pch);
		break;
	case 'newpost':
		$dat['post_mode'] = true;
		$dat['regist'] = true;
		head($dat);
		form($dat,'');
		htmloutput(OTHERFILE,$dat);
		break;
	case 'edit':
		editform($del,$pwd);
		break;
	case 'rewrite':
		rewrite($no,$name,$email,$sub,$com,$url,$pwd,$admin);
		break;
	case 'picrep':
		replace($no,$pwd,$stime);
		break;
	case 'catalog':
		catalog();
		break;
// paintbbs info
  case 'info':
    info();
    break;
// paintbbs info
	case 'tag':
		potitagview();
		break;
	default:
		if($res){
			updatelog($res);
		}else{
			echo "<META HTTP-EQUIV=\"refresh\" content=\"0;URL=".PHP_SELF2."\">";
		}
}
*/
$inpage = "AC" ;
$thispage = "AC_POTIBOARD" ;
require ("index.php") ;
?>