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

define('IN_ADMIN', true);
define('IN_WEENCOMPANY', true);

$rootpath = "./../";

include($rootpath . 'includes/core.php');

PrintHeader('論壇接口');


// ############################ GET FORUM FUNCTIONS ############################

// get forum functions if we are updating to a forum, or if we are currently already integrated with a forum
if( (isset($_POST['systemname']) AND $_POST['systemname'] != 'weenCompany') OR ($usersystem = $DB->query_first("SELECT name, dbname, tblprefix, folderpath FROM " . TABLE_PREFIX . "usersystems WHERE activated = '1' AND name != 'weenCompany'")) )
{
  $switchvar = isset($_POST['systemname']) ? $_POST['systemname'] : $usersystem['name'];

  switch($switchvar)
  {
    case 'Discuz5':                 include('./forumintegration/discuz5.php');    break;
    case 'vBulletin 2':             include('./forumintegration/vbulletin2.php'); break;
    case 'phpBB2':                  include('./forumintegration/phpbb2.php');     break;
    case 'vBulletin 3':             include('./forumintegration/vbulletin3.php'); break;
    case 'Invision Power Board 2':  include('./forumintegration/ipb2.php');       break;
    case 'Simple Machines Forum 1': include('./forumintegration/smf1.php');       break;
  }
}


// ############################ RESTORE FORUM TEMPLATE #############################

if($action == 'restoreforumtemplate')
{
  // switch to forum db
  $DB->select_db($usersystem['dbname']);

  // restore forum template
  RestoreForumTemplate();

  // switch back to weencompany db
  $DB->select_db($dbname);

  PrintRedirect('forumintegration.php',1);
}


// ################################ TEMPLATE FORUM #################################

if($action == 'templateforum')
{
  // locate template's forumtemplate.php, this is bad method but it works:
  $gettemplate       = $DB->query_first("SELECT previewimage FROM " . TABLE_PREFIX . "templates where activated = '1'");
  $gettemplatefolder = explode("/", $gettemplate['previewimage']);

  if(is_file('../templates/' . $gettemplatefolder[0] . '/forumtemplate.php'))
  {
    // we need the site's main settings
    $getmainsettings = $DB->query("SELECT varname, value FROM " . TABLE_PREFIX . "mainsettings");
    for($i = 0; $setting = $DB->fetch_array($getmainsettings); $i++)
    {
      $mainsettings[$setting['varname']] = $setting['value'];
    }

    $weensyspath     = $mainsettings['weensysurl'];
    $logo       = $mainsettings['currentlogo'];
	
	if($mainsettings['websitebeian']){
		$websitebeian = ' <a href="http://www.miibeian.gov.cn/" target="_blank">' . $mainsettings['websitebeian'] . '</a>';
        $mainsettings['copyrighttext'] .= $websitebeian;
	}

    $copyright  = $mainsettings['bfo'] ? $mainsettings['copyrighttext'] : $mainsettings['copyrighttext'] . '. Created by <a href="http://www.weentech.com" target="_blank" class="poweredbyween">weenCompany</a>';
    $modrewrite = $mainsettings['modrewrite'];

    // fix relative url in logo;
    if(substr_count($logo, 'src="') AND !substr_count($logo, 'src="http') AND !substr_count($logo, 'src="www'))
    {
      $logo = str_replace('src="', 'src="' . $weensyspath, $logo);
    }

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

    // get guest categories
    $getguestcategoryids = $DB->query_first("SELECT categorymenuids FROM " . TABLE_PREFIX . "usergroups WHERE usergroupid = 4");
    $guestcategoryids = explode(',', $getguestcategoryids['categorymenuids']);

    $javascriptadded = 0;
    $javascript = '';

    for($i = 0; $category = $DB->fetch_array($getcategories); $i++)
    {
      if(in_array($category['categoryid'], $guestcategoryids))
      {
        if(strlen($category['image']))
        {
          // hover image
          if(strlen($category['hoverimage']))
          {
            $categoryname[$i] = '<img name="sdhover'.$category['categoryid'].'" src="'.$weensyspath.'images/'.$category['image'].'" border="0" onMouseOver="Rollover('.$category['categoryid'].',`'.$category['hoverimage'].'`, true)" onMouseOut="Rollover('.$category['categoryid'].',`'.$category['image'].'`, false)" />';

            if($javascriptadded == 0)
            {
              $javascript = '<script language="JavaScript">
                             function Rollover(imagename, image, over)
                             {
                               if(window.document.images)
                               {
                                 if (over)
                                   window.document.images["sdhover" + imagename].src = "'.$weensyspath.'images/" + image;
                                 else
                                   window.document.images["sdhover" + imagename].src = "'.$weensyspath.'images/" + image;
                               }
                             }
                            </script>';

              $javascriptadded = 1;
            }
          }
          else
          {
            $categoryname[$i] = '<img src="' . $weensyspath . 'images/'.$category['image'].'" border="0" />';
          }
        }
        else
        {
          // apostrophes can screw things up, so lets clean up the name
          $categoryname[$i] = htmlspecialchars($category['name'], ENT_QUOTES);
        }

        if(strlen($category['link']))
        {
          if( substr($category['link'], 0, 4) == 'http' || substr($category['link'], 0, 3) == 'www' )
          {
            $categorylink[$i] = $category['link'];
          }
          else
          {
            $categorylink[$i] = $weensyspath . $category['link'];
          }
        }
        else if($modrewrite)
        {
          $categorylink[$i] = $weensyspath . $category['urlname'];
        }
        else
        {
          $categorylink[$i] = $weensyspath . 'index.php?categoryid=' . $category['categoryid'];
        }
      }
      else
      {
        $i--;
      }
    }

    $categoryrows = $i;

    // include forumtemplate.php to get sdpre and sdpost
    include('../templates/' . $gettemplatefolder[0] . '/forumtemplate.php');

    // switch to forum db
    $DB->select_db($usersystem['dbname']);

    $message = TemplateForum($javascript . $weenheader, $weenfooter);

    // switch back to weencompany db
    $DB->select_db($dbname);

        if(isset($message))
        {
          PrintErrors($message);
        }
        else
        {
      PrintRedirect('forumintegration.php',1);
        }
  }
  else
  {
    // could not find file
    PrintErrors('weenCompany當前使用的模板不支持論壇模板接口!', '論壇接口錯誤');
  }

}


// ########################## UPDATE SYSTEM SETTINGS ###########################

function UpdateSystemSettings()
{
  global $DB, $dbname;

  $forumfolderpath = $_POST['forumfolderpath'];

  // update forum's to use these values:
  $cookiedomain = '';
  $cookiepath   = '/';

  if($_POST['systemname'] == 'weenCompany')
  {
    $DB->query("UPDATE " . TABLE_PREFIX . "usersystems SET activated = '0' WHERE activated = '1'");
    $DB->query("UPDATE " . TABLE_PREFIX . "usersystems SET activated = '1' WHERE name = 'weenCompany'");
    $DB->query("UPDATE " . TABLE_PREFIX . "mainsettings SET value = 'weenCompany' WHERE varname = 'smiliesystem'");
  }
  else if(strlen($forumfolderpath))
  {
    // fix the systemfolderpath, first get rid of the wrong slash
    $forumfolderpath = str_replace('\\\\', '/', trim($forumfolderpath));

    // now get rid of the starting slash
    if($forumfolderpath{0} == '/')
      $forumfolderpath = substr($forumfolderpath, 1);

    // now add a last slash
    if(substr($forumfolderpath, -1) != '/')
      $forumfolderpath .= '/';

    // get forum details and upgrade database
    if($forumsystem = GetForumSystem($forumfolderpath, $dbname, $cookiedomain, $cookiepath))
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "usersystems SET dbname        = '" . $forumsystem['dbname']        . "',
                                                             tblprefix     = '" . $forumsystem['tblprefix']     . "',
                                                             folderpath    = '" . $forumsystem['folderpath']    . "',
                                                             cookietimeout = '" . $forumsystem['cookietimeout'] . "',
                                                             cookieprefix  = '" . $forumsystem['cookieprefix']  . "',
                                                             extra         = '" . $forumsystem['extra']         . "'
                                                       WHERE name          = '" . $_POST['systemname']          . "'");

      PrintSection($forumsystem['name'] . ' 用戶群組關聯說明');
      echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
            <tr>
              <td class="tdrow1">設置說明</td>
            </tr>
            <tr>
              <td class="tdrow2">
                為了成功與論壇: ' . $forumsystem['name'] . ' 實行接口, 必須設置網站用戶群組與論壇用戶群組進行關聯.<br />
                <b>意思是: 關聯後, 您必須使用論壇的管理員帳號和密碼進行網站管理!</b><br /><br />
                
                1) 關聯方式如: 系統管理員&raquo;Admin, 註冊用戶&raquo;Registered Users, 遊客&raquo;Guest, 等等)<br />
                2) 沒有設置關聯的論壇用戶群組, weenCompany系統自動將其關聯到網站的"遊客"用戶組.<br />
				3) <font class="ohred">重要提示:</font> 如果論壇的管理員組不設置關聯到網站的系統管理員組, 後臺管理將無法登陸(除非手動修改數據庫, 取消論壇接口).<br />
                4) 完成設置後, 需用戶論壇的管理員帳號和密碼重新登陸網站後臺進行管理.<br />
              </td>
            </tr>
            </table>';
      EndSection();

      // get usergroups
      $getusergroups = $DB->query("SELECT usergroupid, name FROM " . TABLE_PREFIX . "usergroups ORDER BY usergroupid");

      switch($forumsystem['name'])
      {
        case 'Discuz5':
          $forumusergroup_sql = "SELECT groupid AS usergroupid, grouptitle AS usergroupname FROM " . $forumsystem['tblprefix'] . "usergroups ORDER BY groupid";
        break;
        case 'vBulletin 2':
          $forumusergroup_sql = "SELECT usergroupid AS usergroupid, title AS usergroupname FROM " . $forumsystem['tblprefix'] . "usergroup ORDER BY usergroupid";
        break;

        case 'vBulletin 3':
          $forumusergroup_sql = "SELECT usergroupid AS usergroupid, title AS usergroupname FROM " . $forumsystem['tblprefix'] . "usergroup ORDER BY usergroupid";
        break;

        case 'phpBB2':
          $forumusergroup_sql = "SELECT group_id AS usergroupid, group_name AS usergroupname FROM " . $forumsystem['tblprefix'] . "groups WHERE group_name != '' ORDER BY group_id";
        break;

        case 'Invision Power Board 2':
          $forumusergroup_sql = "SELECT g_id AS usergroupid, g_title AS usergroupname FROM " . $forumsystem['tblprefix'] . "groups ORDER BY g_id";
        break;

        case 'Simple Machines Forum 1':
          $forumusergroup_sql = "SELECT ID_GROUP AS usergroupid, groupName AS usergroupname FROM " . $forumsystem['tblprefix'] . "membergroups ORDER BY ID_GROUP";
        break;
      }

      // switch database? $dbname is include from config.php
      if($forumsystem['dbname'] != $dbname)
      {
        $DB->select_db($forumsystem['dbname']);
      }

      $getforumusergroups = $DB->query($forumusergroup_sql);

      // switch back to weencompany database? $dbname is include from config.php
      if($forumsystem['dbname'] != $dbname)
      {
        $DB->select_db($dbname);
      }

      for($i = 0; $forumusergroup = $DB->fetch_array($getforumusergroups); $i++)
      {
        $forumusergroupid[$i]   = $forumusergroup['usergroupid'];
        $forumusergroupname[$i] = $forumusergroup['usergroupname'];
      }

      PrintSection($forumsystem['name'] . ' 用戶群組關聯設置');
      echo '<form method="post" action="forumintegration.php">
            <input type="hidden" name="action" value="updatesystemsettings2" />
            <input type="hidden" name="forumname" value="' . $forumsystem['name'] . '" />

            <table width="100%" border="0" cellpadding="5" cellspacing="0">
            <tr>
              <td class="tdrow1">網站用戶組</td>
              <td class="tdrow1" align="center">&raquo;</td>
              <td class="tdrow1">' . $forumsystem['name'] . ' 論壇用戶組</td>
            </tr>';

      while($usergroup = $DB->fetch_array($getusergroups))
      {
        echo '<tr>
                <td class="tdrow2" width="45%">' . $usergroup['name'] . '</td>
                <td class="tdrow3" width="10%" align="center">&raquo;</td>
                <td class="tdrow2" width="45%">
                  <select name="weencompanyusergroupids[' . $usergroup['usergroupid'] . ']">
                  <option value=""></option>';

        if($forumsystem['name'] == 'phpBB2')
        {
                  echo '<option value="-3">Registered Users</option>';
        }

        for($i = 0; $i < count($forumusergroupid); $i++)
        {
          echo '<option value="' . $forumusergroupid[$i] . '">' . $forumusergroupname[$i] . '</option>';
        }

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

      echo '<tr>
              <td class="tdrow1" colspan="3" align="center"><input type="submit" value=" 提交保存 " onclick="return confirm(\'確定設置網站管理員組與論壇管理員組關聯了嗎?\');" /></td>
            </tr>
            </table>

            </form>';
      EndSection();
    }
    else
    {
      $errors[] = 'weenCompany網站系統無法找到到您選擇的論壇: ' . $_POST['systemname'] . ', 請檢查論壇所在目錄是否正確!';
    }
  }
  else
  {
    $errors[] = 'weenCompany網站系統無法找到到您選擇的論壇: ' . $_POST['systemname'] . ', 請檢查論壇所在目錄是否正確!';
  }

  if(isset($errors))
  {
    PrintErrors($errors, '論壇接口錯誤');
    DisplayDefault();
  }
  else if($_POST['systemname'] == 'weenCompany')
  {
    echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';
    PrintRedirect('forumintegration.php', 1);
  }
}



if($action == 'updatesystemsettings2')
{
  $weencompanyusergroupids = $_POST['weencompanyusergroupids'];

  // update settings
  while(list($key, $value) = each($weencompanyusergroupids))
  {
    if($value == '')
    {
      $value = 0;
    }

    $DB->query("UPDATE " . TABLE_PREFIX . "usergroups SET forumusergroupid = '$value' WHERE usergroupid = '$key'");
  }

  $DB->query("UPDATE " . TABLE_PREFIX . "usersystems SET activated = '0' WHERE activated = '1'");
  $DB->query("UPDATE " . TABLE_PREFIX . "usersystems SET activated = '1' WHERE name = '" . $forumname . "'");

  echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';
  PrintRedirect('forumintegration.php', 1);
}



// ############################### PRINT DEFAULT ###############################

function DisplayDefault()
{
  global $DB;

  $usersystem = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "usersystems WHERE activated = '1'");

  $usersystem['folderpath'] = isset($_POST['forumfolderpath']) ? $_POST['forumfolderpath'] : $usersystem['folderpath'];
  $usersystem['name']       = isset($_POST['systemname']) ? $_POST['systemname'] : $usersystem['name'];

  PrintSection('論壇接口設置');
  echo '<form method="post" action="forumintegration.php">
        <input type="hidden" name="action" value="updatesystemsettings" />

        <table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow1" colspan="2">選擇論壇</td>
        </tr>
        <tr>
          <td class="tdrow2" width="80%">
            先按"論壇安裝要求"安裝weenCompany網站系統支持接口的論壇, 然後選擇論壇實行接口:<br/><br/>
			<font class="ohred">接口說明:</font> <br/>
		   1). 論壇和網站程序的編碼格式必須相同, 即: UTF-8編碼的論壇只能與UTF-8編碼的網站實現接口<br/>
		        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(GB2312編碼同理), 否則無法實現模板接口.<br />
		   2). 訪問論壇數據庫和網站數據庫的用戶名及密碼(非管理員用戶和密碼)保持一致, 否則無法實現接口.<br />
		   3). 當網站與論壇實行接口後, 網站的用戶註冊及登陸系統將不再工作, 統一使用論壇的用戶系統.<br />
		   4). <font class="ohred">重要提示:</font> 使用論壇接口後, 原網站用戶將無法正常登陸網站, 直至關閉論壇接口.<br />
           5). 使用論壇接口後, 用戶群組訪問網站的權限和訪問論壇的權限應在網站和論壇後臺獨立進行設置.<br />
           6). 使用論壇接口後, 可在表情圖標管理中為網站前臺選擇使用論壇表情圖標系統.<br />
		   7). 使用論壇接口後, 再選擇"關閉"保存設置, 網站與論壇的用戶系統將恢復到獨立運行狀態.<br /><br />
          </td>
          <td class="tdrow3" valign="top">

           <select name="systemname">
             <option value="weenCompany"              ' . iif($usersystem['name'] == 'weenCompany',              'selected', '') . '>關閉</option>
			 <option value="phpBB2"                  ' . iif($usersystem['name'] == 'phpBB2',                  'selected', '') . '>phpBB2</option>
           </select>

          </td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">論壇目錄</td>
        </tr>
        <tr>
          <td class="tdrow2" width="80%">輸入網站論壇所在目錄:<br /><br />說明: 只能輸入相對路徑, 如: <i>bbs/</i><br /><br /></td>
          <td class="tdrow3" valign="top"><input type="text" name="forumfolderpath" value="'.CleanFormValue($usersystem['folderpath']).'" size="26" /></td>
        </tr>
        <tr>
          <td class="tdrow1" bgcolor="#FCFCFC" colspan="2" align="center">
           <input type="submit" value=" 保存設置 " />
          </td>
        </tr>
        </table>
        </form>';
  EndSection();


  // display template forum options if a forum is selected
  if($forumintegrated = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "usersystems WHERE activated = '1' AND name != 'weenCompany'"))
  {
    echo '<br />';

    PrintSection('模板接口設置');
    echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td class="tdrow1" colspan="2">論壇模板接口</td>
          </tr>
          <tr>
            <td class="tdrow2" width="80%">
              當網站與論壇成功實行接口後, 可進行模板接口, 使得論壇配匹到網站模板內, 如同論壇是網站的一個模塊一樣.
              <br /><br /><font class="ohred">重要提示:</font> 當您修改了網站模板文件(包括CSS樣式文件)後, 需要重新實行模板接口, 以保持匹配效果.<br /><br />
            </td>
            <td class="tdrow3" valign="top">
              <form method="post" action="forumintegration.php">
              <input type="hidden" name="action" value="templateforum" />
              <input type="submit" name="Submit" value="實行模板接口" />
              </form>
            </td>
          </tr>
          <tr>
            <td class="tdrow1" colspan="2">取消模板接口</td>
          </tr>
          <tr>
            <td class="tdrow2" width="80%">
              取消模板接口可以論壇恢復到初始樣式, 不再匹配到網站模板內.
              <br /><br /><font class="ohred">重要提示:</font> 在未取消模板接口前, 選擇關閉論壇接口, 則論壇模板仍處在接口狀態.<br /><br />
            </td>
            <td class="tdrow3" valign="top">
              <form method="post" action="forumintegration.php">
              <input type="hidden" name="action" value="restoreforumtemplate" />
              <input type="submit" name="Submit" value="取消模板接口" />
              </form>
            </td>
          </tr>
          </table>';
    EndSection();
  }

}



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

switch($action)
{
  case 'updatesystemsettings':
    UpdateSystemSettings();
  break;

  default:
    DisplayDefault();
}



PrintFooter();

?>
