<?php
define('IN_ADMIN', true);
define('IN_WEENCOMPANY', true);

$rootpath = "./../";

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

PrintHeader('设置菜单');

// get the value of $action
$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : 'displaycategory');

// this page always has to run with the categoryid variable set, so lets get it now, default 1 (home)
$categoryid = isset($_POST['categoryid']) ? $_POST['categoryid'] : (isset($_GET['categoryid']) ? $_GET['categoryid'] : 1);



// ############################### ALLOW PARENT ################################

function AllowParent($categoryid, $parentid)
{
  global $DB;

  // cylce through all this categoryid's children and see if the selected parentid for categoryid is equal
  // if so then return false, because category's can not be a parent of a child and also the child be a parent for that same category!
  $getcategories = $DB->query("SELECT * FROM " . TABLE_PREFIX . "categories WHERE parentid = $categoryid");

  while($category = $DB->fetch_array($getcategories))
  {
    if($category['categoryid'] == $parentid)
    {
      return 0;
    }
    else
    {
      // go deeper and check all children of this categoryid
      if(!AllowParent($category['categoryid'], $parentid))
      {
        return 0;
      }
    }
  }

  return 1;
}



// ############################## UPDATE CATEGORY ##############################

if($action == 'updatecategory')
{
  // get $_POST variables
  // $categoryid is received above
  $parentid        = $_POST['parentid'];
  $categoryname    = $_POST['categoryname'];
  $categoryurlname = strlen($_POST['categoryurlname']) ? $_POST['categoryurlname'] : $_POST['categoryname'];
  $categorylink    = $_POST['categorylink'];
  $categorytarget  = $_POST['categorytarget'];
  $menuwidth       = strlen($_POST['menuwidth']) ? $_POST['menuwidth'] : 0;
  $modules         = $_POST['modules'];
  $nolink         = $_POST['nolink'];

  // initialize the errors variable
  $errors = array();

  // update the modules unless a new design has been selected
  $updatemodules = true;


  // fix up the categoryurl name by removing single and double quotes
  $categoryurlname = str_replace('"', "",  $categoryurlname);
  $categoryurlname = str_replace("'", "",  $categoryurlname);
  $categoryurlname = str_replace(" ", "_", $categoryurlname);

  // check if the user entered a category name
  if(!strlen($categoryname))
  {
    $errors[] = '菜单名称不能为空!';

    $DB->query("UPDATE " . TABLE_PREFIX . "categories SET urlname    = '$categoryurlname',
                                                          link       = '$categorylink',
                                                                                                                  target     = '$categorytarget',
                                                          menuwidth  = $menuwidth,
														  nolink  = $nolink
                                                    WHERE categoryid = $categoryid");
  }
  else
  {
    // update category name, and link
    $DB->query("UPDATE " . TABLE_PREFIX . "categories SET name       = '$categoryname',
                                                          urlname    = '$categoryurlname',
                                                          link       = '$categorylink',
                                                                                                                  target     = '$categorytarget',
                                                          menuwidth  = $menuwidth,
														  nolink  = $nolink
                                                    WHERE categoryid = $categoryid");
  }

  $changeParent = false;

  // update parentid
  if($categoryid != $parentid)
  {
    // check and see if the parent selection is a child of this category (that will really mess things up!)
    if(AllowParent($categoryid, $parentid))
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "categories SET parentid = '$parentid' WHERE categoryid = '$categoryid'");
      $changeParent = true;
    }
    else
    {
      $errors[] = '上级菜单不能设置为其子菜单的子菜单!';
    }
  }
  else
  {
    $errors[] = '一个菜单不能设置成自己的上级菜单!';
  }


  // update template design and pagesort?
  if(isset($_POST['designselection']))
  {
    $templateid          = $_POST['templateid'];
    $imagepath       = $_POST['designselection'];
    $currentdesignid = $_POST['currentdesignid'];

    $design = $DB->query_first("SELECT designid, maxmodules FROM " . TABLE_PREFIX . "designs
                                WHERE templateid = '$templateid' AND imagepath = '$imagepath'");

    // has user selected a new design?
    if($design['designid'] != $currentdesignid)
    {
      // update design
      $DB->query("UPDATE " . TABLE_PREFIX . "categories SET designid = '" . $design['designid'] . "' WHERE categoryid = '$categoryid'");
    }

  }

  // update modules
  // check to see if a module was selected twice
  $checkKeysUniqueComparison = create_function('$value','if ($value > 1) return true;');
  $result = array_keys(array_filter(array_count_values($modules), $checkKeysUniqueComparison));

  for($i = 0; $i < count($result); $i++)
  {
    if($result[$i] != 1)
    {
      $moduleerror = 1;
    }
  }

  if(isset($moduleerror))
  {
    $errors[] = '同一个菜单下不能放置相同的模块!<br />
                 提示: 可以将其复制的模块放在此菜单.';
  }
  else
  {
    // update modules

    // first delete pagesort modules for this category
    $DB->query("DELETE FROM " . TABLE_PREFIX . "pagesort WHERE categoryid = '$categoryid'");

    // now insert the new modules into pagesort
    for($i = 0; $i < count($modules); $i++)
    {
      // convert Menus (ex: + Custom Modules) to the empty module
      if(empty($modules[$i]))
      {
        $modules[$i] = 1 ;
      }

      $DB->query("INSERT INTO " . TABLE_PREFIX . "pagesort (categoryid, moduleid, displayorder)
                  VALUES ('$categoryid', '" . $modules[$i] . "', '".($i+1)."')");
    }
  }

  if(count($errors) > 0)
  {
    PrintErrors($errors);
    $action = 'displaycategory';
  }
  else
  {
    if($changeParent)
      echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';

    PrintRedirect('mycategories.php?categoryid=' . $categoryid, 1);
  }

}



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

if($action == 'displaycategory')
{
  // get the category information
  $category = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "categories WHERE categoryid = '$categoryid'");

  // get the category's design image and it's max modules
  $currentdesign = $DB->query_first("SELECT designid, templateid, maxmodules, imagepath FROM " . TABLE_PREFIX . "designs WHERE designid = '" . $category['designid'] . "'");

  // get all the designs for this template
  $getdesigns = $DB->query("SELECT designid, maxmodules, imagepath FROM " . TABLE_PREFIX . "designs WHERE templateid = '" . $currentdesign['templateid'] . "' ORDER BY designid");
  $designrows = $DB->get_num_rows($getdesigns);

  // get the cloned modules for selection, weencompany modules are hardcoded into this script
  $getclonedmodules = $DB->query("SELECT moduleid, name FROM " . TABLE_PREFIX . "modules WHERE authorname = 'weencompany_cloner' ORDER BY name");
  $clonedmodulerows = $DB->get_num_rows($getclonedmodules);

  while($clonedmodule = $DB->fetch_array($getclonedmodules))
  {
    $clonedmoduleid[]   = $clonedmodule['moduleid'];
    $clonedmodulename[] = $clonedmodule['name'];
  }

  // get the downloaded modules for selection
  $getdownloadedmodules = $DB->query("SELECT moduleid, name FROM " . TABLE_PREFIX . "modules WHERE authorname != 'weencompany' AND authorname != 'weencompany_cloner' ORDER BY moduleid");
  $downloadedmodulerows = $DB->get_num_rows($getdownloadedmodules);

  while($downloadedmodule = $DB->fetch_array($getdownloadedmodules))
  {
    $downloadedmoduleid[]   = $downloadedmodule['moduleid'];
    $downloadedmodulename[] = $downloadedmodule['name'];
  }

  // get all custom modules to be displayed in the selection boxes
  $getcustommodules = $DB->query("SELECT custommoduleid, name FROM " . TABLE_PREFIX . "custommodules ORDER BY name");
  $custommodulerows = $DB->get_num_rows($getcustommodules);

  while($custommodule = $DB->fetch_array($getcustommodules))
  {
    $custommoduleid[]   = $custommodule['custommoduleid'];
    $custommodulename[] = $custommodule['name'];
  }

  // get the current selected modules for this category
  $getselectedmodules = $DB->query("SELECT moduleid FROM " . TABLE_PREFIX . "pagesort WHERE categoryid = '$categoryid' ORDER BY displayorder");

  while($selectedmodule = $DB->fetch_array($getselectedmodules))
  {
    $selectedmoduleid[]   = $selectedmodule['moduleid'];
  }

  // check to see if user is integrating with a forum, if so then display top posters and latest posts
  if($checkintegration = $DB->query_first("SELECT usersystemid FROM " . TABLE_PREFIX . "usersystems WHERE name != 'weenCompany' AND activated = '1'"))
  {
    $forumintegration = true;
  }
  else
  {
    $forumintegration = false;
  }

  // create the module selection boxes
  for($i = 0; $design = $DB->fetch_array($getdesigns); $i++)
  {
    // start of the table
    $moduleselection[$i] = '<table width="400" border="0" cellspacing="8" cellpadding="0">';

    // display 'i' amount of selection modules for the category
    for($moduleselectioncount = 0; $moduleselectioncount < $design['maxmodules']; $moduleselectioncount++)
    {
      // this code makes sure that the unselected design's modules are all set to empty,
      // although this code can possible mess up a selected design and set it's modules to empty by
      // previously setting an unselected design's $selectedmoduleid to 1, therefore we need to keep a
      // copy of the selectedmoduleid and revert it back to normal at the end of this for loop
      if($currentdesign['designid'] != $design['designid'])
      {
        $oldselectedmoduleid = $selectedmoduleid[$moduleselectioncount];
        $selectedmoduleid[$moduleselectioncount] = 1;
      }

      $moduleselection[$i] .= '<tr>';
      $moduleselection[$i] .= '<td>模块位置 ' . ($moduleselectioncount + 1) . ':</td>';
      $moduleselection[$i] .= '<td>';
      $moduleselection[$i] .= '<select name="modules[]">';
      $moduleselection[$i] .= '<option value="1"' . iif($selectedmoduleid[$moduleselectioncount] == 1," selected","") . '>无</option>';
      $moduleselection[$i] .= '<optgroup label="系统模块">';
      $moduleselection[$i] .= '<option value="2"  ' . iif($selectedmoduleid[$moduleselectioncount] == 2,  "selected", "") . '>文章模块</option>';
      $moduleselection[$i] .= '<option value="3"  ' . iif($selectedmoduleid[$moduleselectioncount] == 3,  "selected", "") . '>最新文章</option>';
      $moduleselection[$i] .= '<option value="4"  ' . iif($selectedmoduleid[$moduleselectioncount] == 4,  "selected", "") . '>留言簿</option>';
      $moduleselection[$i] .= '<option value="6"  ' . iif($selectedmoduleid[$moduleselectioncount] == 6,  "selected", "") . '>联系框</option>';
      $moduleselection[$i] .= '<option value="7"  ' . iif($selectedmoduleid[$moduleselectioncount] == 7,  "selected", "") . '>留言板</option>';

      if($forumintegration)
      {
        $moduleselection[$i] .= '<option value="8" ' . iif($selectedmoduleid[$moduleselectioncount] == 8, "selected", "") . '>最新话题</option>';
        $moduleselection[$i] .= '<option value="9" ' . iif($selectedmoduleid[$moduleselectioncount] == 9, "selected", "") . '>发帖排行</option>';
      }

      $moduleselection[$i] .= '<option value="10" ' . iif($selectedmoduleid[$moduleselectioncount] == 10, "selected", "") . '>用户登陆</option>';
      $moduleselection[$i] .= '<option value="11" ' . iif($selectedmoduleid[$moduleselectioncount] == 11, "selected", "") . '>用户资料</option>';
      $moduleselection[$i] .= '<option value="12" ' . iif($selectedmoduleid[$moduleselectioncount] == 12, "selected", "") . '>用户注册</option>';
      $moduleselection[$i] .= '<option value="16" ' . iif($selectedmoduleid[$moduleselectioncount] == 16, "selected", "") . '>链接模块</option>';
      $moduleselection[$i] .= '<option value="17" ' . iif($selectedmoduleid[$moduleselectioncount] == 17, "selected", "") . '>产品模块</option>';
      $moduleselection[$i] .= '<option value="18" ' . iif($selectedmoduleid[$moduleselectioncount] == 18, "selected", "") . '>网站计数器</option>';
      $moduleselection[$i] .= '<option value="31" ' . iif($selectedmoduleid[$moduleselectioncount] == 31, "selected", "") . '>二级菜单</option>';
      $moduleselection[$i] .= '</optgroup>';

      // display cloned modules
      if($clonedmodulerows)
      {
        $moduleselection[$i] .= '<optgroup label="复制的模块">';

        for($x = 0; $x < $clonedmodulerows; $x++)
        {
          $moduleselection[$i] .= '<option value="'.$clonedmoduleid[$x].'"'.iif($clonedmoduleid[$x] == $selectedmoduleid[$moduleselectioncount]," selected","").'>'.$clonedmodulename[$x].'</option>';
        }
        $moduleselection[$i] .= '</optgroup>';
      }

      // display custom modules
      if($custommodulerows)
      {
        $moduleselection[$i] .= '<optgroup label="自定义模块">';

        for($x = 0; $x < $custommodulerows; $x++)
        {
          $moduleselection[$i] .= '<option value="c'.$custommoduleid[$x].'"'.iif('c'.$custommoduleid[$x] == $selectedmoduleid[$moduleselectioncount]," selected","").'>'.$custommodulename[$x].'</option>';
        }
        $moduleselection[$i] .= '</optgroup>';
      }

      // display downloaded modules
      if($downloadedmodulerows)
      {
        $moduleselection[$i] .= '<optgroup label="下载的模块">';

        for($x = 0; $x < $downloadedmodulerows; $x++)
        {
          $moduleselection[$i] .= '<option value="' . $downloadedmoduleid[$x] . '"' . iif($downloadedmoduleid[$x] == $selectedmoduleid[$moduleselectioncount], " selected","").'>'.$downloadedmodulename[$x] . '</option>';
        }
        $moduleselection[$i] .= '</optgroup>';
      }

      $moduleselection[$i] .= '</select></td></tr>';

      if($currentdesign['designid'] != $design['designid'])
      {
        $selectedmoduleid[$moduleselectioncount] = $oldselectedmoduleid;
      }

    } // end the for loop

    // end the table
    $moduleselection[$i] .= '</table>';

  } // end the while loop


  // print some javascript
  // major props to adam cohen 'abcohen' for this awesome javascript code!!
  echo '<script language="javascript" type="text/javascript">

        function change_design(newimage)
        {
          document.designimage.src = "./../templates/" + newimage;
        }

        var moduleselectiontext = new Array();

        ';

  for($i = 0; $i < count($moduleselection); $i++)
  {
    echo 'moduleselectiontext[' . $i . '] = \'' . addslashes($moduleselection[$i]) . '\';';
    echo "\n\n";
  }

  echo 'function DisplayModuleSelection(which)
        {
          if(document.all)
          {
            moduleselection.innerHTML = moduleselectiontext[which];
          }
          else if(document.getElementById)
          {
            document.getElementById("moduleselection").innerHTML = moduleselectiontext[which];
          }
        }

        </script>';


  // start printing the section
  PrintSection('菜单: '.$category['name']);
  echo '<form enctype="multipart/form-data" method="post" action="./mycategories.php" name="categoryform">
        <input type="hidden" name="action" value="updatecategory" />
        <input type="hidden" name="categoryid" value="' . $categoryid . '" />

        <table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow1" colspan="2">菜单名称</td>
        </tr>
        <tr>
          <td class="tdrow2" width="70%">编辑菜单的名称:</td>
          <td class="tdrow3" valign="top"><input type="text" name="categoryname" value="' . htmlentities($category['name'], ENT_QUOTES,'gb2312') . '" /></td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">友好访问名称</td>
        </tr>
        <tr>
          <td class="tdrow2" width="70%">编辑菜单的友好访问名称:<br />注: 当网站的友好访问功能打开时, 显示在浏览器地址栏中名称, 要求使用<font class=ohred>英文字符</font>.</td>
          <td class="tdrow3" valign="top"><input type="text" name="categoryurlname" value="' . htmlentities($category['urlname'], ENT_QUOTES,'gb2312') . '" /></td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">上级菜单</td>
        </tr>
        <tr>
          <td class="tdrow2" width="70%">选择一个菜单为上级菜单, 留空为顶级菜单:</td>
          <td class="tdrow3" valign="top">';

  // first argument:  categoryid that should be selected
  // second argument: display an empty first row of categoryid with value zero (1 = yes, 0 = no)
  DisplayCategorySelection($category['parentid'], 1);


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

  if($category['parentid'] == 0)
  {
    echo '<tr>
            <td class="tdrow1" colspan="2">菜单宽度</td>
          </tr>
          <tr>
            <td class="tdrow2" width="70%">
              菜单显示的宽度(像素):
            </td>
            <td class="tdrow3" valign="top">
              <input type="text" name="menuwidth" value="' . iif($category['menuwidth'] == 0, '', $category['menuwidth']) . '" size="6" />
            </td>
          </tr>';
  }

  echo '<tr>
          <td class="tdrow1" colspan="2">菜单链接</td>
        </tr>
        <tr>
          <td class="tdrow2" width="70%">
            菜单的转向链接(设置此项, 点击菜单时将不打开以下设置的模块):<br />
            如: http://www.weentech.com/bbs; forum/index.php等等(最好设置为全路径URL).
          </td>
          <td class="tdrow3" valign="top">
            <input type="text" name="categorylink" value="' . htmlentities($category['link'], ENT_QUOTES,'gb2312') . '" size="35" />
          </td>
        </tr>
                
        <tr>
          <td class="tdrow1" colspan="2">打开方式</td>
        </tr>				<tr>
          <td class="tdrow2" width="70%">
            点击菜单时打开窗口的方式:<br/>如: "_blank", "_self", "_parent", "_top".
          </td>
          <td class="tdrow3" valign="top">
            <input type="text" name="categorytarget" value="' . htmlentities($category['target'], ENT_QUOTES,'gb2312') . '" size="15" />
          </td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">父菜单无链接模式</td>
        </tr>				
		<tr>
          <td class="tdrow2" width="70%">
            当此菜单拥有下属菜单时, 是否显示为无链接状态?<br/>如: 当菜单此项设置为"是", 且其拥有下属菜单时, 前台点击此菜单将不加载任何内容或打开任何页面.
          </td>
          <td class="tdrow3" valign="top">
             是<input type="radio" name="nolink" '.iif($category['nolink']==1,"checked","").' value="1">&nbsp;&nbsp;&nbsp;否<input type="radio" name="nolink" '.iif($category['nolink']==0,"checked","").' value="0">
          </td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">放置模块与设置布局</td>
        </tr>
        <tr>
          <td class="tdrow2" width="70%" valign="top">

            <span id="moduleselection"></span>

            <table border="0" cellspacing="8" cellpadding="0">
            <tr>
              <td><br />说明: 模块的位置编号与右侧布局样式图中的编号相对应, 编号小的显示在前.</td>
            </tr>
            </table>

          </td>
          <td class="tdrow3" valign="top">
            <img name="designimage" src="./../templates/' . $currentdesign['imagepath'] . '" border="0" alt="0" />';

  unset($getdesigns);
  unset($designrows);
  unset($design);

  // get all the designs for this template
  $getdesigns = $DB->query("SELECT designid, maxmodules, imagepath FROM " . TABLE_PREFIX . "designs WHERE templateid = '" . $currentdesign['templateid'] . "' ORDER BY designid");
  $designrows = $DB->get_num_rows($getdesigns);

  echo '<br /><br />选择布局:
        <input type="hidden" name="currentdesignid" value="' . $category['designid'] . '" />
        <input type="hidden" name="templateid" value="' . $currentdesign['templateid'] . '" />
        <select name="designselection" onchange="change_design(this.options[selectedIndex].value); DisplayModuleSelection(document.categoryform.designselection.selectedIndex)">';

  for($designcount = 1; $design = $DB->fetch_array($getdesigns); $designcount++)
  {
    echo '<option value="' . $design['imagepath'] . '" ' . iif($currentdesign['designid'] == $design['designid'], "selected", "") . '>样式 ' . $designcount . '</option>';
  }

  echo '    </select>

            <script language="javascript" type="text/javascript">
            DisplayModuleSelection(document.categoryform.designselection.selectedIndex);
            </script>

          </td>
        </tr>
        <tr>
          <td class="tdrow1" bgcolor="#FCFCFC" colspan="2" align="center">
           <input type="submit" value=" 保存更新 " />
          </td>
        </tr>
        </table>
        </form>';

  EndSection();

}



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

PrintFooter();

?>