<?php
@ini_set('memory_limit', '-1');
@set_time_limit(0);
require_once MODEPATH.'./includes/image.func.php';
require_once MODEPATH.'./'.$adminpath.'/makehtml.func.php';
require_once MODEPATH.'./'.$adminpath.'/httpget.class.php';

function image_resize($f,$t,$tw,$th){
        $temp = array(1=>'gif', 2=>'jpeg', 3=>'png');

        list($fw,$fh,$tmp) = getimagesize($f);

        if(!$temp[$tmp]){
                return false;
        }
        $tmp = $temp[$tmp];
        $infunc = "imagecreatefrom$tmp";
        $outfunc = "image$tmp";

        $fimg = $infunc($f);

        if($fw/$tw > $fh/$th){
                $fw = $tw * ($fh/$th);
        }else{
                $fh = $th * ($fw/$tw);
        }

        $timg = imagecreatetruecolor($tw,$th);
        imagecopyresampled($timg,$fimg,0,0,0,0,$tw,$th,$fw,$fh);
        if($outfunc($timg,$t,100)){
                return true;
        }else{
                return false;
        }
}

$sorts=$fsorts=$uploads=array();
$query = $db -> query("SELECT * FROM {$tablepre}picsort ORDER BY ordermode ");
while($sort = $db -> fetch_array($query)){
	$sorts[$sort['id']]=$sort;
	$fsorts[$sort['upid']][$sort['id']]=$sort;
}

if($editp){
	$pic = $db -> queryarray("SELECT * FROM {$tablepre}pic WHERE pid='$editp'");
	if(!$pic){
		cpmsg('error');
	}
	$query = $db -> query("SELECT * FROM {$tablepre}uploads WHERE pid='$editp'");
		while($upload = $db -> fetch_array($query)){
			$upload['uptime']=gmdate("$dateformat $timeformat", $upload['uptime']+3600*$timeoffset);			
			$upload['filesize']=sizecount($upload['filesize']);
			$uploads[$upload['uid']]=$upload;
		}
	$pic['pname']=str_replace('"', '&quot;', $pic['pname']);
	if(cpchecksubmit('update')){	
		$newpname = trim($newpname);
		if(empty($pnamenew)){
			cpmsg('pic_name_must');
		}
		
		if(empty($newid) || !$sorts[$newid]){
			cpmsg('sort_must');
		}		
		$updfiles =  uploadfile('attachupdate');
		if($updfiles){
			foreach($uploads AS $key => $up){
				$puid = 'uid'.$up['uid'];			
				if(isset($updfiles[$puid])){
					$attach=$updfiles[$puid];
					@unlink(MODEPATH.'./'.$attachdir.'/'.$up['attachment']);
					@unlink(MODEPATH.'./'.$attachdir.'/'.$up['face']);
					$cfg_photo_type = $attach['ext'];
					if($gd && in_array($cfg_photo_type, array('png','jpg','gif','jpeg','bmp'))){
						$face = $attach['path'].'/face_'.random(6).'.'.$attach['ext'];
						$refile = $attach['path'].'/body_'.random(8).'.'.$attach['ext'];
						imageresize(MODEPATH.'./'.$attachdir.'/'.$attach['attachment'],$sppicw,$sppich,MODEPATH.'./'.$attachdir.'/'.$face) ;								
						if($mark != 'off'){
							imgwatermark(MODEPATH.'./'.$attachdir.'/'.$attach['attachment'], $mark,MODEPATH.'./'.$attachdir.'/'.$wartermark,$markview);						
						}	
				
						unset($cfg_photo_type);
					}			
					$db -> query("UPDATE {$tablepre}uploads  SET type='$attach[ext]', filename='$attach[name]',filesize='$attach[size]', filetype='$attach[type]', face='$face', attachment='$attach[attachment]',description='$attach[description]',uptime='$time' WHERE uid='$up[uid]'");
				}
			}
		}
		$upids = '';
		if(!empty($deletea)){
			$common = $commns = $delids =$uidss= '';				
			$query = $db -> query("SELECT * FROM {$tablepre}uploads WHERE pid='$editp'");
			while($ups = $db -> fetch_array($query)){
				if(isset($deletea[$ups['uid']])){				
					@unlink(MODEPATH.'./'.$attachdir.'/'.$ups['attachment']);					
					@unlink(MODEPATH.'./'.$attachdir.'/'.$ups['face']);
					$delids .=	$common.$ups['uid'];					
					$common=',';
				}else{
					$upids.= $commns.$ups['uid'];
					$commns = ',';
					$upk = $attachdesc['uid'. $ups['uid']];
					$db -> query("UPDATE {$tablepre}uploads SET description='$upk' WHERE uid='$ups[uid]'");
				}				
			}
			$db -> query("DELETE FROM {$tablepre}uploads WHERE uid IN($delids)");
		}else{
			if(isset($uploads)){
				foreach($uploads AS $key => $ups){
					$upk = htmlconvert($attachdesc['uid'. $ups['uid']]);
					$db -> query("UPDATE {$tablepre}uploads  SET description='$upk'  WHERE uid='$ups[uid]'");
				}
			}
			$upids = trim($pic['attachment']);
		}
		$upnew=uploadfile();
		if($upnew){
			$newupids=$common='';
			foreach($upnew AS $key => $attach){
					$cfg_photo_type = $attach['ext'];
					if($gd && in_array($cfg_photo_type, array('png','jpg','gif','jpeg','bmp'))){
						$face = $attach['path'].'/face_'.random(6).'.'.$attach['ext'];
						imageresize(MODEPATH.'./'.$attachdir.'/'.$attach['attachment'],$sppicw,$sppich,MODEPATH.'./'.$attachdir.'/'.$face);					
						if($mark != 'off'){
							imgwatermark(MODEPATH.'./'.$attachdir.'/'.$attach['attachment'], $mark,MODEPATH.'./'.$attachdir.'/'.$wartermark,$markview);
						
						}							
						unset($cfg_photo_type);
					}
					$db -> query("INSERT INTO {$tablepre}uploads  (pid, mid, type, filename, filesize, filetype, face, attachment, description, uptime) VALUES ('$editp', '$mm_mid', '$attach[ext]', '$attach[name]', '$attach[size]', '$attach[type]', '$face', '$attach[attachment]', '$attach[description]', '$time') ");
					$newupids.=$common.$db -> insert_id();
					$common=',';
			}	
			$upids = $upids ? $upids.','.$newupids : $newupids;						
		}
		$facenews= '';
		if($delface){
			@unlink(MODEPATH.'./'.$attachdir.'/'.$pic['face']);
		}else{
			
			$facenews= $pic['face'] ? $pic['face'] : '';
			$upcace = uploadfile('facenew');
			if($upcace){
				@unlink(MODEPATH.'./'.$attachdir.'/'.$pic['face']);
				$facenews=$upcace['face'.$editp]['attachment'];
				$cfg_photo_type =$upcace['face'.$editp]['ext'];
				if($gd && in_array($cfg_photo_type, array('png','jpg','gif','jpeg','bmp'))){
				
					imageresize(MODEPATH.'./'.$attachdir.'/'.$facenews,$sppicw,$sppich,MODEPATH.'./'.$attachdir.'/'.$facenews) ;
		
					unset($cfg_photo_type);
				}				
			}
		}
		$db -> query("UPDATE {$tablepre}pic SET  id='$newid', pname='$pnamenew', face='$facenews', attachment='$upids', about='$message' WHERE pid='$editp'");
		//userlogs
		makepage($editp);
		
		makeindex();
		cpmsg('succeeded', 'index.php?action=pic');
	}else{
		$select = sortselect($fsorts,$pic['id']);
		include theme('pic_edit', 'themes/admin', 'admin');
	
	}

		
}elseif(cpchecksubmit('makehtml')){
		$ids = idarray($delete);
		$query = $db -> query("SELECT * FROM {$tablepre}pic WHERE pid IN($ids)");
		
		while($pagedb = $db -> fetch_array($query)){
			makepage($pagedb['pid']);

		}
	cpmsg("makehtml_ok",'index.php?action=pic');
}elseif($makepage){
		$ids = idarray($delete);
		$pagedb = $db -> queryarray("SELECT * FROM {$tablepre}pic WHERE pid='$makepage'");
		if($pagedb) {
				makepage($makepage);

		}
		cpmsg("makehtml_ok",'index.php?action=pic');
}elseif(cpchecksubmit('updatelist')){
	if(is_array($delete) && count($delete)){
		$ids = idarray($delete);
		$sort = $db -> queryarray("SELECT id FROM {$tablepre}picsort WHERE id='$newid'");
		if(!$newid || !$sort['id']) {
			cpmsg('sort_must');
		}
		$query = $db -> query("SELECT * FROM {$tablepre}pic WHERE pid IN($ids)");
		
		while($pagedb = $db -> fetch_array($query)){
			@unlink(modepath.'.'.$sorts[$pagedb['id']]['folderdir'].'/'.$pagedb['pid'].'.html');
		}
		$db -> query("UPDATE {$tablepre}pic SET id='$newid' WHERE pid IN($ids)");	
		$query = $db -> query("SELECT * FROM {$tablepre}pic WHERE pid IN($ids)");
		
		while($pagedb = $db -> fetch_array($query)){
			makepage($pagedb['pid']);

		}
		makeindex();
		cpmsg('succeeded', 'index.php?action=pic');		
	}else{
		cpmsg('error');
	}
}elseif(cpchecksubmit('dels')){
	if(is_array($delete) && count($delete)){
		$ids = idarray($delete);
		$query = $db -> query("SELECT p.*,s.folderdir FROM {$tablepre}pic p LEFT JOIN {$tablepre}picsort s ON s.id=p.id WHERE p.pid IN($ids)");
		$pics = $common='';
		while($pic = $db -> fetch_array($query)){
			if($pic['face'] && file_exists(MODEPATH.'./'.$attachdir.'/'.$pic['face'])) {
				@unlink(MODEPATH.'./'.$attachdir.'/'.$pic['face']);
			}
			@unlink(MODEPATH.$pic['folderdir'].'/'.$pic['pid'].'.html');
		}
		
		$db -> query("DELETE FROM {$tablepre}pic WHERE pid IN($ids)");
		$query = $db -> query("SELECT * FROM {$tablepre}uploads WHERE pid IN($ids)");
		while($pic = $db -> fetch_array($query)){
				@unlink(MODEPATH.'./'.$attachdir.'/'.$pic['face']);
				@unlink(MODEPATH.'./'.$attachdir.'/'.$pic['attachment']);
		}
		$db -> query("DELETE FROM {$tablepre}uploads WHERE pid IN($ids)");
		makeindex();
		cpmsg('succeeded', 'index.php?action=pic');		
	}else{
		cpmsg('error');
	}
}elseif($digest){
	if(is_array($delete)) {
		$ids = idarray($delete);
		$query = $db -> query("SELECT * FROM {$tablepre}pic WHERE pid IN($ids)");
		while($pic = $db-> fetch_array($query)) {	
			$dig=$pic['digest'] ? 0 : 1;
			$db -> query("UPDATE {$tablepre}pic SET digest='$dig' WHERE  pid='$pic[pid]'");
		}		
	}else{
		$pic = $db -> queryarray("SELECT * FROM {$tablepre}pic WHERE pid='$digest'");
		$dig=$pic['digest'] ? 0 : 1;
		$db -> query("UPDATE {$tablepre}pic SET digest='$dig' WHERE  pid='$digest'");
	}	
	$width = $ppicw;
	$height = $ppich;
	$line = 5;
		if ($dh = opendir(MODEPATH.'./flashshow')) {
			while (($file = readdir($dh)) !== false) {
				if ($file != "." && $file != "..") {		
			
						@unlink(MODEPATH.'./flashshow/' . $file);
						
		
				}   
			}
			closedir($dh);
		}
	$query = $db -> query("SELECT COUNT(*) FROM {$tablepre}pic WHERE digest='1'");
	$lines = $db -> result($query,0);
	if($lines > $line) {
		$num = rand(1,$lines-$line);
	}else{
		$num = 0;
	}
	
	$query = $db -> query("SELECT p.*,s.folderdir FROM {$tablepre}pic p LEFT JOIN {$tablepre}picsort s ON s.id=p.id WHERE p.digest='1' ORDER BY p.postime DESC LIMIT $num,$line");
	$i=0;
	$xml = '<?xml version="1.0" encoding="'.$charset.'"?>'."\n"
	.'<viewer interval="4000" isRandom="1">'."\n";

	while($pic = $db -> fetch_array($query)) {	
		$pics = $db -> queryarray("SELECT * FROM {$tablepre}uploads WHERE pid='$pic[pid]' LIMIT 1");
		$i++;
		$ext = fileext($pics['attachment']);
		$ext = $ext ? $ext : 'jpg';
		$imgname = '/flashshow/img_'.random(5);
		$img = $imgname.'.'.$ext;
		$imga = $imgname.'a.'.$ext;
		$imgb = $imgname.'b.'.$ext;
		image_resize(MODEPATH.$attachdir.'/'.$pics['attachment'],MODEPATH.'.'.$img,$width,$height);
		//image_resize(MODEPATH.$attachdir.'/'.$pics['attachment'],MODEPATH.'.'.$imga,105,60);
		//image_resize(MODEPATH.$attachdir.'/'.$pics['attachment'],MODEPATH.'.'.$imgb,52,52);
		$xml.= '<item title="'.$pic['pname'].'" img="'.$siteurl.''.$img.'" url="'.$pic['folderdir'].'/'.$pic['pid'].'.html" target="_blank" />'."\n";
	}
	$xml.='</viewer>';
	writetofile(MODEPATH.'./flashshow/list.xml',$xml);
	makeindex();
	cpmsg('succeeded', 'index.php?action=pic');	
}elseif($del){
	$pic = $db -> queryarray("SELECT p.*,s.folderdir FROM {$tablepre}pic p LEFT JOIN {$tablepre}picsort s ON s.id=p.id WHERE p.pid='$del'");
	if($pic['face'] && file_exists(MODEPATH.'./'.$attachdir.'/'.$pic['face'])) {
		@unlink(MODEPATH.'./'.$attachdir.'/'.$pic['face']);
	}
	@unlink(MODEPATH.$pic['folderdir'].'/'.$del.'.html');
	$db -> query("DELETE FROM {$tablepre}pic WHERE pid='$del'");	


	$query = $db -> query("SELECT * FROM {$tablepre}uploads WHERE pid='$del'");
	while($pic = $db -> fetch_array($query)){
			@unlink(MODEPATH.'./'.$attachdir.'/'.$pic['face']);
			@unlink(MODEPATH.'./'.$attachdir.'/'.$pic['attachment']);
	}
	$db -> query("DELETE FROM {$tablepre}uploads WHERE  pid='$del'");
	cpmsg('succeeded', 'index.php?action=pic');	

}else{
	if(cpchecksubmit('add')){
		if(empty($newid) || !$sorts[$newid]){
			cpmsg('sort_must');
		}
		$newpname = trim($newpname);
		if(empty($newpname)){
			cpmsg('pic_name_must');
		}	
		$uids=$newfaces=$common='';
		$isget = false;
		$uploadfile = array();	
		if($getpicmode == 'getfromtxt' || $getpicmode=='getfromurl'){
			$get = new httpget;
			$html = '';
			if($getpicmode =='getfromurl' && isurl($fromurl)) {
				$html = $get -> openurl($fromurl);
			}
			if($getpicmode == 'getfromtxt' && $fromtext) {
				$html = stripslashes($fromtext);
			}
		
			if($html) {
				$image_array = array();
				preg_match_all("/(src|SRC)=[\"|'| ]{0,}(http:\/\/(.*)\.(gif|jpg|jpeg|bmp|png))/isU",$html,$image_array);
	
				if(count($image_array[2])) {
					$isget = true;
					$images = array_unique($image_array[2]);
					 $attach_subdir = 'day_'.date('Ymd');
					if(!is_dir(MODEPATH.'./'.$attachdir.'/'. $attach_subdir.'/')) {
						@mkdir(MODEPATH.'./'.$attachdir.'/'. $attach_subdir.'/', 0777);
						@fclose(@fopen(MODEPATH.'./'.$attachdir.'/'. $attach_subdir.'/index.htm', 'w'));
					}

					foreach($images as $key => $img){
						if($getpicmode=='getfromurl') {
							$img = $get -> formaturl($img);
						}
						$ext = strtolower(fileext($img));
						if((($urlmust && strpos($img,$urlmust)) || !$urlmust) && in_array($ext, array('png','jpg','gif','jpeg','bmp'))) {
							$list = explode('/',$img);
							$filename = $list[count($list)-1];
										
							$attachment=date('Ymd').'_'.substr(md5($filename.microtime()), 6).random(6).'.'.$ext;
							$target = MODEPATH.'./'.$attachdir.'/'. $attach_subdir.'/'.stripslashes($attachment);
							$getcode = $get -> openurl($img);
							writetofile($target,$getcode);
							unset($getcode);
							$filesize = @filesize($target);

							if($filesize > 0) {
								$uploadfile[$key]['name']=$filename;
								$uploadfile[$key]['ext']=$ext;		
								$uploadfile[$key]['attachment'] = $attach_subdir.'/'.$attachment;
								$uploadfile[$key]['size'] = $filesize;
								$uploadfile[$key]['path'] =  $attach_subdir;

							}else{
								@unlink($target);
							}
									
						}
					}
				}			
			}
		}else{
			$uploadfile = uploadfile();
		}
		$upface = uploadfile('newface');
		if($uploadfile){
			$i=0;
			foreach($uploadfile AS $key => $attach){
				$i++;
			
					$cfg_photo_type = $attach['ext'];
					$face='';
					if($gd && in_array($cfg_photo_type, array('png','jpg','gif','jpeg','bmp'))){
						$face = $attach['path'].'/face_'.random(6).'.'.$attach['ext'];

						imageresize(MODEPATH.'./'.$attachdir.'/'.$attach['attachment'],$sppicw,$sppich,MODEPATH.'./'.$attachdir.'/'.$face) ;				
						if($mark != 'off'){
							imgwatermark(MODEPATH.'./'.$attachdir.'/'.$attach['attachment'], $mark,MODEPATH.'./'.$attachdir.'/'.$wartermark,$markview);
						}	
						if(($isget && $i==1) || (!$upface && $i==1)) {
							$newfaces=$attach['path'].'/face_'.random(6).'.'.$attach['ext'];
							@copy(MODEPATH.'./'.$attachdir.'/'.$face,MODEPATH.'./'.$attachdir.'/'.$newfaces);
						}						
						unset($cfg_photo_type);
					}
					$db -> query("INSERT INTO {$tablepre}uploads  (mid, type, filename, filesize, filetype, face, attachment, description, uptime) VALUES ( '$mm_mid', '$attach[ext]', '$attach[name]', '$attach[size]', '$attach[type]', '$face', '$attach[attachment]', '$attach[description]', '$time') ");
					$upids.=$common.$db -> insert_id();
					$common=',';
				}
		}
		if($upface){
			$newfaces=$upface[0]['attachment'];
				$cfg_photo_type =$upface[0]['ext'];
					if($gd && in_array($cfg_photo_type, array('png','jpg','gif','jpeg','bmp'))){					
						imageresize(MODEPATH.'./'.$attachdir.'/'.$newfaces,$sppicw,$sppich,MODEPATH.'./'.$attachdir.'/'.$newfaces);			
						unset($cfg_photo_type);
					}
		}
		$db -> query("INSERT INTO {$tablepre}pic (id,pname, face,postime, attachment, about) VALUES('$newid',  '$newpname', '$newfaces', '$time', '$upids', '$message')");
		$pid = $db -> insert_id();
		if($upids) {
			$db -> query("UPDATE {$tablepre}uploads SET pid='$pid' WHERE uid IN($upids)");
		}
		makepage($pid);

		makeindex();
		dsetcookie('_urlmust', $urlmust, 3600);
		dsetcookie('_getpicmode', $getpicmode, 3600);
		dsetcookie('_id', $newid, 3600);
		dsetcookie('_postnext', $postnext, 3600);	
		cpmsg('succeeded', 'index.php?action='.($postnext ? 'pic_post' : 'pic'));
	
	}else{
		$urlmust = $_DCOOKIE['_urlmust'] ? $_DCOOKIE['_urlmust'] : '';
		$postnext = $_DCOOKIE['_postnext'] ? ' checked' : '';
		$_getpicmode = $_DCOOKIE['_getpicmode'] ? $_DCOOKIE['_getpicmode'] : 'upload';
		switch($_getpicmode) {
			case 'upload': $getpicmode0='checked'; break;
			case 'getfromurl': $getpicmode1='checked';break;
			case 'getfromtxt': $getpicmode2='checked';break;
		}
		$_id = $_DCOOKIE['_id'] ? $_DCOOKIE['_id'] : 0;

		$select = sortselect($fsorts,$_id);
		include theme('pic_post', 'themes/admin', 'admin');
	
	}

}

?>