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

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



// ################################# GET MENU ##################################

function m16_GetMenu($sectionid, $currsectionid)
{
  global $DB;
  global $categoryid;

  $getsection = $DB->query("SELECT sectionid, parentid, name FROM " . TABLE_PREFIX . "m16_sections WHERE sectionid = '$sectionid'");
  $section    = $DB->fetch_array($getsection);

  while($sectionid != 1)
  {
    $sectionid = m16_GetMenu($section['parentid'], $currsectionid);
  }

  if($section['sectionid'] == $currsectionid)
  {
    echo $section['name'];
  }
  else
  {
    echo '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m16_sectionid=' . $section['sectionid']) . '">'.$section['name'].'</a> &raquo; ';
  }

  return $sectionid;
}



// ################################ INSERT LINK ################################

function m16_InsertLink($sectionid)
{
  global $DB, $mainsettings, $sdlanguage, $rootpath;

  // get language
  $language = GetLanguage(16);
  
  $vvc = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = 16 AND title = '验证码'");

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

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

  // did user enter an author name?
  if(!strlen($_POST['m16_author']))
  {
    $errors[] = $language['enter_name'];
  }

  // did user enter a title for the link?
  if(!strlen($_POST['m16_title']))
  {
    $errors[] = $language['enter_site_name'];
  }

  // did user enter a link?
  if(!strlen($_POST['m16_url']))
  {
    $errors[] = $language['enter_site_url'];
  }
  else
  {
    // remove ending slash
    if(substr($_POST['m16_url'], -1) == '/')
    {
      $Tempa = $_POST['m16_url'];
	  $_POST['m16_url'] = substr($_POST['m16_url'], 0, -1);
    }

    // is the link in a correct format?
    if(!preg_match("/^(http|https|ftp)\://((([a-zA-Z0-9\-]+\.){1,}[a-zA-Z]{2,4})|(localhost))(:[0-9]+){0,1}(/[a-zA-Z0-9\-\_\,\./\+&?amp;%\$#\=~]+)*$/", $_POST['m16_url']))
    {
      $errors[] = $language['url_invalid'];
	  $_POST['m16_url'] = $Tempa;
    }
  }

  // did user enter a description?
  if(!strlen($_POST['m16_description']))
  {
    $errors[] = $language['enter_description'];
  }
  
  if(strlen($_POST['m16_description'])>1024)
  {
    $errors[] = '链接描述内容不能超过1024个字符!';
  }


  if($samelink = $DB->query_first("SELECT linkid FROM " . TABLE_PREFIX . "m16_links WHERE author = '".$_POST['m16_author']."'
					   AND title = '".$_POST['m16_title']."' AND description = '".$_POST['m16_description']."' AND url = '".$_POST['m16_url']."'") )

	{
			$errors[] = '<font color=red><b>Sorry! this is a same link.</b></font>' . '<br />';
	}

  if(isset($errors))
  {
    foreach($errors as $key => $value)
    {
      echo '<font color=red>'. $value . '<br /><br /></font>';
    }

    m16_SubmitLink($_POST['m16_sectionid']);
    return;
  }
  else
  {
  	// get module settings
	$getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '16' AND groupname = '模块设置'");
	while($setting = $DB->fetch_array($getsettings))
	{
		$settings[$setting['title']] = $setting['value'];
	}
  	
    // if sectionid is not an integer then it will be set to 1 in the bottom of this script, so the POST variable is secure
    // all other post variables have been cleaned and are secure
    $DB->query("INSERT INTO " . TABLE_PREFIX . "m16_links VALUES ('0', $sectionid, '" . $settings['自动发布'] . "', '1', '1', '" . $_POST['m16_author'] . "', '" . $_POST['m16_title'] . "', '" . $_POST['m16_url'] . "', '" . $_POST['m16_description'] . "') ");

    $email = $settings['邮件通知'];

    if(strlen($email) > 0)
    {
      // obtain emails
      $getemails = str_replace(',', ' ', $email);                    // get rid of commas
      $getemails = preg_replace("/[[:space:]]+/", " ", $getemails);   // get rid of extra spaces
      $getemails = trim($getemails);                                 // then trim
      $emails    = explode(" ", $getemails);

      $message  = $language['notify_email_message'] . EMAIL_CRLF;
      $message .= $language['notify_email_author'] . ' - ' . $_POST['m16_author'] . EMAIL_CRLF;
      $message .= $language['notify_email_website'] . ' - ' . $_POST['m16_title'] . EMAIL_CRLF;
      $message .= $language['notify_email_url'] . ' - ' . $_POST['m16_url'] . EMAIL_CRLF;
      $message .= $language['notify_email_description'] . ' - ' . $_POST['m16_description'] . EMAIL_CRLF;

		require_once($rootpath . 'includes/mail/class.phpmailer.php');

		$mail = new PHPMailer();

		if($mainsettings['email_use_smtp'] == '1')
			$mail->IsSMTP();
		else
			$mail->IsMail();


		$mail->Host = $mainsettings['email_smtp_host'];
		$mail->Port = $mainsettings['email_smtp_port'];

		if( $mainsettings['email_smtp_require_auth'] == "1" ) {
			$mail->SMTPAuth = true;
			$mail->Username = $mainsettings['email_smtp_user'];
			$mail->Password = $mainsettings['email_smtp_pass'];
		}

		$mail->From      =  $mainsettings['technicalemail'];
		$mail->FromName      =  $mainsettings['copyrighttext'];
		$mail->AddReplyTo($mainsettings['technicalemail'], $mainsettings['copyrighttext']);   
		$mail->Sender      =  $mainsettings['email_smtp_from'];

		for($i = 0; $i < count($emails); $i++)
		{
			$mail->AddAddress($emails[$i]);
		}
		
		$mail->Subject   = $language['notify_email_subject'];
		$mail->Body      = nl2br($message);

		$mail->Send();

    }

    echo $language['link_submitted'] . '<br /><br />';
    m16_DisplayLinks($sectionid, 0);
  }
}



// ################################ SUBMIT LINK ################################

function m16_SubmitLink($sectionid)
{
  global $DB, $categoryid, $userinfo, $inputsize, $sdlanguage;
  $vvc = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = 16 AND title = '验证码'");
  // get language
  $language = GetLanguage(16);

  echo $language['sections'] . ' ';
  m16_GetMenu($sectionid, $sectionid);
  echo ' - ' . $language['submitting_link'] . '<br /><br />';

  echo '<form method="post" action="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m16_action=insertlink') . '">
        <input type="hidden" name="m16_sectionid" value="' . $sectionid . '" />

        <table width="100%" border="0" cellspacing="0" cellpadding="0">';

  if($userinfo['loggedin'])
  {
    echo '<input type="hidden" name="m16_author" value="' . $userinfo['username'] . '" />';
  }
  else
  {
    echo '<tr>
            <td valign="top" width="100">' . $language['your_name'] . '</td>
            <td style="padding-left: 8px; padding-bottom: 8px;"><input size="'.$inputsize.'" type="text" name="m16_author" value="'.$_POST['m16_author'].'" maxlength="26" /></td>
          </tr>';
  }

  echo '<tr>
          <td valign="top" width="100">' . $language['website_name'] . '</td>
          <td style="padding-left: 8px; padding-bottom: 8px;"><input size="'.$inputsize.'" type="text" name="m16_title" value="'.$_POST['m16_title'].'" maxlength="56" /></td>
        </tr>
        <tr>
          <td valign="top" width="100">' . $language['website_url'] . '</td>
          <td style="padding-left: 8px; padding-bottom: 8px;"><input size="'.$inputsize.'" type="text" name="m16_url" value="' . iif(!empty($_POST['m16_url']), $_POST['m16_url'], 'http://') . '" maxlength="128" /></td>
        </tr>
        <tr>
          <td valign="top" width="100">' . $language['description'] . '</td>
          <td style="padding-left: 8px; padding-bottom: 8px;"><textarea name="m16_description" rows="5" cols="'.$inputsize.'">'.$_POST['m16_description'].'</textarea></td>
        </tr>';

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

    echo '<tr>
    <td valign="top" width="100"></td>
    <td style="padding-left: 8px; padding-bottom: 8px;"><input type="hidden" name="m16_vvcid" value="' . $vvcid . '"/>
        <img src="includes/vvc.php?vvcid=' . $vvcid . '"/></td>
    </tr>
    <tr>
    <td style="padding-left: 8px; padding-bottom: 8px;" colspan="2">' . $sdlanguage['enter_verify_code'] . '</td>
    </tr>
    <tr>
    <td valign="top" width="100"></td>
    <td style="padding-left: 8px; padding-bottom: 8px;"><input type="text" size="'.$inputsize.'" name="m16_verifycode"/></td>
    </tr>';
  }

  echo '<tr>
          <td></td>
          <td style="padding-left: 8px; padding-bottom: 8px;"><input type="submit" name="m16_Submit" value="' . strip_tags($language['submit_link']) . '" /></td>
        </tr>
        </table>

        </form>';

}



// ########################## GET SECTION LINK COUNT ###########################

function m16_GetSectionLinkCount($sectionid, $linkcount)
{
  global $DB;

  // get total links of the section
  $getlinkcount = $DB->query_first("SELECT COUNT(*) AS linkcount FROM " . TABLE_PREFIX . "m16_links
                                    WHERE sectionid = '$sectionid' AND activated = '1'");

  $linkcount += $getlinkcount['linkcount'];

  // are there any subsections?
  $getsubsections = $DB->query("SELECT sectionid FROM " . TABLE_PREFIX . "m16_sections WHERE parentid = '$sectionid'");

  while($subsection = $DB->fetch_array($getsubsections))
  {
    $linkcount = m16_GetSectionLinkCount($subsection['sectionid'], $linkcount);
  }

  return $linkcount;

}



// ############################### DISPLAY LINKS ###############################

function m16_DisplayLinks($sectionid, $start)
{
  global $DB, $categoryid, $userinfo;

  // get language
  $language = GetLanguage(16);

  // is link section online?
  if($offline = $DB->query_first("SELECT sectionid FROM " . TABLE_PREFIX . "m16_sections WHERE sectionid = '$sectionid' AND activated = '0'"))
  {
    $sectionid = 1;
  }

  // get module settings
  $getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '16' ORDER BY displayorder");
  for($i = 0; $setting = $DB->fetch_array($getsettings); $i++)
  {
    $settings[$setting['title']] = $setting['value'];
  }

  $limit = $settings['每页链接数'];

  // show menu ?
  if($settings['显示导航栏'])
  {
    echo $language['sections'] . ' ';
    m16_GetMenu($sectionid, $sectionid);
    echo '<br />';
  }

  // display 'submit link'?
  if(@in_array(16, $userinfo['modulesubmitids']))
  {
    echo '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m16_sectionid=' . $sectionid . '&m16_action=submitlink') . '">' . $language['submit_a_link'] . '</a><br />';
  }

  // display an extra line break
  if($settings['显示导航栏'] OR @in_array(16, $userinfo['modulesubmitids']))
  {
    echo '<br />';
  }

  // get subsections of sectionid
  $getsubsections = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m16_sections WHERE parentid = '$sectionid' AND activated = '1'");

  // display subsections
  while($subsection = $DB->fetch_array($getsubsections))
  {
    $numsectionlinks = m16_GetSectionLinkCount($subsection['sectionid'], 0);

    echo '- <b><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m16_sectionid=' . $subsection['sectionid']) . '">' . $subsection['name'] . '</a></b> (' . $numsectionlinks . ')
          <br />' . nl2br($subsection['description']);

    if(strlen($subsection['description']) > 0)
    {
      echo '<br />';
    }

    echo '<br />';
  }

  echo '<hr size="1" noshade="noshade" /><br />';

  // get sort type of current section
  $getsorttype = $DB->query_first("SELECT sorting FROM " . TABLE_PREFIX . "m16_sections WHERE sectionid = '$sectionid'");
  $sorttype    = $getsorttype['sorting'];

  switch($sorttype)
  {
    case '标题(A-Z)':
      $order = 'title ASC';
    break;

    case '标题(Z-A)':
      $order = 'title DESC';
    break;

    case '作者(A-Z)':
      $order = 'author ASC';
    break;

    case '作者(Z-A)':
      $order = 'author DESC';
    break;

    case '时间(升序)':
      $order = 'linkid ASC';
    break;

    default:
      $order = 'linkid DESC';  // Newest First
  }

  // get links
  $getlinks = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m16_links WHERE sectionid = '$sectionid' AND activated = '1'
                          ORDER BY " . $order . " LIMIT $start, " . ($limit + 1) . "");

  $rows = $DB->get_num_rows($getlinks);

  echo '<table cellpadding="0" cellspacing="0" border="0">';

  $curcol = 0; // current column

  // display links
  for($i = 0; $i < $rows AND $i < $limit; $i++)
  {
    $link = $DB->fetch_array($getlinks);

    if($curcol == 0)
    {
      echo '<tr>';
    }

    

    // add smilies
    if($link['allowsmilies'])
    {
      $link['description'] = AddSmilies($link['description']);
    }

    echo '<td valign="top" style="padding-bottom: 20px; padding-right: 20px;">
          <a href="'.$link['url'].'" target="_blank">'.$link['title'].'</a>';

    if($link['showauthor'])
    {
      echo '<br />' . $language['submitted_by'] . ' ' . $link['author'];
    }

    echo '<br />' . $link['description'] . '</td>';

    $curcol++;

    if($curcol == $settings['每行链接数'])
    {
      echo '</tr>';
      $curcol = 0;
    }

  }

  if($curcol != $settings['每行链接数'])
  {
    echo '<td colspan="' . ($settings['每行链接数'] - $curcol) . '">&nbsp;</td></tr>';
  }

  echo '</table>';

  // multiple pages
  if(($start > 0) || ($rows > $limit))
  {
	  // get all section links number
	  $getsectionlinks = $DB->query("SELECT linkid FROM " . TABLE_PREFIX . "m16_links WHERE sectionid = '$sectionid' AND activated = '1' ");

	  $sectionlinksnum = $DB->get_num_rows($getsectionlinks);

	echo '<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 . '&m16_sectionid=' . $sectionid . '&m16_start=' . ($start - $limit)) . '">' . $language['previous_links'] . '</a></td>';
	}else{
	  echo '<td style="padding-left: 3px; vertical-align:middle;" width="10%" nowrap="nowrap">&nbsp;</td>';
	}

	$page_num = ceil($sectionlinksnum / $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 . '&m16_sectionid=' . $sectionid . '&m16_start=0') . '">1</a><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m16_sectionid=' . $sectionid . '&m16_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 . '&m16_sectionid=' . $sectionid . '&m16_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 . '&m16_sectionid=' . $sectionid . '&m16_start=' . (($page_group + 7)*$limit)) . '">...&rsaquo;&rsaquo;</a><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m16_sectionid=' . $sectionid . '&m16_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)
	{
	  $start += $limit;
	  echo '<td style="padding-right: 3px; vertical-align:middle;" width="10%" nowrap="nowrap"><div align="right"><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m16_sectionid=' . $sectionid . '&m16_start=' . $start) . '">' . $language['more_links'] . '</a></div></td>';
	}else{
	  echo '<td style="padding-right: 3px; vertical-align:middle;" width="10%" nowrap="nowrap">&nbsp;</td>';
	}

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

}



// ######################### START CALLING FUNCTIONS  ##########################

$m16_action    = isset($_GET['m16_action']) ? $_GET['m16_action'] : ( isset($_POST['m16_action']) ? $_POST['m16_action'] : NULL);
$m16_sectionid = (isset($_GET['m16_sectionid']) AND preg_match("/^[0-9]+$/", $_GET['m16_sectionid'])) ? $_GET['m16_sectionid'] : ( (isset($_POST['m16_sectionid']) AND preg_match("/^[0-9]+$/", $_POST['m16_sectionid'])) ? $_POST['m16_sectionid'] : 1);
$m16_start     = (isset($_GET['m16_start']) AND preg_match("/^[0-9]+$/", $_GET['m16_start'])) ? $_GET['m16_start'] : ( (isset($_POST['m16_start']) AND preg_match("/^[0-9]+$/", $_POST['m16_start'])) ? $_POST['m16_start'] : 0);

if($m16_action == 'submitlink' AND @in_array(16, $userinfo['modulesubmitids']))
{
  m16_SubmitLink($m16_sectionid);
}
else if($m16_action == 'insertlink' AND @in_array(16, $userinfo['modulesubmitids']))
{
  m16_InsertLink($m16_sectionid);
}
else
{
  m16_DisplayLinks($m16_sectionid, $m16_start);
}

unset($m16_action, $m16_sectionid, $m16_start);
?>