<?php
// ------------------------------------------------------------------------- //
//                      IMGTag for TacmicCMS                                 ////                        <https://impresscms.jp/>                           //
// ------------------------------------------------------------------------- //

include('header.php');
//include_once(XOOPS_ROOT_PATH . '/class/xoopstree.php');
//include_once(dirname(dirname(__FILE__)).'/class/myuploader.php');

//include_once(dirname(dirname(__FILE__)).'/class/d3imgtag.textsanitizer.php');

//$myts =& d3imgtagTextSanitizer::getInstance();
$myts =& icms_core_Textsanitizer::getInstance();


$cattree = new icms_view_Tree($table_cat , 'cid' , 'pid');

$lid = empty($_GET['lid']) ? 0 : intval($_GET['lid']);

$result = $xoopsDB->query("SELECT submitter FROM $table_photos WHERE lid='$lid'");
list($submitter) = $xoopsDB->fetchRow($result);

if($global_perms & D3IMGTAG_GPERM_EDITABLE) {
	if($my_uid != $submitter && ! $isadmin) {
		redirect_header($mod_url.'/' , 3 , _NOPERM);
		exit;
	}
} else {
	redirect_header($mod_url.'/' , 3 , _NOPERM);
	exit;
}

// 削除を選択した時
if(!empty($_POST['do_delete'])) {

	if(!($global_perms & D3IMGTAG_GPERM_DELETABLE)) {
		redirect_header($mod_url.'/' , 3 , _NOPERM);
		exit ;
	}
	// anti-CSRF
	if(!icms::$security->checkReferer()) die("XOOPS_URL is not included in your REFERER");

	// Ticket Check
	if ( ! $xoopsGTicket->check() ) {
		redirect_header(XOOPS_URL.'/',3,$xoopsGTicket->getErrors());
	}

	// get and check lid is valid
	if($lid < 1) die("Invalid photo id.");

	$whr = "lid=$lid";
	if(!$isadmin) $whr .= " AND submitter=$my_uid";

	d3imgtag_delete_photos($whr);

	redirect_header($mod_url.'/' , 3 , _MD_D3IMGTAG_DELETINGPHOTO);
	exit ;
}

// 削除を確認した時
if(!empty($_POST['conf_delete'])) {

	if(! ($global_perms & D3IMGTAG_GPERM_DELETABLE)) {
		redirect_header($mod_url.'/' , 3 , _NOPERM);
		exit ;
	}

	include(XOOPS_ROOT_PATH."/include/cp_functions.php");
	include_once(XOOPS_ROOT_PATH . "/header.php");

	echo "<table width='100%' border='0' cellspacing='1' cellpadding='8' style='border: 2px solid #2F5376;'><tr class='bg4'><td valign='top'>\n";

	$result = $xoopsDB->query("SELECT l.ext, l.img FROM $table_photos l WHERE l.lid=$lid");
	list($ext, $img) = $xoopsDB->fetchRow($result);
	if(! in_array(strtolower($ext) , $d3imgtag_normal_exts)) $ext = 'gif' ;

	echo "
	<h4>"._MD_D3IMGTAG_PHOTODEL."</h4>
	<div>
		<img src='$thumbs_url/$img.$ext' />
		<br />
		<form action='index.php?page=editphoto&lid=$lid' method='post'>
			".$xoopsGTicket->getTicketHtml( __LINE__ )."
			<input type='submit' name='do_delete' value='"._YES."' />
			<input type='submit' name='cancel_delete' value="._NO." />
		</form>
	</div>
	\n";

	echo '</td></tr></table>\n';
	include(XOOPS_ROOT_PATH . "/footer.php");
	exit();
}


// 修正をかけた時
if(!empty($_POST['submit'])) {

	// 画像フォルダのチェック
	if(! is_dir($photos_dir)) {
		if($safe_mode_flag) {
			redirect_header(XOOPS_URL."/modules/$mydirname/",10,"At first create & chmod 777 '$photos_dir' by ftp or shell.");
			exit;
		}

		$rs = mkdir($photos_dir , 0777);
		if(!$rs) {
			redirect_header(XOOPS_URL."/modules/$mydirname/",10,"$photos_dir is not a directory");
			exit;
		} else @chmod($photos_dir , 0777);
	}

	// プレビューフォルダのチェック
	if($d3imgtag_makepreview && ! is_dir($previews_dir)) {
		if($safe_mode_flag) {
			redirect_header(XOOPS_URL."/modules/$mydirname/",10,"At first create & chmod 777 '$previews_dir' by ftp or shell.");
			exit;
		}

		$rs = mkdir($previews_dir , 0777);
		if(!$rs) {
			redirect_header(XOOPS_URL."/modules/$mydirname/",10,"$previews_dir is not a directory");
			exit;
		} else @chmod($previews_dir , 0777);
	}


	// サムネイルフォルダのチェック
	if($d3imgtag_makethumb && ! is_dir($thumbs_dir)) {
		if($safe_mode_flag) {
			redirect_header(XOOPS_URL."/modules/$mydirname/",10,"At first create & chmod 777 '$thumbs_dir' by ftp or shell.");
			exit;
		}

		$rs = mkdir($thumbs_dir , 0777);
		if(!$rs) {
			redirect_header(XOOPS_URL."/modules/$mydirname/",10,"$thumbs_dir is not a directory");
			exit;
		} else @chmod($thumbs_dir , 0777);
	}

	// anti-CSRF
	if(!icms::$security->checkReferer()) die("XOOPS_URL is not included in your REFERER");

	// Ticket Check
	if ( ! $xoopsGTicket->check() ) {
		redirect_header(XOOPS_URL.'/',3,$xoopsGTicket->getErrors());
	}

	if(empty($_POST['submitter'])) {
		$submitter = $my_uid ;
	} else {
		$submitter = intval($_POST['submitter']);
	}

	// status change
	if($isadmin) {
		$valid = empty($_POST['valid']) ? 0 : intval($_POST['valid']);
		if(empty($_POST['old_status'])) {
			if($valid == 0) $valid = null ;
			else $valid = 1 ;
		} else {
			if($valid == 0) $valid = 0 ;
			else $valid = 2 ;
		}
	} else {
		$valid = 2 ;
	}

	$cid = empty($_POST['cid']) ? 0 : intval($_POST['cid']);

	// Check if upload file name specified
	$field = $_POST["xoops_upload_file"][0];

	if($_FILES[$field]['name'] == ''){ // 画像がアップロードされていない時
		// Check if title is blank
		if(trim($_POST["title"]) === "") {
			$_POST['title'] = 'no title' ;
		}
		$title = $myts->stripSlashesGPC($_POST["title"]);
		$desc_text = $myts->stripSlashesGPC($_POST["desc_text"]);
		$cid = intval($_POST['cid']);
		d3imgtag_update_photo($lid , $cid , $title , $desc_text , $valid);
	} else { // 画像がアップロードされている
		if($d3imgtag_canresize) {
			$uploader = new icms_file_MediaUploadHandler($photos_dir , $array_allowed_mimetypes , $d3imgtag_fsize , null , null);
		} else {
			$uploader = new icms_file_MediaUploadHandler($photos_dir , $array_allowed_mimetypes , $d3imgtag_fsize , $d3imgtag_width , $d3imgtag_height);
		}
		$uploader->setPrefix('tmp_');
		if($uploader->fetchMedia($field) && $uploader->upload()) { // アップロードに成功している
			if(trim(@$_POST["title"]) === "") { // 表題がなかったら
				$_POST['title'] = $uploader->getMediaName();
			}
			$tmp_name = $uploader->getSavedFileName();
			$fileSize = $uploader->getMediaSize();
			$fileName = createFileName($d3imgtag_minfile, $d3imgtag_maxfile, $d3imgtag_filerule);

		} else { // アップロードに失敗した（指定のサイズとか容量とかがオーバーしている)
			include(XOOPS_ROOT_PATH."/header.php");

			echo $uploader->getErrors();
			@unlink($uploader->getSavedDestination());

			include(XOOPS_ROOT_PATH . "/footer.php");
			exit;
		}

		if(! is_readable("$photos_dir/$tmp_name")) {	// データを読めなかったらエラー
			redirect_header('index.php?page=submit' , 2 , _MD_D3IMGTAG_FILEREADERROR);
			exit;
		}

		$title = $myts->stripSlashesGPC(@$_POST["title"]);
		$desc_text = $myts->stripSlashesGPC(@$_POST["desc_text"]);
		$shareimg = @$_POST["shareimg"];
		if ($shareimg != 1)
			$shareimg = 0;

		$date = time();
		$ext = substr(strrchr($tmp_name , '.') , 1);
		$ext2 = "webp";
		$status = ($global_perms & D3IMGTAG_GPERM_SUPERINSERT) ? 1 : 0 ;
		
		// 従来のファイルを削除する
		$prs = $xoopsDB->query("SELECT img, ext FROM $table_photos WHERE lid=$lid");
		list($img, $ext) = $xoopsDB->fetchRow($prs);
		@unlink("$photos_dir/$img.$ext");
		@unlink("$thumbs_dir/$img.$ext");
		@unlink("$previews_dir/$img.$ext");
	
		// 画像ファイルをセットする
		d3imgtag_modify_photo("$photos_dir/$tmp_name" , "$photos_dir/$fileName.$ext2");
		$dim = GetImageSize("$photos_dir/$fileName.$ext2");
		if($dim) $xoopsDB->query("UPDATE $table_photos SET res_x='{$dim[0]}', res_y='{$dim[1]}' WHERE lid=$lid");
	
		// サムネイルを作成する
		if(!d3imgtag_create_thumb("$photos_dir/$fileName.$ext2", $fileName, $ext2)) {
			$xoopsDB->query("DELETE FROM $table_photos WHERE lid=$lid");
			redirect_header('index.php?page=submit' , 2 , _MD_D3IMGTAG_FILEREADERROR);
			exit;
		}
	
		if(! d3imgtag_create_preview("$photos_dir/$fileName.$ext2", $fileName, $ext2)) {
			$xoopsDB->query("DELETE FROM $table_photos WHERE lid=$led");
			redirect_header('index.php?page=submit' , 2 , _MD_D3IMGTAG_FILEREADERROR);
			exit;
		}
	
		$sql = "update $table_photos set ";
		$sql .= "`img` = '" . addslashes($fileName) . "',";
		$sql .= "`cid` = '" . $_POST['cid'] . "',";
		$sql .= "`title` = '" . $title . "',";
		$sql .= "`ext` = '" . $ext2 . "',";
		$sql .= "`size` = '" . $fileSize . "',";
		$sql .= "`submitter` = '" . $submitter . "',";
		$sql .= "`date` = '" . $date . "' ";
		$sql .= " where lid='" . $lid . "'";
		$xoopsDB->queryF($sql) or die("DB error: UPDATE data table " . $sql);

		echo $sql;
		// テキストのアップデート
		$sql = "update $table_text set `description`='". addslashes($desc_text)."' where lid='" . $lid . "'";
		$xoopsDB->queryF($sql) or die("DB error: UPDATE text table " . $sql);

	}
	redirect_header('index.php?page=photo&lid=' . $lid , 12 , "データを更新しました");
}


// Editing Display
include(XOOPS_ROOT_PATH."/header.php");

echo "<table width='100%' border='0' cellspacing='1' cellpadding='8' style='border: 2px solid #2F5376;'><tr class='bg4'><td valign='top'>\n";

include_once(XOOPS_ROOT_PATH . '/class/xoopsformloader.php');
include_once(XOOPS_ROOT_PATH . '/include/xoopscodes.php');

// Get the record
$result = $xoopsDB->query("SELECT l.lid, l.img, l.cid, l.title, l.share, l.size, l.ext, l.res_x, l.res_y, l.status, l.date, l.hits, l.rating, l.votes, l.comments, l.submitter, t.description FROM $table_photos l LEFT JOIN $table_text t ON l.lid=t.lid WHERE l.lid=$lid");
$photo = $xoopsDB->fetchArray($result);

// Preview
if(! empty($_POST['preview'])) {
	$photo['description'] = $myts->stripSlashesGPC($_POST["desc_text"]);
	$photo['title'] = $myts->stripSlashesGPC($_POST["title"]);
}


// Display
$photo_for_tpl = d3imgtag_get_array_for_photo_assign($photo);
require_once XOOPS_ROOT_PATH.'/class/template.php' ;
	$tpl = new icms_view_Tpl() ;
/*
include(dirname(dirname(__FILE__)).'/include/assign_globals.php');
$tpl->assign($d3imgtag_assign_globals);
$tpl->assign('photo' , $photo_for_tpl);
echo "<table class='outer' style='width:100%;'>";
$tpl->display("db:{$mydirname}_photo_in_list.html");
echo "</table>\n";
*/

echo '<div class="padded align-center">';
$ptpl = d3imgtag_get_array_for_photo_assign($photo);
echo '<img src="' . $mod_url . '/index.php?page=image&id=' . $ptpl['lid'] . '&sz=1" bolder="0" />';
echo "</div>";


// Show the form
$form = new  icms_form_Theme(_MD_D3IMGTAG_PHOTOEDITUPLOAD , "uploadphoto", "index.php?page=editphoto&lid=$lid");
$form->setExtra("enctype='multipart/form-data'");

$title_text = new icms_form_elements_Text(_MD_D3IMGTAG_PHOTOTITLE , "title" , 50 , 255 , $myts->makeTboxData4Edit($photo['title']));

$cat_select = new icms_form_elements_Select('' , "cid" , $photo['cid']);
$tree = $cattree->getChildTreeArray(0 , "title");
foreach($tree as $leaf) {
	$leaf['prefix'] = substr($leaf['prefix'] , 0 , -1);
	$leaf['prefix'] = str_replace("." , "--" , $leaf['prefix']);
	$cat_select->addOption($leaf['cid'] , $leaf['prefix'] . $leaf['title']);
}

$cat_link = new icms_form_elements_Label("<a href='javascript:location.href=\"index.php?page=viewcat&cid=\"+document.uploadphoto.cid.value;'>"._GO."</a>");
$cat_tray = new icms_form_elements_Tray(_MD_D3IMGTAG_PHOTOCAT , '&nbsp;');
$cat_tray->addElement($cat_select);
$cat_tray->addElement($cat_link);

$desc_tarea = new icms_form_elements_cktextarea(_MD_D3IMGTAG_PHOTODESC , "desc_text" , $myts->makeTareaData4Edit($photo['description']) , 10 , 50);

$file_form = new icms_form_elements_File(_MD_D3IMGTAG_SELECTFILE , "photofile" , $d3imgtag_fsize);
$file_form->setExtra("size='70'");

if($d3imgtag_canrotate) {
	$rotate_radio = new icms_form_elements_Radio(_MD_D3IMGTAG_RADIO_ROTATETITLE , 'rotate' , 'rot0');
	$rotate_radio->addOption('rot0' , _MD_D3IMGTAG_RADIO_ROTATE0." &nbsp; ");
	$rotate_radio->addOption('rot90' , "<img src='images/rotate90.png' alt='"._MD_D3IMGTAG_RADIO_ROTATE90."' title='"._MD_D3IMGTAG_RADIO_ROTATE90."' /> &nbsp; ");
	$rotate_radio->addOption('rot180' , "<img src='images/rotate180.png' alt='"._MD_D3IMGTAG_RADIO_ROTATE180."' title='"._MD_D3IMGTAG_RADIO_ROTATE180."' /> &nbsp; ");
	$rotate_radio->addOption('rot270' , "<img src='images/rotate270.png' alt='"._MD_D3IMGTAG_RADIO_ROTATE270."' title='"._MD_D3IMGTAG_RADIO_ROTATE270."' /> &nbsp; ");
}

$op_hidden = new icms_form_elements_Hidden("op" , "submit");
$counter_hidden = new icms_form_elements_Hidden("fieldCounter" , 1);
$status_hidden = new icms_form_elements_Hidden("old_status" , $photo['status']);
$valid_or_not = empty($photo['status']) ? 0 : 1 ;
$valid_box = new icms_form_elements_Checkbox(_MD_D3IMGTAG_VALIDPHOTO , "valid" , array($valid_or_not));
$valid_box->addOption('1' , '&nbsp;');

$submit_button = new icms_form_elements_Button("" , "submit" , _SUBMIT , "submit");
$preview_button = new icms_form_elements_Button("" , "preview" , _PREVIEW , "submit");
$reset_button = new icms_form_elements_Button("" , "reset" , _CANCEL , "reset");
$submit_tray = new icms_form_elements_Tray('');
$submit_tray->addElement($preview_button);
$submit_tray->addElement($submit_button);
$submit_tray->addElement($reset_button);
if($global_perms & D3IMGTAG_GPERM_DELETABLE) {
	$delete_button = new icms_form_elements_Button("" , "conf_delete" , _DELETE , "submit");
	$submit_tray->addElement($delete_button);
}

$form->addElement($title_text);
$form->addElement($desc_tarea);
$form->addElement($cat_tray);


$form->addElement($file_form);
if($d3imgtag_canrotate) $form->addElement($rotate_radio);
$form->addElement($counter_hidden);
$form->addElement($op_hidden);
if($isadmin) {
	$form->addElement($valid_box);
	$form->addElement($storets_box) ;
	$form->addElement($status_hidden);
}
$form->addElement($submit_tray);

// Ticket
$GLOBALS['xoopsGTicket']->addTicket_icms_form_Element( $form , __LINE__ ) ;

$form->display();

echo '</td></tr></table>\n';

d3imgtag_footer();

include(XOOPS_ROOT_PATH . "/footer.php");

?>
