<?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();

?>