www.gusucode.com > weenCompany闻名企业网站系统 4.0.0 繁体中英文 UTF8源码程序 > includes/functions.php

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

if(!defined('IN_WEENCOMPANY'))
die('Sorry! This file not found.');

// include global functions
include($rootpath . 'includes/globalfunctions.php');



// ########################### CHECK FOR EMPTY FIELD ###########################
// check if $formvariable is empty only if $dochecking is enabled
// basically this function is used within form fields and will print out a
// different colored border (ex: red) if the variable is empty

function CheckForEmptyField($formvariable, $dochecking)
{
  if($dochecking AND !strlen($formvariable))
  {
    return ' style="border: 2px solid #FF0000;" ';
  }
}



// ########################## INSERT COMMENT  ###########################
// $objectid can be anything like categoryid, articleid, imageid, etc...

function InsertComment($moduleid, $objectid, $username, $comment, $url, $open)
{
  global $DB, $userinfo, $sdlanguage;
  $commentlen = 1024;
  
  if(isset($_POST['com_commentid']))
  {
    $commentid = $_POST['com_commentid'];
  }

  if(strlen($username) == 0)
  {
    $error[] = $sdlanguage['enter_comment_name'];
  }

  if(strlen($comment) == 0)
  {
    $error[] = '<font color=red>' . $sdlanguage['enter_comment'] . '</font>';
  }
  
   if(strlen($comment) > $commentlen)
  {
    $error[] = '<font color=red><b>comment length must be less than ' . $commentlen . '.</b></font>';
  }

  if(!isset($error))
  {
    if(isset($commentid) AND ereg("^[0-9]+$", $commentid) AND $userinfo['commentaccess'])
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "comments SET username  = '$username',
                comment   = '$comment'
      WHERE commentid = '$commentid' AND moduleid = '$moduleid' AND objectid = '$objectid'");
      $open = true; // force the comments to be open if we just added a new one
      DisplayComments($moduleid, $objectid, $url, $open);
    }
    else if(!isset($commentid))
    {
      // check for repeat posting
      $lastentry = $DB->query_first("SELECT username, comment FROM " . TABLE_PREFIX . "comments
             WHERE moduleid = '$moduleid' AND objectid = '$objectid'
             ORDER BY commentid DESC LIMIT 0, 1");

      if($lastentry['username'] == $username AND $lastentry['comment'] == $comment)
      {
        echo '<font color=red>'. $sdlanguage['repeat_comment'] . '</font><br /><br />';
      }
      else
      {
        $open = true; // force the comments to be open if we just added a new one
        $DB->query("INSERT INTO " . TABLE_PREFIX . "comments (moduleid, objectid, date, username, comment)
        VALUES ('$moduleid', '$objectid', '".time()."', '$username', '$comment')");
      }

      DisplayComments($moduleid, $objectid, $url, $open);
    }
    else
    {
      // bad data
      DisplayComments($moduleid, $objectid, $url, $open);
    }

  }
  else
  {
    // there are errors
    foreach($error as $key => $value)
    {
      echo $value . '<br />';
    }

    DisplayCommentForm($url, $moduleid, $objectid);
  }

}

// ########################## DISPLAY COMMENT FORM ##########################

function DisplayCommentForm($url, $moduleid, $objectid)
{
  global $DB, $weenurl, $categoryid, $userinfo, $inputsize, $sdlanguage;
  
  if(isset($_GET['com_commentid']) AND $_GET['com_action'] == 'editcomment_' . $moduleid . '_' . $objectid AND $userinfo['commentaccess'] == 1)
  {
    // edit a comment:
    $comment = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "comments WHERE commentid = '" . $_GET['com_commentid'] . "' ");

	echo '	
	<form action="' . RewriteLink($url) . '" method="post">
    <input type="hidden" name="com_action" value="insertcomment_' . $moduleid . '_' . $objectid .'" />
    <input type="hidden" name="com_commentid" value="' . $_GET['com_commentid'] . '" />
    <table cellpadding="0" cellspacing="0" border="0">
    <tr><td style="padding-bottom: 8px;">' . $sdlanguage['users_name'] . '</td></tr>
    <tr><td style="padding-bottom: 8px;"><input type="text" size="18" name="com_username" value="' . $comment['username'] . '" maxlength="18"/></td></tr>
    <tr><td style="padding-bottom: 8px;">' . $sdlanguage['comment'] . '</td></tr>
    <tr><td style="padding-bottom: 8px;"><textarea name="com_comment" rows="5" cols="' . $inputsize . '">' . $comment['comment'] . '</textarea></td></tr>
    <tr><td style="padding-bottom: 8px;"><input type="submit" value="' . strip_tags($sdlanguage['update_comment']) . '" /></td></tr>
    </table>
    </form>';
  }
  else
  {
    // post new comment
    echo '<form action="' . RewriteLink($url) . '" method="post" name="form_' . $moduleid . '_' . $objectid .'">
    <input type="hidden" name="com_action" value="insertcomment_' . $moduleid . '_' . $objectid .'" />';

    if($userinfo['loggedin'])
    {
      echo '<input type="hidden" name="com_username" value="' . $userinfo['username'] . '" />';
    }

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

    if(!$userinfo['loggedin'])
    {
      echo '<tr><td style="padding-bottom: 8px;">' . $sdlanguage['your_name'] . '</td></tr>
      <tr><td style="padding-bottom: 8px;"><input type="text" size="18" name="com_username" value="" maxlength="18"/></td></tr>';
    }

    echo '<tr><td style="padding-bottom: 8px;">' . $sdlanguage['comment'] . '</td></tr>
    <tr><td style="padding-bottom: 8px;"><textarea name="com_comment" rows="5" cols="' . $inputsize . '"></textarea></td></tr>
    <tr><td style="padding-bottom: 8px;"><input type="submit" value="' . strip_tags($sdlanguage['post_comment']) . '" /></td></tr>
    </table>
    </form>';
  }

}

// ######################## GET COMMENT COUNTS ##########################

function GetCommentsCount($moduleid, $objectid)
{
  global $DB;

  $count = $DB->query_first("SELECT COUNT(*) FROM " . TABLE_PREFIX . "comments WHERE moduleid = '$moduleid' AND objectid = '$objectid'");

  return $count[0];
}


// ########################## DISPLAY COMMENTS ##########################

function DisplayComments($moduleid, $objectid, $url, $open = false)
{
  global $DB, $weenurl, $userinfo, $usersystem, $sdlanguage, $mainsettings;

  $getcomments = $DB->query("SELECT * FROM " . TABLE_PREFIX . "comments WHERE moduleid = '$moduleid' AND objectid = '$objectid' ORDER BY commentid DESC");
  $commentrows = $DB->get_num_rows($getcomments);

  $strCount = ' (' . $commentrows . ')';

  echo '<a href="javascript:void(0)" onclick="ToggleCommentDiv(this, \'comments_' . $moduleid . '_' . $objectid . '\',\'' . $sdlanguage['view_comments'] . $strCount . '\', \'' . $sdlanguage['hide_comments'] . $strCount . '\');">';
  echo iif($open, $sdlanguage['hide_comments'], $sdlanguage['view_comments']) . $strCount;
  echo '</a>';
  echo '<div id="comments_' . $moduleid . '_' . $objectid . '" ' . iif($open, '', 'style="display: none;"') . '><br/>';

  while($comment = $DB->fetch_array($getcomments))
  {
    $comment['comment'] = AddSmilies($comment['comment']);

    echo '<b>' . $comment['username'] . '</b> - ' . DisplayDate($comment['date']);

    if($userinfo['commentaccess'])
    {
      echo ' (<a href="' . RewriteLink($url . '&com_action=editcomment_' . $moduleid . '_' . $objectid . '&com_commentid=' . $comment['commentid']) . '">' . $sdlanguage['edit'] . '</a> -
        <a href="' . RewriteLink($url . '&com_action=deletecomment_' . $moduleid . '_' . $objectid . '&com_commentid=' . $comment['commentid']) . '">' . $sdlanguage['delete'] . '</a>)';
    }

    echo '<br />' . nl2br($comment['comment']) . '<br /><br /><br />';
  }

  if(@in_array($moduleid, $userinfo['modulecommentids']))
  {
    DisplayCommentForm($url, $moduleid, $objectid);
  }
  else
  {
    echo $sdlanguage['no_comment_access'];
  }

  echo '</div>';

}


// ########################## DELETE COMMENT ##########################

function DeleteComment($moduleid, $objectid, $url, $commentid, $open)
{
  global $DB, $usersystem, $userinfo;

  // check to see if an admin is loggedin
  if($userinfo['commentaccess'])
  {
    $DB->query("DELETE FROM " . TABLE_PREFIX . "comments WHERE commentid = '$commentid' AND moduleid = '$moduleid' AND objectid = '$objectid'");
  }
  $open = true; // force the comments to be open if we just added a new one
  DisplayComments($moduleid, $objectid, $url, $open);
}


// ########################## ADD COMMENT ##########################

function Comments($moduleid, $objectid, $url, $open = false)
{
  $com_action = isset($_POST['com_action']) ? $_POST['com_action'] : $_GET['com_action'];

  switch($com_action)
  {
    case 'insertcomment_' . $moduleid . '_' . $objectid:
    InsertComment($moduleid, $objectid, $_POST['com_username'], $_POST['com_comment'], $url, $open);
    break;

    case 'editcomment_' . $moduleid . '_' . $objectid:
    DisplayCommentForm($url, $moduleid, $objectid);
    break;

    case 'deletecomment_' . $moduleid . '_' . $objectid:
    DeleteComment($moduleid, $objectid, $url, $_GET['com_commentid'], $open);
    break;

    default:
    DisplayComments($moduleid, $objectid, $url, $open);
  }
}



// ########################## PRE CLEAN ##########################
// preclean: cleans all post, get, and cookie data - before entering database

function PreClean($data)
{
  if(is_array($data))
  {
    foreach($data as $key => $val)
    {
      $return[$key] = PreClean($val);
    }

    return ($return);
  }
  else
  {
    // htmlspecialchars might give trouble to other languges (ex: russian)
    // if so then try adding the charset argument, read this page for more information:
    // http://us4.php.net/manual/en/function.htmlspecialchars.php
    return trim(htmlspecialchars($data, ENT_QUOTES));
  }
}



// ########################### WEENCOMPANY WORD WRAP ############################
// this function will wordwrap an htmlentities string correctly

function cws_wordwrap($string, $width = 75, $break = '<br />', $cut = 1)
{
  global $userinfo;

  $string = unhtmlspecialchars($string);        // first decode the html
  $string = wordwrap($string, $width, $break, $cut);        // now wrap the string
  $string = htmlspecialchars($string, ENT_QUOTES);    // switch back to htmlspecialchars
  return str_replace(htmlspecialchars($break, ENT_QUOTES), $break, $string);  // fix the line break and return string
}



// ############################### PRINT MESSAGE ###############################

function PrintMessage($message, $displayloginpanel = 0)
{
  global $DB, $categoryid, $userinfo;

  echo '<html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <style media="screen" type="text/css">

  .msgbox
  {
    background-color: #FFFFFF;

    border-width: 1px;
    border-color: #E2AD8D;
    border-style: solid;
  }

  td { font: 12px verdana, arial, sans-serif; color: #666666; }

  </style>

  </head>

  <body bgcolor="#909FA4" topmargin="60">

  <table width="400" height="100" border="0" cellpadding="0" cellspacing="1" align="center" class="msgbox">
  <tr><td style="padding: 8px;">' . $message;

  // display login panel?
  if($displayloginpanel)
  {
    echo '<br /><br />';
    include('./modules/m10_loginpanel/loginpanel.php');
  }

  echo '  </td></tr>
  </table>

  </body>
  </html>';
}






// ############################### REWRITE LINK  ###############################

function RewriteLink($url)
{
  global $DB, $weenurl, $mainsettings, $userinfo;

  // url examples:
  // index.php?categoryid=1&m2_start=0&m2_articleid=1&com_action=displaycomments
  // index.php?categoryid='.$categoryid.'&logout=1

  if(strlen($userinfo['sessionurl']))
  {
    $url .= !strstr($url, '?') ? '?' . $userinfo['sessionurl'] : '&' . $userinfo['sessionurl'];
  }

  // there is a bug in many new templates where mainsettings is not loaded in the forummenu.php
  // this but prevents modrewrite in the forum, even if it's enabled
  // mainsettings should always be a set variable
  // in the future the templates should be updated and this should be removed
  if(!isset($mainsettings['modrewrite']))
  {
    $getmodrewrite = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'modrewrite'");
    $mainsettings['modrewrite'] = $getmodrewrite['value'];
  }

  if($mainsettings['modrewrite'])
  {
    // full transformation example:
    // index.php?categoryid=1&m2_start=0&m2_articleid=1&com_action=displaycomments
    // into this:
    // home/m2_start/0/m2_articleid/1/com_action/displaycomments

    // first make sure there is a category
    if(eregi("^index.php\?categoryid=([0-9]+)", $url, $eregidata))
    {
      $categoryid = $eregidata[1];  // [0] = the $url, [1] = the first () match, http://us2.php.net/manual/en/function.ereg.php

      if(ereg("^[0-9]+$", $categoryid))
      {
        if($category = $DB->query_first("SELECT name, urlname FROM " . TABLE_PREFIX . "categories WHERE categoryid = $categoryid"))
        {
          // change index.php?categoryid=1 into home, etc...
          $friendlyurl = eregi_replace("^index.php\?categoryid=[0-9]+", $category['urlname'], $url);

          // this should take care of the rest
          $friendlyurl = str_replace('&', '/', $friendlyurl);
          $friendlyurl = str_replace('=', '/', $friendlyurl);
          $friendlyurl = str_replace('=', '/', $friendlyurl);
        }
      }
    }
  }
  else
  {
    // Replace '&' with '&amp;'
    $url = str_replace('&', '&amp;', $url);
  }

  if(isset($friendlyurl))
  {
    // url.com/home should be returned as url.com/ (otherwise google will treat home as two pages)
    if($categoryid == 1 AND $friendlyurl == $category['urlname'])
    {
      return $weenurl;
    }
    else
    {
      return $weenurl . $friendlyurl;
    }
  }
  else
  {
    return $weenurl . $url;
  }
}




// ############################# CREATE HOVER MENU #############################

function CreateHoverMenu($categoryid = 0, $vn = 1)
{
  global $DB, $userinfo, $weenurl;

  $getcategories = $DB->query("SELECT categoryid, parentid, name, urlname, link, target, image, hoverimage, menuwidth
             FROM " . TABLE_PREFIX . "categories WHERE parentid = $categoryid
             ORDER BY displayorder");

  while($category = $DB->fetch_array($getcategories))
  {
    if(in_array($category['categoryid'], $userinfo['categorymenuids']))
    {
      if(!$vn)
      {
        echo ',';
      }

      list($categoryid, $parentid, $name, $urlname, $clink, $target, $image, $hoverimage, $menuwidth, $vn) = $category;

      $icon      = strlen($image) ? ", '" .$weenurl . "images/" . $image . "'"      : ", '" . $weenurl . "includes/javascript/hovermenu/pixel.gif width=16'";
      $hovericon = strlen($image) ? ", '" .$weenurl . "images/" . $hoverimage . "'" : ", '" . $weenurl . "includes/javascript/hovermenu/pixel.gif width=16'";

      if(strlen($clink))
      {
        if( substr($clink, 0, 4) == 'http')
        {
          $categorylink = $clink;
        }
        else if(substr($clink, 0, 3) == 'www' )
        {
          // URL needs to be fully qualified
          $categorylink = 'http://' . $clink;
        }
        else
        {
          $categorylink = $weenurl . $clink;
        }
      }
      else
      {
        $categorylink = RewriteLink('index.php?categoryid=' . $categoryid);
      }

      if(strlen($target))
      {
        $optionsTag = "'tw': '" . $target . "'";
      }
      else
      {
        $optionsTag = '';
      }

      if($parentid == 0)
      {
        if($menuwidth != 0)
        {
          $optionsTag = iif(strlen($optionsTag), $optionsTag . ",", "") . "'sw': " . $menuwidth;
        }

        echo "[wrap_root('" . addslashes($name) . "'), '" . $categorylink . "', {" . $optionsTag . "}";
      }
      else if($isparent = $DB->query_first("SELECT categoryid FROM " . TABLE_PREFIX . "categories WHERE parentid = $categoryid"))
      {
        echo "[wrap_parent('" . addslashes($name) . "'" . $icon . $hovericon . "), '" . $categorylink . "', {" . $optionsTag . "}";
      }
      else
      {
        echo "[wrap_child('" . addslashes($name) . "'" . $icon . $hovericon . "), '" . $categorylink . "', {" . $optionsTag . "}";
      }

      CreateHoverMenu($categoryid, $vn);

      echo ']';
    }
  }

  $DB->free_result($getcategories);
}

// ########################### CREATE VISUAL VERIFY CODE #############################

function CreateVisualVerifyCode()
{
  global $DB;

  /*random string generator.*/
  /*The seed for the random number*/
  srand((double)microtime()*1000000);

  /*Runs the string through the md5 function*/
  $verifycode = str_replace('0', '8', str_replace('O', 'A', strtoupper(md5(rand(0,9999)))));

  /*creates the new string. */
  $verifycode = substr($verifycode, 17, 5);

  $DB->query("INSERT INTO " . TABLE_PREFIX . "vvc (verifycode) VALUES ('$verifycode')");

  return $DB->insert_id();
}

function ValidVisualVerifyCode($vvcid, $enteredcode)
{
  global $DB;

  if(is_numeric($vvcid))
  {
    $verifycode = $DB->query_first("SELECT verifycode FROM " . TABLE_PREFIX . "vvc WHERE vvcid = $vvcid");

    if($verifycode[0] == $enteredcode)
    {
      return true;
    }
  }

  return false;
}

// ########################### Short TITLES ##############################
function ShortTitle($string, $length=50)
{

	if(strlen($string) == 0){
		$string = '(無標題)';
		return $string;
	}

	if(strlen($string) <= $length) {
		return $string;
	}

	$charset = 'utf-8';
	$dot = ' ...';
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

	$strcut = '';
	if($charset == 'utf-8') {

		$n = $tn = $noc = 0;
		while($n < strlen($string)) {

			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}

			if($noc >= $length) {
				break;
			}

		}
		if($noc > $length) {
			$n -= $tn;
		}

		$strcut = substr($string, 0, $n);

	} else {
		for($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}

	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

	return $strcut.$dot;

}


?>