<?php
// +---------------------------------------------+
// |     Copyright 2007 - 2008 weenCompany       |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

if(!defined('IN_WEENCOMPANY'))
  die('File not found!');


// ############################## INSERT MESSAGE ###############################

function m4_InsertMessage($language)
{
  global $DB, $sdlanguage;

  // get message lenth setting
  $getmessagelength = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = 4 AND title = '內容字符長度'");
  $messagelength    = $getmessagelength['value'];

  if(!strlen($_POST['m4_username']))
  {
    $errors[] = $language['no_username'];
  }

  if(!strlen($_POST['m4_message']))
  {
    $errors[] = $language['no_message'];
  }

  if(strlen($_POST['m4_message']) > $messagelength)
  {
    $errors[] = $language['message_too_long'] . ' ' . $messagelength . ' ' . $language['characters'];
  }


  // Check Visual Verify Code if set
  $vvc = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = 4 AND title = '驗證碼'");

  if($vvc[0] == 1)
  {
    $vvcid    = $_POST['m4_vvcid'];
    $code     = $_POST['m4_verifycode'];

    if(!ValidVisualVerifyCode($vvcid, $code))
    {
      $errors[] = $sdlanguage['incorrect_vvc_code'];
    }
  }

  if(!isset($errors))
  {
    // check for repeat posting
    $lastentry = $DB->query_first("SELECT username, message FROM " . TABLE_PREFIX . "m4_guestbook ORDER BY messageid DESC LIMIT 1");

    if($lastentry['username'] == $_POST['m4_username'] AND $lastentry['message'] == $_POST['m4_message'])
    {
      echo $language['repeat_comment'] . '<br />';
    }
    else
    {
	  $getoncheck = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = 4 AND title = '審核發佈'");
	  $checkedon    = $getoncheck['value'];
	
      $DB->query("INSERT INTO " . TABLE_PREFIX . "m4_guestbook (noactivated, username, websitename, website, message, datecreated)
                  VALUES ('".$checkedon."', '".$_POST['m4_username']."', '".$_POST['m4_websitename']."', '".$_POST['m4_website']."', '".$_POST['m4_message']."', " . time() . ")");
    }

    m4_DisplayMessages(0, $language);
  }
  else
  {
    foreach($errors as $key => $value)
    {
      echo $value . '<br /><br />';
    }

    m4_SubmitMessage($language);
  }
}


// ############################## SUBMIT MESSAGE ###############################

function m4_SubmitMessage($language)
{
  global $DB, $categoryid, $userinfo, $inputsize, $sdlanguage;
  $vvc = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = 4 AND title = '驗證碼'");
  echo '<form method="post" action="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m4_action=insertmessage') . '">
        <table width="100%" border="0" cellspacing="0" cellpadding="0">';

  if($userinfo['loggedin'])
  {
    echo '<input type="hidden" name="m4_username" value="' . $userinfo['username'] . '" />
			<tr>
            <td valign="top">' . $language['name'] . '</td>
            <td style="padding-left: 4px; padding-bottom: 10px;">' . $userinfo['username'] . '</td>
		    </tr>';
  }
  else
  {
    echo '<tr>
            <td valign="top">' . $language['name'] . ' <font color=red>*</font></td>
            <td style="padding-left: 4px; padding-bottom: 10px;"><input type="text" size="' . $inputsize . '" name="m4_username" value="' . $_POST['m4_username'] . '" /></td>
          </tr>';
  }

  echo '<tr>
          <td valign="top" nowrap="nowrap">' . $language['website_name'] . '</td>
          <td style="padding-left: 4px; padding-bottom: 10px;"><input type="text" size="' . $inputsize . '" name="m4_websitename" value="' . $_POST['m4_websitename'] . '" /></td>
        </tr>
        <tr>
          <td valign="top">' . $language['website_url'] . '</td>
          <td style="padding-left: 4px; padding-bottom: 10px;"><input type="text" size="' . $inputsize . '" name="m4_website" value="' . $_POST['m4_website'] . '" /></td>
        </tr>
        <tr>
          <td valign="top">' . $language['message'] . ' <font color=red>*</font></td>
          <td style="padding-left: 4px; padding-bottom: 10px;"><textarea name="m4_message" rows="5" cols="' . $inputsize . '">' . $_POST['m4_message'] . '</textarea></td>
        </tr>';

  if($vvc[0])
  {
    $vvcid = CreateVisualVerifyCode();

    echo '<tr>
    <td valign="top"></td>
    <td style="padding-left: 4px; padding-bottom: 10px;"><input type="hidden" name="m4_vvcid" value="' . $vvcid . '"/>
        <img src="includes/vvc.php?vvcid=' . $vvcid . '"/></td>
    </tr>
    <tr>
    <td style="padding-left: 4px; padding-bottom: 10px;" colspan="2">' . $sdlanguage['enter_verify_code'] . ' <font color=red>*</font></td>
    </tr>
    <tr>
    <td valign="top"></td>
    <td style="padding-left: 4px; padding-bottom: 10px;"><input type="text" size="'.$inputsize.'" name="m4_verifycode"/></td>
    </tr>';
  }

  echo '<tr>
          <td></td>
          <td style="padding-left: 4px; padding-bottom: 10px;"><input type="submit" name="m4_Submit" value="' . strip_tags($language['submit_message']) . '" /> <input type="reset" value="' . strip_tags($language['reset']) . '"></td>
        </tr>
        </table>
        </form>';
}


// ############################# DISPLAY GUESTBOOK #############################

function m4_DisplayMessages($start, $language)
{
  global $DB, $categoryid, $userinfo, $inputsize, $sdlanguage;

  // load guestbook settings
  $getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = 4");
  for($i = 0; $setting = $DB->fetch_array($getsettings); $i++)
  {
    $settings[$setting['title']] = $setting['value'];
  }

  $limit = $settings['顯示條目數'];  // number of messages to display per page
  $wordwrap     = $settings['換行字符數'];

  if(in_array(4, $userinfo['modulesubmitids']))
  {
    echo '<center><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m4_action=submitmessage') . '">' . $language['sign_guestbook'] . '</a></center>
          <br /><br />';
  }
  else
  {
    echo '<center>' . $sdlanguage['no_post_access'] . '</center>
          <br /><br />';
  }

  $getmessages = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m4_guestbook ORDER BY messageid DESC LIMIT $start, " . ($limit +1) . "");
  $rows = $DB->get_num_rows($getmessages);

  for($i = 0; $i < $rows AND $i < $limit; $i++)
  {
    $message = $DB->fetch_array($getmessages);

    $username     = $message['username'];
    $websitename  = $message['websitename'];
	if($message['noactivated']){
	    $comment      = $language['message_checking'];
	}else{
	    $comment      = nl2br($message['message']);
	}

    if($wordwrap)
    {
      $comment      = cws_wordwrap($comment,     $wordwrap, "<br />", 1);
    }

    if($settings['允許表情符號'])
    {
      $comment = AddSmilies($comment);
    }


    echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td width="70" valign="top" style="padding-right: 4px; padding-bottom: 4px;">' . $language['name'] . '</td>
            <td valign="top">'.$username.'</td>
            <td width="70" valign="top" style="padding-right: 4px; padding-bottom: 4px;">'.iif($settings['顯示發表日期'], $language['date'], '&nbsp;').'</td>
             <td valign="top" align="left">'.iif($settings['顯示發表日期'], DisplayDate($message['datecreated']), '&nbsp;').'</td>
            </tr>';

	if(strlen($message['website']) > 0 OR strlen($websitename) > 0){
			  echo '<tr><td valign="top" style="padding-right: 4px; padding-bottom: 4px;" nowrap="nowrap">' . $language['website'] . '</td>
					  <td valign="top">'.$websitename.'</a></td>
					  <td valign="top" style="padding-right: 4px; padding-bottom: 4px;" nowrap="nowrap">' . $language['website_url'] . '</td>
					  <td valign="top" align="left">'.$message['website'].'</td></tr>';

	 }
			
   echo '</table>
		   <table width="100%" border="0" cellspacing="0" cellpadding="0">
		   <tr>
            <td width="70" valign="top" style="padding-right: 4px;">' . $language['message'] . '</td>
            <td valign="top" colspan="3">'.$comment.'</td>
          </tr>
          </table>';

    if( (($i + 1) < $rows) AND (($i + 1) < $limit) )
    {
      echo '<br /><hr size="1" noshade="noshade" /><br />';
    }
  } // end for loop

  // previous and next section
  if($start > 0 OR $rows > $limit)
  {
	  $getallmessages = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m4_guestbook");
	  $totalnums = $DB->get_num_rows($getallmessages);

		echo '<br /><br /><hr size="1" noshade="noshade" />
				<style type="text/css">
				<!--
				.pages_nav a {BACKGROUND: #cad9ea; PADDING-TOP: 5px; PADDING-BOTTOM: 5px; PADDING-RIGHT: 7px; PADDING-LEFT: 7px;  LINE-HEIGHT: 24px;}
				.pages_nav STRONG{FONT-WEIGHT: bold; BACKGROUND: #BBBBBB; COLOR: #CC0000;PADDING-TOP: 5px; PADDING-BOTTOM: 5px; PADDING-RIGHT: 7px; PADDING-LEFT: 7px;LINE-HEIGHT: 24px;}
				-->
				</style>
			  <table width="100%" cellpadding="0" cellspacing="0" border="0">
			  <tr>';

		if($start > 0)
		{
		  echo '<td style="padding-left: 3px; vertical-align:middle;" width="10%" nowrap="nowrap"><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m4_start=' . ($start - $limit)) . '">' . $language['previous'] . '</a></td>';
		}else{
		  echo '<td style="padding-left: 3px; vertical-align:middle;" width="10%" nowrap="nowrap">&nbsp;</td>';
		}
		
		
		$page_num = ceil($totalnums / $limit);
		$page_group = floor($start/$limit/8)*8+1;
		$now_page_num = $start/$limit+1;

		if($page_num - $now_page_num < 10){
			$start_page = $page_num - 9;
			if($start_page<1){
				$start_page = 1;
			}
			$end_page = $page_num + 1;
		}else{
			$start_page = $page_group;
			$end_page = $start_page + 8;
		}

		if($start_page > 1){
			$direct_bar = '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m4_start=0') . '">1</a><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m4_start=' . ($start_page-2)*$limit) . '">&lsaquo;&lsaquo;...</a>';
		}

		for ($p=$start_page; $p < $end_page; $p++ ) 
		{	
			if (($start/$limit+1) == $p){
				$direct_bar .= '<STRONG>'.$p.'</STRONG>';
			}else{
				$direct_bar .= '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m4_start=' . ($p-1)*$limit) . '">'.$p.'</a>';
			}


			if($p >= $page_num){
				break;
			}

		}
		
		if($page_num - $now_page_num >= 10){
			$direct_bar .= '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m4_start=' . (($page_group + 7)*$limit)) . '">...&rsaquo;&rsaquo;</a><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m4_start=' .($page_num-1)*$limit) . '">'.$page_num.'</a>';
		}

		echo '<td width="80%" style="text-align:center; vertical-align:middle;" class="pages_nav">'.$direct_bar.'</td>';


		if($rows > $limit)
		{
		  echo '<td style="padding-right: 3px; vertical-align:middle;" width="10%" nowrap="nowrap"><div align="right"><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m4_start=' . ($start + $limit)) . '">' . $language['next'] . '</a></div></td>';
		}else{
		  echo '<td style="padding-right: 3px; vertical-align:middle;" width="10%" nowrap="nowrap">&nbsp;</td>';
		}

		echo '</tr></table>';
  }
}


// ############################ VALIDATE VARIABLES #############################

$m4_action = isset($_GET['m4_action']) ? $_GET['m4_action'] : (isset($_POST['m4_action']) ? $_POST['m4_action'] : '');
$m4_start  = (isset($_GET['m4_start']) AND preg_match("/^[0-9]+$/", $_GET['m4_start'])) ? $_GET['m4_start'] : ((isset($_POST['m4_start']) AND preg_match("/^[0-9]+$/", $_POST['m4_start'])) ? $_POST['m4_start'] : 0);


// ########################### LOAD MODULE LANGUAGE ############################

$m4_language = GetLanguage(4);


// ############################## SELECT FUNCTION ##############################

if($m4_action == 'insertmessage' AND in_array(4, $userinfo['modulesubmitids']))
{
  m4_InsertMessage($m4_language);
}
else if($m4_action == 'submitmessage' AND in_array(4, $userinfo['modulesubmitids']))
{
  m4_SubmitMessage($m4_language);
}
else
{
  m4_DisplayMessages($m4_start, $m4_language);
}

unset($m4_action, $m4_start, $m4_language);

?>
