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

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

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


$enablewysiwyg = '';

// ############################### PRINT HEADER ################################

function PrintHeader($pagetitle, $includetinymce = 0)
{
  global $DB, $stylepath, $weenurl, $enablewysiwyg, $sitedefaultlang;

  SetPageCharacterSet();

  echo '<html>
        <head>
          <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
          <link rel=stylesheet href="'.$stylepath.'style.css" />
          <script type="text/javascript" src="javascript/admin_functions.js"></script>
          <SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
          <!--
          if(top.location == self.location)
          {
            top.location.replace("index.php");
          }
          -->
          </SCRIPT>';

  if($includetinymce AND $enablewysiwyg = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'enablewysiwyg' AND value = 1"))
  {
    // is gzip enabled?
    if($gzip = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'gzipcompress' AND value = 1"))
    {
      echo '<script language="javascript" type="text/javascript" src="./tiny_mce/tiny_mce_gzip.js"></script>';
	  
	  echo '<script type="text/javascript">
			tinyMCE_GZ.init({
				disk_cache : true,
				debug : false
			});
			</script>
			';
    }
    else
    {
      echo '<script language="javascript" type="text/javascript" src="./tiny_mce/tiny_mce.js"></script>';
    }


    echo '<script type="text/javascript">
	tinyMCE.init({
		// General options
		theme : "advanced",
        document_base_url : "' . $weenurl . '",
		language: "zh",
		mode : "specific_textareas",
		forced_root_block : "",
		editor_selector : "mceEditor",';
		
		if($simpleTinyMce = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'simpletingymce' AND value = 1"))
		{
			echo 'plugins : "imagemanager,save,preview,table,fullscreen,advimage,inlinepopups",
	
			// Theme options
			theme_advanced_buttons1 : "code,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,styleselect,formatselect,fontselect,fontsizeselect,forecolor,backcolor,|,removeformat,cleanup,visualaid",
			theme_advanced_buttons2 : "newdocument,save,|,cut,copy,paste,|,undo,redo,|,outdent,indent,|,hr,sub,sup,charmap,|,link,unlink,image,imagemanager,|,tablecontrols,|,fullscreen,preview",
			
			theme_advanced_buttons3 : "",';
			
		}
		else
		{
		  echo 'plugins : "safari,imagemanager,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

		// Theme options
		theme_advanced_buttons1 : "code,|,save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,imagemanager,cleanup,help,|,insertdate,inserttime,preview,|,forecolor,backcolor",
		theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
		theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",';
		}
		
		
		echo '
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		theme_advanced_styles : "点线条=dotline;横色带=hrule;代码区=code;高亮区=highlight;警告区=notice;正确区=success;错误区=error;浮右区=right;浮左区=left",
		content_css : "templates/custom_css.css?" + new Date().getTime(),
		template_replace_values : {
			username : "WeenCompany",
			staffid : "556688"
		}
	});
</script>';

  }

	if($sitedefaultlang == 'en')
	{
	   $thislang = '__<font style="color: #66FFFF; font:bold; ">English</font>';
	}
	else
	{
	   $thislang = '__<font style="color: #66FFFF; font:bold; ">简体中文</font>';
	}
	
  echo '</head>
        <body>

        <table width=100%" border="0" cellpadding="0" cellspacing="0" class="header">
        <tr>
          <td align="center"><p class="pagetitle">'.$pagetitle.$thislang.'</p></td>
        </tr>
        </table>

        <br /><br />';
}



// ############################### PRINT SUBMIT ################################

function PrintSubmit($name, $value)
{

  echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
        <tr>
          <td align="center">
            <input type="hidden" name="'.$name.'" value="'.$value.'" />
            <input type="submit" value="'.$value.'" />
          </td>
        </tr>
        </table>';
}



// ############################### PRINT SECTION ###############################

function PrintSection($sectionname)
{
  global $stylepath;

  echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
        <tr>
          <td width="15" height="30"><img src="'.$stylepath.'images/section/section_top_left.gif" /></td>
          <td width="100%" background="'.$stylepath.'images/section/section_top_bg.gif" valign="bottom" align="center">
            <div style="font-family:verdana;font-size:10pt;color:#5D729B"><b>'.$sectionname.'</b></div>
          </td>
          <td width="1" height="30"><img src="'.$stylepath.'images/section/section_top_right.gif" /></td>
        </tr>
        <tr>
          <td width="15" height="4"><img src="'.$stylepath.'images/section/section_top_left2.gif" /></td>
          <td background="'.$stylepath.'images/section/section_top_bg2.gif"></td>
          <td width="15" height="4"><img src="'.$stylepath.'images/section/section_top_right2.gif" /></td>
        </tr>
        <tr>
          <td colspan="3">

          <table width="100%" border="0" cellpadding="0" cellspacing="0">
          <tr>
            <td width="7" background="'.$stylepath.'images/section/section_middle_left.gif"></td>
            <td>';
}



// ################################ END SECTION ################################

function EndSection()
{
  global $stylepath;

  echo '    </td>
            <td width="7" background="'.$stylepath.'images/section/section_middle_right.gif"></td>
          </tr>
          </table>

          </td>
        </tr>
        </table>

        <br /><br />';
}



// ############################### PAGE REDIRECT ###############################

function PrintRedirect($gotopage, $timeout = 0)
{

  $gotopage = str_replace('&amp;', '&', $gotopage);

  PrintSection('完成更新!');
  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow1"  colspan="2">跳转中...</td>
        </tr>
        <tr>
          <td class="tdrow2" width="70%">';

  echo '<a href="'.$gotopage.'" onclick="javascript:clearTimeout(timerID);">
        完成更新! 如果网页没有跳转，请点击这里.</a>';

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

  echo '<script type="text/javascript">';
  if($timeout == 0)
  {
    echo 'window.location="'.$gotopage.'"';
  }
  else
  {
    echo 'timeout = '.($timeout*10).';

          function Refresh()
          {
            timerID = setTimeout("Refresh();", 100);

            if (timeout > 0)
            {
              timeout -= 1;
            }
            else
            {
              clearTimeout(timerID);
              window.location="'.$gotopage.'";
            }
          }

          Refresh();';
  }

  echo '</script>';

  EndSection();
  PrintFooter();

  exit();
}

// ############################### PRINT FOOTER ################################

function PrintFooter()
{
  global $DB;
  global $stylepath;
  
  $getversion = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE  title = 'version'");
  $version    = $getversion['value']; 

  echo '<br /><br />

        <table width="48%" border="0" cellpadding="0" cellspacing="0" align="center">
        <tr><td align="center"><p class="copyright">&copy; 2006-'.date("Y").' 闻泰网络. weenCompany' . $version . ' CWS</p><br><a href="http://www.weentech.com" target="_blank"><img src="'.$stylepath.'images/wenlo.gif" alt="闻泰网络" /></a><br></td></tr>
        </table>

        </body>
        </html>';
}



// ########################### PRINT MODULE SETTINGS ###########################

function PrintModuleSettings($moduleid, $groupname = 'Options', $refreshpage)
{
  global $DB;

  $modulesettings = $DB->query("SELECT * FROM " . TABLE_PREFIX . "modulesettings
                                WHERE moduleid = '$moduleid' AND groupname = '$groupname'
                                ORDER BY displayorder");

  $modulesettingrows = $DB->get_num_rows($modulesettings);

  PrintSection($groupname);

  if($modulesettingrows)
  {
    echo '<form method="post" action="'.$refreshpage.'">

          <table width="100%" border="0" cellpadding="5" cellspacing="0">
          <input type="hidden" name="refreshpage" value="'.$refreshpage.'" />';

    while($setting = $DB->fetch_array($modulesettings))
    {
      if(strlen($setting['title']))
      {
        echo '<tr>
                <td class="tdrow1" colspan="2">' . $setting['title'] . '</td>
              </tr>';
      }

      echo '<tr>
              <td class="tdrow2" width="70%">'.$setting['description'].'</td>
              <td class="tdrow3" valign="top">';

      if($setting['input']=="text")
      {
        echo '<input type="text" size="40" name="settings['.$setting['settingid'].']" value="'.htmlspecialchars($setting['value']).'">';
      }
      elseif($setting['input']=="yesno")
      {
        echo "是<input type=\"radio\" name=\"settings[$setting[settingid]]\"  ".iif($setting['value']==1,"checked","")." value=\"1\">&nbsp;&nbsp;&nbsp;否<input type=\"radio\" name=\"settings[$setting[settingid]]\" ".iif($setting['value']==0,"checked","")." value=\"0\">";
      }
      elseif($setting['input']=="textarea")
      {
        echo "<textarea name=\"settings[$setting[settingid]]\" rows=\"4\" cols=\"30\">".$setting['value']."</textarea>";
      }
      elseif($setting['input']=="wysiwyg")
      {
        echo "<textarea name=\"settings[$setting[settingid]]\" rows=\"4\" cols=\"30\" style=\"width:100%;\" class=\"mceEditor\">".$setting['value']."</textarea>";
      }
      else
      {
        eval("echo \"$setting[input]\";");
      }

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

    echo '<tr>
            <td class="tdrow1" bgcolor="#FCFCFC" colspan="2" align="center">
             <input type="hidden" name="updatesettings" value="Save Settings" />
             <input type="submit" value=" 保存设置 " />
            </td>
          </tr>
          </table>
          </form>';
  }
  else
  {
    echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td class="tdrow1">&nbsp;</td>
          </tr>
          <tr>
            <td class="tdrow2" align="center">此模块无任何可设置选项.</td>
          </tr>
          </table>';
  }

  EndSection();

}



// ########################## UPDATE MODULE SETTINGS ###########################

function UpdateModuleSettings($settings, $refreshpage)
{
  global $DB;

  while(list($key,$val) = each($settings))
  {
    $DB->query("UPDATE " . TABLE_PREFIX . "modulesettings SET value='". trim($val) . "' WHERE settingid='$key'");
  }

  PrintRedirect($refreshpage, 1);
}



// ########################## DELETE MODULE COMMENTS ###########################

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

  $DB->query("DELETE FROM " . TABLE_PREFIX . "comments WHERE moduleid = '$moduleid' AND objectid = '$objectid'");
}

// ############################### PRINT ERROR #################################

function PrintErrors($errors, $errortitle = '运行错误')
{
  echo '<table width="100%" border="0" cellpadding="5" cellspacing="6">
        <tr>
          <td style="border: 1px solid #FF0000; font-size: 12px;" bgcolor="#FFE1E1"><u>' . $errortitle . '</u><br /><br />系统运行过程中发现如下错误:<br /><br />';

  if(is_array($errors))
  {
    for($i = 0; $i < count($errors); $i++)
      echo '<b>' . ($i + 1) . ') ' . $errors[$i] . '</b><br /><br />';
  }
  else
    echo '<b>1) ' . $errors . '</b><br /><br />';

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


// ######################## DISPLAY CATEGORY SELECTION #########################

function DisplayCategorySelection($categoryid = 0, $showzerovalue = 0, $parentid = 0, $sublevelmarker = '', $selectname = 'parentid')
{
  global $DB;

  // start selection box
  if($parentid == 0)
  {
    echo '<select name="' . $selectname . '">';

    if($showzerovalue)
    {
      echo '<option value="0"></option>';
    }
  }
  else
  {
    $sublevelmarker .= '- ';
  }

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

  while($category = $DB->fetch_array($getcategories))
  {
    echo '<option value="' . $category['categoryid'] . '" ' . iif($categoryid == $category['categoryid'], 'SELECTED', '') . '>' . $sublevelmarker . $category['name'] . '</option>';
    DisplayCategorySelection($categoryid, $showzerovalue, $category['categoryid'], $sublevelmarker);
  }

  // end the selection box
  if($parentid == 0)
  {
    echo '</select>';
  }
}



// ############################## CONFIRM DELETE ###############################

function ConfirmDelete($description = '<b>请确认删除:</b>', $hiddenvalues = '', $formredirect = '')
{
  PrintSection('确认删除');
  echo '<form method="post" action="' . $formredirect . '">
        ' . $hiddenvalues . '
        <table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow2" style="padding: 25px;">' . $description . '</td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2" align="center"><input type="submit" name="confirmdelete" value=" 确定 " /> &nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" name="confirmdelete" value=" 取消 " /></td>
        </table>

        </form>';
  EndSection();
}



// ############################## CLEAN FORM VALUE #############################
// this is an interesting function that needs a bit of explaining.
// basically any frontend submitted information goes through htmlspecialchars
// so in the admin panel this information will not break a form (<input value="&quote;test", instead of value=""test"
// however when submitting information from the admin panel, admins should have the
// option of submitting HTML, but if they do then forms will break <input type value=""test"
// Now, the solution seems simple, just htmlspecialchars($value) of all admin html forms,
// but the problem is doing that with information that was submitted from the frontend
// becuase htmlspecialchars(&quote;) = &ampquote;
// So the real solution is to first UNhtmlespecialchars the information, and then
// htmlspecilachars the information.

// this only needs to be done on <input type="text" forms in the admin panel
// that ALSO receive frontend information (like the chatterbox, news, guestbook, etc..)

function CleanFormValue($value)
{
  return htmlspecialchars(unhtmlspecialchars($value), ENT_QUOTES);
}

// ########################### SET PAGE CHARACTER SET ##############################

function SetPageCharacterSet()
{
        global $DB;

        // Get the correct characterset
  $language = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'language'");
  $language = explode('|', $language[0]);

  header("Content-Type: text/html; charset=" . $language[2]);
}

// ########################### 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;

}


// ########################### Show Error Message ##############################

function Errmsg($string) {
echo "<script> alert('$string');  history.back(); </script> "; exit;
}
?>