<?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,'UTF-8') . '" /></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,'UTF-8') . '" /></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,'UTF-8') . '" 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,'UTF-8') . '" size="15" />
          </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();

?>
