<?php

//投稿権限が無い場合
if(!$gperm->group_perm(1)){
	die(_NOPERM);
	exit();
}

// トピックがない場合
$BTopic = new D3newsTopic( $mydirname );
if( !$BTopic->topicExists() ){
	die(_MD_NO_TOPICS);
	exit;
}

//
$op = isset($_POST['op']) ? trim($_POST['op']) : 'form';
$op = isset($_GET['op']) && $_GET['op'] == 'delete' ? 'delete' : $op;

// error log
$errors = array();

// チケットのチェック
require_once dirname(dirname(__FILE__))."/include/gtickets.php";
if ( !empty($_POST['preview']) ) {
	if ( ! $xoopsGTicket->check() ) {
		$errors['ticket'] = 'Ticket Error';
		$op = 'form';
	} else {
		$op = 'preview';
	}
}elseif( !empty($_POST['post']) ) {
	if ( ! $xoopsGTicket->check() ) {
		$errors['ticket'] = 'Ticket Error';
		$op = 'form';
	} else {
		$op = 'post';
	}
}

$storyid = isset( $_GET['storyid'] ) ? intval($_GET['storyid']) : 0 ;
$storyid = isset( $_POST['storyid'] ) ? intval($_POST['storyid']) : $storyid ;
$return = isset( $_GET['return'] ) ? intval($_GET['return']) : 0 ;
$return = isset( $_POST['return'] ) ? intval($_POST['return']) : $return ;

$story = new D3news( $mydirname , $storyid );

if($story->getVar('image')) {
	$imgmsg = "<img src='" . XOOPS_URL . "/uploads/d3news/t_" . $story->getVar('image') . "' class='uploaded thumb' alt='' /><br />";
}


// 編集権限が無い場合
if( $storyid > 0 && !$isadmin ){
	die(_NOPERM);
	exit();
}

// トピックIDが指定されている場合
if( isset( $_GET['topicid'] ) ) $story->setVar('topicid', $_GET['topicid']);

// エディタ切替の結果を反映
if( ! empty( $_REQUEST['using_fck'] ) ) {
	$_POST['text'] = $_POST['text_fck'] ;
}

// ホワイトリストによるサニタイズ
$str_arr = array('title','text','image');
$int_arr = array('topicid','type','topicimg','published','expired','weight');
$bai_arr = array('html','smiley','br','xcode','autodate','autoexpdate','notifypub','block','ihome','approve');
foreach( $str_arr as $k ){
	if( isset($_POST[$k]) ) $story->setVar($k, $_POST[$k]);
}
foreach( $int_arr as $k ){
	if( isset($_POST[$k]) ) $story->setVar($k, $_POST[$k]);
}
foreach( $bai_arr as $k ){
	if( $_SERVER['REQUEST_METHOD'] == 'POST' ){
		$_POST[$k] = isset( $_POST[$k] ) ? 1 : 0 ;
		$story->setVar($k, $_POST[$k]);
	}
}

// relation
if( $gperm->group_perm(7) && $d3news_use_relations ){
	if( isset($_POST['storyidRH']) && isset($_POST['dirnameR']) && is_array($_POST['storyidRH']) && is_array($_POST['dirnameR']) ){
		foreach( $_POST['storyidRH'] as $k => $v ){
			$relations[$k]['dirname'] = $_POST['dirnameR'][$k];
			$relations[$k]['linkedid'] = intval($v);
		}
	}elseif( $storyid > 0 && is_array($relation_arr = $story->relation->getRelations($storyid)) && $op == 'form' ){
		$relations = $relation_arr;
	}else{
		$relations = array();
	}
}

if( empty( $storyid ) ){
	// 権限がない場合HTMLをOFF
	if( !$gperm->group_perm(4) ){
		$story->setVar('html', 0);
		$story->setVar('br', 1);
	}
	if( !$gperm->group_perm(2) ){
		$story->setVar('approve', 0);
	}
}

if( $op == 'post' ){

	$time = time();

	$auto['year']  = isset( $_POST['auto']['year'] )  ? intval( $_POST['auto']['year'] )  : formatTimestamp($time, 'Y');
	$auto['month'] = isset( $_POST['auto']['month'] ) ? intval( $_POST['auto']['month'] ) : formatTimestamp($time, 'n');
	$auto['day']   = isset( $_POST['auto']['day'] )   ? intval( $_POST['auto']['day'] )   : formatTimestamp($time, 'd');
	$auto['hour']  = isset( $_POST['auto']['hour'] )  ? intval( $_POST['auto']['hour'] )  : formatTimestamp($time, 'H');
	$auto['min']   = isset( $_POST['auto']['min'] )   ? intval( $_POST['auto']['min'] )   : formatTimestamp($time, 'i');
	$auto['sec']   = isset( $_POST['auto']['sec'] )   ? intval( $_POST['auto']['sec'] )   : date('s');

	$autoexp['year']  = isset( $_POST['autoexp']['year'] )  ? intval( $_POST['autoexp']['year'] )  : formatTimestamp($time, 'Y');
	$autoexp['month'] = isset( $_POST['autoexp']['month'] ) ? intval( $_POST['autoexp']['month'] ) : formatTimestamp($time, 'n');
	$autoexp['day']   = isset( $_POST['autoexp']['day'] )   ? intval( $_POST['autoexp']['day'] )   : formatTimestamp($time, 'd');
	$autoexp['hour']  = isset( $_POST['autoexp']['hour'] )  ? intval( $_POST['autoexp']['hour'] )  : formatTimestamp($time, 'H');
	$autoexp['min']   = isset( $_POST['autoexp']['min'] )   ? intval( $_POST['autoexp']['min'] )   : formatTimestamp($time, 'i');
	$autoexp['sec']   = isset( $_POST['autoexp']['sec'] )   ? intval( $_POST['autoexp']['sec'] )   : date('s');


	$fb_send_flag = 1;
	// new post
	if ( empty( $storyid ) ){

		$story->setVar('hostname', xoops_getenv('REMOTE_ADDR'));
		$story->setVar('uid', $my_uid);
		$story->devideHomeTextAndBodyText();

		// 自動承認かどうか
		if( $gperm->group_perm(2) ){
			$story->setVar('type', $story->getVar('approve') ); // GIJ
		}else{
			$story->setVar('type', 0);
		}

		// 掲載予定日設定のルーチン
		if ( $story->getVar('autodate') == 1 && $gperm->group_perm(3) ){
			$pubdate = mktime( $auto['hour'], $auto['min'], $auto['sec'], $auto['month'], $auto['day'], $auto['year'] );
			$offset  = $xoopsUser->timezone() - $xoopsConfig['server_TZ'];
			$pubdate = $pubdate - ( $offset * 3600 );
			$story->setVar('published', $pubdate);
			if($pubdate > time())
				$fb_send_flag = 0;

		}else{
			$story->setVar('published', time());
		}
		// 掲載終了日設定のルーティン
		if ( $story->getVar('autoexpdate') == 1 && $gperm->group_perm(3) ){
			$expdate = mktime( $autoexp['hour'], $autoexp['min'], $autoexp['sec'], $autoexp['month'], $autoexp['day'], $autoexp['year'] );
			$offset = $xoopsUser -> timezone() - $xoopsConfig['server_TZ'];
			$expdate = $expdate - ( $offset * 3600 );
			$story->setVar('expired', $expdate);
		}else{
			$story->setVar('expired', 0);
		}

		$is_new = true;

	// edited post
	}else{

		$fb_send_flag = 0;

		$story->devideHomeTextAndBodyText();

		// approve this article
		$approved = 0;
		if ( $story->getVar('approve') == 1 ){
			if( $story->getVar('type') == 0) $approved = 1;
			$story->setVar('type', 1);
		}else{
			$story->setVar('type', 0);
		}

		// 掲載予定日設定のルーチン
		if ( $story->getVar('autodate') == 1 ){
			$pubdate = mktime( $auto['hour'], $auto['min'], $auto['sec'], $auto['month'], $auto['day'], $auto['year'] );
			$offset = $xoopsUser -> timezone();
			$offset = $offset - $xoopsConfig['server_TZ'];
			$pubdate = $pubdate - ( $offset * 3600 );
			$story->setVar('published', $pubdate);
		} else {
			$story->setVar('published', $time);
		}

		// 掲載終了日設定のルーティン
		if ( $story->getVar('autoexpdate') == 1 ){
			$expdate = mktime( $autoexp['hour'], $autoexp['min'], $autoexp['sec'], $autoexp['month'], $autoexp['day'], $autoexp['year'] );
			if ( !empty( $autoexpdate ) ) $offset = $xoopsUser -> timezone() - $xoopsConfig['server_TZ'];
			$expdate = $expdate - ( $offset * 3600 );
			$story->setVar('expired', $expdate);
		} else {
			$story->setVar('expired', 0);
		}

		$is_new = false;

	}

	if (is_uploaded_file($_FILES["upfile"]["tmp_name"])) {

		// 画像ファイル情報をゲット
		$ufile_oname = $_FILES["upfile"]["name"];
		$ufile_mine  = $_FILES["upfile"]["type"];
		$ufile_size  = $_FILES["upfile"]["size"];
		$ufile_tmp   = $_FILES["upfile"]["tmp_name"];
		$size        = getimagesize("$ufile_tmp");
		$img_w = $size[0];
		$img_h = $size[1];

		$myext = substr($ufile_oname,-3);
		$myext = strtolower($myext);

		$path = XOOPS_ROOT_PATH . "/uploads/d3news/";
        if(!file_exists($path)){
            mkdir($path,0777) ;
        }


		if($myext=='jpg' OR $myext=='peg' OR $myext=='png' OR $myext=='gif' ){

		    //縦か横かでタイプ分け
		      if($size[0] > $size[1]){
			        $img_Type = 1;
    		  }else{
    		    $img_Type = 2;
    		  }

		      $Size_0 = $size[0]; //オリジナルサイズ　横
		      $Size_1 = $size[1]; //オリジナルサイズ　縦

			$fileN = time().'_'.mt_rand(5, 15);
			$new_upload_file  = $path . $fileN . "." . $myext; 		//usual
			$thum_upload_file = $path . "t_" . $fileN . "." . $myext; //thumbnail

			$new_upload_webp  = $path . $fileN . ".webp"; 		//usual
			$thum_upload_webp = $path . "t_" . $fileN . ".webp"; //thumbnail


			$real_file = $fileN.'.'.$myext;
			$real_webp = $fileN.'.webp';
			move_uploaded_file($ufile_tmp,$new_upload_file);

		  $image1 = imagecreatefromstring( file_get_contents($new_upload_file) );
      $image2 = imagecreatefromstring( file_get_contents($new_upload_file) );

		    /*  通常画象リサイズ  */
			$imgSize   = RatioCalculation_l($img_Type,500,500,$Size_0,$Size_1);
			$newwidth  = $imgSize['W'];
			$newheight = $imgSize['H'];

			/* 縮小後のキャンバスを生成 */
			$newimage1        = imagecreatetruecolor($newwidth, $newheight);
			$resize_image1    = imagecopyresampled($newimage1, $image1, 0, 0, 0, 0, $newwidth, $newheight, $img_w, $img_h);
//			imagejpeg($newimage1, $new_upload_file);
			imagewebp($newimage1, $new_upload_webp);

		     /*  Thubmnailサイズ  */
			$imgSize   = RatioCalculation_s($img_Type,200,200,$Size_0,$Size_1);
			$newwidth  = $imgSize['W'];
			$newheight = $imgSize['H'];

			/* 縮小後のキャンバスを生成 */
			$newimage2        = imagecreatetruecolor($newwidth, $newheight);
			$resize_image2    = imagecopyresampled($newimage2, $image2, 0, 0, 0, 0, $newwidth, $newheight, $img_w, $img_h);
//			imagejpeg($newimage2, $thum_upload_file);
			imagejpeg($newimage2, $thum_upload_webp);

//			$story->setVar('image', $real_file);
			$story->setVar('image', $real_webp);
			unlink($new_upload_file);

		}
	}

	//DB挿入時にエラーが発生したら
	if(!$story->store()) {
		die(_MD_THANKS_BUT_ERROR);
	}

	// relation
	if( $gperm->group_perm(7) && $d3news_use_relations ){
		$story->relation->storyid = $story->getVar('storyid');
		$story->relation->cleanup();
		$story->relation->store($relations);
	}

	if( $is_new ){
		$fsend_msg = $story->getVar('hometext', 'n');
		$fsend_msg = mb_substr(strip_tags($fsend_msg),0,200);

		if($real_file){
			$pimg_url = XOOPS_URL . "/uploads/d3news/" . $real_file;
		} else {
			$pimg_url = XOOPS_URL . "/uploads/d3news/noimage.png";
		}


		//投稿数加算処理
		if ($gperm->group_perm(2) && is_object($xoopsUser) && $d3news_plus_posts == 1) {
			$xoopsUser->incrementPost();
		}



		// 自動承認のときはメッセージを変える
		if($gperm->group_perm(2)){
			redirect_header($mydirurl.'/index.php', 2, _MD_THANKS_AUTOAPPROVE);
			exit;
		}
		redirect_header($mydirurl.'/index.php', 3, _MD_THANKS);
		exit;

	} else {

		// イベント通知処理
		$notification_handler =& xoops_gethandler('notification');
		$tags = array();
		$tags['STORY_NAME'] = $myts->stripSlashesGPC($story->getVar('title', 'n'));
		$tags['STORY_URL']  = $mydirurl.'/index.php?page=article&storyid=' . $story->getVar('storyid');
		// 承認の通知
		if ( $approved == 1 ){
			$notification_handler->triggerEvent( 'story', $story->getVar('storyid'), 'approve', $tags );
			$notification_handler->triggerEvent('global', 0, 'new_story', $tags);
		}

		if ( $return == 1 || $story->getVar('published') > time() ){
			redirect_header($mydirurl.'/index.php?mode=admin&op=list', 2, _MD_DBPUDATED);
		}else{
			redirect_header($mydirurl.'/index.php?page=article&storyid='.$story->getVar('storyid'), 2, _MD_DBPUDATED);
		}
		exit;

	}

}

if( $op == 'preview' ){

	require_once XOOPS_ROOT_PATH.'/header.php';

	// remove extra slashes only for preview

	$story->setVar( 'title' , stripslashes( $story->getVar( 'title' , 'n' ) ) ) ;
	$story->setVar( 'text' , stripslashes( $story->getVar( 'text' , 'n' ) ) ) ;

	$p_title = $myts->makeTboxData4Show($story->getVar('title', 'n'), 0, 0);
	$p_hometext = str_replace('[pagebreak]', '<br style="page-break-after:always;" />', $myts->displayTarea($story->getVar('text', 'n'), $story->getVar('html'), $story->getVar('smiley'), $story->getVar('xcode'), 1, $story->getVar('br')));
	$xoopsTpl->assign('preview', array('title' => $p_title, 'hometext' => $p_hometext));

	$op = 'form';
}

if( $op == 'form' ){

	// for edit
	if( $storyid  && $story->getVar('text', 'n') == '' ){
		$story->unifyHomeTextAndBodyText();
	}



	// 掲載日時
	if( isset($_POST['auto']) && is_array($_POST['auto']) ){
		$auto = mktime( $_POST['auto']['hour'], $_POST['auto']['min'], @$_POST['auto']['sec'], $_POST['auto']['month'], $_POST['auto']['day'], $_POST['auto']['year'] );
	} elseif ( $story->getVar('published') > 0 ) {
		$auto = $story->getVar('published');
		$story->setVar('autodate', 1);
	} else {
		$auto = time();
	}

	// 掲載終了日時
	if( isset($_POST['auto']) && is_array($_POST['autoexp']) ){
		$autoexp = mktime( $_POST['autoexp']['hour'], $_POST['autoexp']['min'], @$_POST['autoexp']['sec'], $_POST['autoexp']['month'], $_POST['autoexp']['day'], $_POST['autoexp']['year'] );
	} elseif ( $story->getVar('expired') > 0 ) {
		$autoexp = $story->getVar('expired');
		$story->setVar('autoexpdate', 1);
	} else {
		$autoexp = time();
	}

	$xoopsOption['template_main'] = "{$mydirname}_submit.html";
//	require_once sprintf('%s/modules/legacy/language/%s/main.php' ,XOOPS_ROOT_PATH, $xoopsConfig['language']);

	require XOOPS_ROOT_PATH.'/header.php';
	if( !empty($errors) ) icms_core_Message::error($errors);
	// require dirname(dirname(__FILE__)).'/include/storyform.inc.php';
	require dirname(dirname(__FILE__)).'/include/storyform_templatevars.inc.php';
	$xoopsTpl->assign( 'xoops_breadcrumbs' , array(
		array( 'name' => $xoopsModule->getVar('name') , 'url' => XOOPS_URL.'/modules/'.$mydirname.'/' ) ,
		array( 'name' => _MD_SUBMITNEWS ) ,
	) ) ; // GIJ
	$xoopsTpl->assign( 'mod_config' , $xoopsModuleConfig ) ;
	$xoopsTpl->assign( 'topimg' , $imgmsg ) ;
	$xoopsTpl->assign($assing_array);
	$xoopsTpl->assign( 'weight' , $story->getVar('weight') ) ;



	require_once XOOPS_ROOT_PATH.'/footer.php';
}

if( $op == 'delete' ){

	if(!$isadmin){
		die(_NOPERM);
		exit();
	}
	$storyid = isset( $_GET['storyid'] ) ? intval( $_GET['storyid'] ) : 0 ;

	if ( !empty( $_POST['ok'] ) ){

		//check ticket
		if ( ! $xoopsGTicket->check() ) {
			die('Ticket Error');
			exit();
		}

		$storyid = isset( $_POST['storyid'] ) ? intval( $_POST['storyid'] ) : 0 ;

		if ( empty($storyid) ){
			die( _MD_EMPTYNODELETE );
			exit();
		}
		$story = new D3news( $mydirname , $storyid );
		if (!$story){
			die( _MD_EMPTYNODELETE );
			exit();
		}
		// 関連記事削除
		$story->relation->queryUnlinkById($storyid);
		$story->relation->queryDelete(1);
		$story -> delete();
		xoops_comment_delete( $xoopsModule->getVar('mid'), $storyid );
		xoops_notification_deletebyitem( $xoopsModule->getVar('mid'), 'story', $storyid );
		if( $return == 1){
			redirect_header( $mydirurl.'/index.php?mode=admin&op=list', 1, _MD_DBPUDATED );
		}else{
			redirect_header( $mydirurl.'/index.php', 1, _MD_DBPUDATED );
		}
		exit();
	}else{
		require_once XOOPS_ROOT_PATH.'/header.php';
		icms_core_Message::confirm( array( 'op' => 'delete', 'storyid' => $storyid, 'ok' => 1, 'return' => $return, 'XOOPS_G_TICKET'=>$xoopsGTicket->issue( __LINE__ ) ), 'index.php?page=submit', _MD_RUSUREDEL );
		require_once XOOPS_ROOT_PATH.'/footer.php';
	}
}


function RatioCalculation_l($type,$new_width,$new_height,$old_width,$old_height ) {
/* サイズを上(長い方)に合わせる */
   switch($type){
      case 1:
         $newwidth  = $new_width;
         $Ritu      = $new_width/$old_width;
         $newheight = $old_height*$Ritu;
         break;
      case 2:
         $newheight = $new_height;
         $Ritu      = $new_height/$old_height;
         $newwidth  = $old_width*$Ritu;
         break;
   }

       $newwidth = $newwidth*100;
       $newwidth = round($newwidth);
       $newwidth = $newwidth/100;

       $newheight = $newheight*100;
       $newheight = round($newheight);
       $newheight = $newheight/100;

       $img['W'] = ceil($newwidth);
       $img['H'] = ceil($newheight);

       return $img;

}

function RatioCalculation_s($type,$new_width,$new_height,$old_width,$old_height ) {
/* サイズを下(短い方)に合わせる */
   switch($type){
      case 1:
         $newheight = $new_height;
         $Ritu      = $new_height/$old_height;
         $newwidth  = $old_width*$Ritu;
         break;
      case 2:
         $newwidth  = $new_width;
         $Ritu      = $new_width/$old_width;
         $newheight = $old_height*$Ritu;
         break;
   }

       $newwidth = $newwidth*100;
       $newwidth = round($newwidth);
       $newwidth = $newwidth/100;

       $newheight = $newheight*100;
       $newheight = round($newheight);
       $newheight = $newheight/100;

       $img['W'] = ceil($newwidth);
       $img['H'] = ceil($newheight);

       return $img;

}


?>
