<?php
// +---------------------------------------------+
// |     Copyright 2006 -2009 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 the value of $action
$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : 'displaycategories');

$parentselection = CreateParentSelection();
$listedcategories = array(); // used for finding lost categories
                            // which can happen if you make 2 categories parents each
                            // other (news parent = gallery, gallery parent = news)


// ########################### CREATE PARENT SELECTION #########################

function CreateParentSelection($parentselection = '', $parentid = 0, $sublevelmarker = '')
{
  global $DB;

  // start selection box
  if($parentid != 0)
  {
    $sublevelmarker .= '- ';
  }

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

  while($category = $DB->fetch_array($getcategories))
  {
    $parentselection .= '<option value="' . $category['categoryid'] . '">' . $sublevelmarker . $category['name'] . '</option>';
    $parentselection = CreateParentSelection($parentselection, $category['categoryid'], $sublevelmarker);
  }

  // end the selection box
  if($parentid == 0)
  {
    return '<select name="categoryparentids[]"><option value="0"></option>' . $parentselection . '</select>';
  }
  else
  {
    return $parentselection;
  }
}



// ############################ DISPLAY CATEGORIES #############################

function DisplayCategories($parentid = 0, $sublevelmarker = '')
{
  global $DB;
  global $stylepath;
  global $parentselection;
  global $listedcategories;  // used for finding lost categories
                            // which can happen if you make 2 categories parents each
                            // other (news parent = gallery, gallery parent = news)

  // start table
  if($parentid == 0)
  {
    PrintSection('網站菜單');
    echo '<form method="post" action="categories.php">
          <input type="hidden" name="action" value="updatecategories" />
          <table width="100%" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td class="tdrow1">顯示順序</td>
            <td class="tdrow1">菜單</td>
            <td class="tdrow1">編輯名稱</td>
            <td class="tdrow1">上級菜單</td>
            <td class="tdrow1" width="60" align="center">設置菜單</td>
            <td class="tdrow1" width="60" align="center">預覽</td>
            <td class="tdrow1" width="60" align="center">刪除</td>
          </tr>';
  }
  else
  {
    $sublevelmarker .= '- ';
  }

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

  while($category = $DB->fetch_array($getcategories))
  {
    $listedcategories[] = $category['name'];

    echo '<tr>
            <td class="tdrow2" align="center">
              <input type="hidden" name="categoryids[]" value="' . $category['categoryid'] . '" />
              <input type="text" name="displayorders[]" value="' . $category['displayorder'] . '"  size="4" maxlength="4" />
            </td>
            <td class="tdrow3">
              ' . $sublevelmarker . '<a href="mycategories.php?categoryid=' . $category['categoryid'] . '">' . iif(strlen($category['name']), $category['name'], '<b>未命名</b>') . '</a> (ID: '. $category['categoryid'] . ')
            </td>
            <td class="tdrow2"><input type="text" name="categorynames[]" value="' . iif(strlen($category['name']), $category['name'], '<b>未命名</b>') . '"  /></td>
            <td class="tdrow3">';

    if($category['parentid'] != 0)
    {
      echo str_replace(' value="' . $category['parentid'] . '">', ' value="' . $category['parentid'] . '" SELECTED>', $parentselection);
    }
    else
    {
      echo $parentselection;
    }

    echo '  </td>
            <td class="tdrow2" align="center"><a href="mycategories.php?categoryid=' . $category['categoryid'] . '"><img src="' . $stylepath . 'images/configure.gif" /></a></td>
            <td class="tdrow3" align="center">';

    if(strlen($category['link']) > 0)
    {
      if( substr($category['link'], 0, 4) == 'http' || substr($category['link'], 0, 3) == 'www' )
      {
        echo '<a href="' . $category['link'] . '" target="_blank"><img src="' . $stylepath . 'images/link.gif" /></a>';
      }
      else
      {
        echo '<a href="../' . $category['link'] . '" target="_blank"><img src="' . $stylepath . 'images/link.gif" /></a>';
      }
    }
    else
    {
      echo '<a href="../index.php?categoryid=' . $category['categoryid'] . '" target="_blank"><img src="' . $stylepath . 'images/magnifying_glass.gif" /></a>';
    }

    echo '</td>';

    // display the trash icon, unless it's the home category
    if($category['categoryid'] == 1)
    {
      echo '<td class="tdrow2" align="center"><img src="' . $stylepath . 'images/notrash.gif" /></td>';
    }
    else
    {
      echo '<td class="tdrow2" align="center">
              <a href="categories.php?action=deletecategory&categoryid=' . $category['categoryid'] . '" onclick="return confirm(\'確定刪除菜單: ' . iif(strlen($category['name']), $category['name'], '未命名') . ' 嗎?\r\n\r\n提示: 刪除此菜單, 則其下所有子菜單將被刪除!\');"><img src="' . $stylepath . 'images/trash.gif" /></a>
            </td>';
    }

    echo '</tr>';

    DisplayCategories($category['categoryid'], $sublevelmarker);
  }

  // end table
  if($parentid == 0)
  {
    echo '<tr>
            <td class="tdrow1" bgcolor="#FCFCFC" colspan="7" align="center">
             <input type="submit" value=" 保存更新 " />
            </td>
          </tr>
          </table>

          </form>';

    EndSection();
  }
}



// ########################### DELETE SUBCATEGORIES ############################
// a recursive function to delete all subcategories of a category

function DeleteSubcategories($parentid)
{
  global $DB;

  $subcategories = $DB->query("SELECT categoryid FROM " . TABLE_PREFIX . "categories WHERE parentid = '$parentid'");

  while($subcategory = $DB->fetch_array($subcategories))
  {
    DeleteSubcategories($subcategory['categoryid']);
    
	
    $DB->query("DELETE FROM " . TABLE_PREFIX . "categories WHERE categoryid = '" . $subcategory['categoryid'] . "'");
    $DB->query("DELETE FROM " . TABLE_PREFIX . "pagesort   WHERE categoryid = '" . $subcategory['categoryid'] . "'");
  }
}



// ########################### FIX LOST CATEGORIES #############################

if($action == 'fixlostcategories')
{
  $lostcategoryids = $_POST['lostcategoryids'];

  for($i = 0; $i < count($lostcategoryids); $i++)
  {
    $DB->query("UPDATE " . TABLE_PREFIX . "categories SET parentid = 0 WHERE categoryid = " . $lostcategoryids[$i]);
  }

  echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';

  PrintRedirect('categories.php?action=displaycategories', 1);
}



// ############################# DELETE CATEGORY ###############################

if($action == 'deletecategory')
{
  $categoryid    = is_numeric($_GET['categoryid']) ? intval($_GET['categoryid']) : (is_numeric($_POST['categoryid']) ? intval($_POST['categoryid']) : '');
  $confirmdelete = isset($_POST['confirmdelete']) ? $_POST['confirmdelete'] : '0';

  if( !is_int($categoryid))
  {
    $action = 'displaycategories';
  }
  else
  {
    // delete the category

    $DB->query("DELETE FROM " . TABLE_PREFIX . "categories WHERE categoryid = '$categoryid'");
    $DB->query("DELETE FROM " . TABLE_PREFIX . "pagesort   WHERE categoryid = '$categoryid'");

    // remove this categoryid from the usergroup rows
    $usergroups = $DB->query("SELECT usergroupid, categoryviewids, categorymenuids FROM " . TABLE_PREFIX . "usergroups");

    while($usergroup = $DB->fetch_array($usergroups))
    {
      // get the category view and menu view ids
      $categoryviewids = @explode(',', $usergroup['categoryviewids']);
      $categorymenuids = @explode(',', $usergroup['categorymenuids']);

      // search and if found then remove the deleted categoryid from the allow view column
      if(in_array($categoryid, $categoryviewids))
      {
        unset($categoryviewids[array_search($categoryid, $categoryviewids)]);
      }

      // search and if found then remove the deleted categoryid from the allow menu column
      if(in_array($categoryid, $categorymenuids))
      {
        unset($categorymenuids[array_search($categoryid, $categorymenuids)]);
      }

      // implode both arrays back to a string
      $newcategorymenuids = @implode(',', $categorymenuids);
      $newcategoryviewids = @implode(',', $categoryviewids);

      // now update the usergroup with the updated category values
      $DB->query("UPDATE " . TABLE_PREFIX . "usergroups SET categoryviewids = '$newcategoryviewids',
                                                            categorymenuids = '$newcategorymenuids'
                                                      WHERE usergroupid     = " . $usergroup['usergroupid']);
    }

    // delete subcategories of the category
    DeleteSubcategories($categoryid);

    echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';

    // redirect
    PrintRedirect('categories.php?action=displaycategories', 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 CATEGORIES ############################

if($action == 'updatecategories')
{
  $categoryids   = $_POST['categoryids'];
  $displayorders = $_POST['displayorders'];
  $parentids     = $_POST['categoryparentids'];
  $names         = $_POST['categorynames'];

  $categorycount = count($categoryids);

  // first lets make sure all the parentcategoryid's are setup correctly
  for($i = 0; $i < $categorycount; $i++)
  {
    if($categoryids[$i] != $parentids[$i])
    {
      // check and see if the parent selection is a child of this category (that will really mess things up!)
      if(!(AllowParent($categoryids[$i], $parentids[$i])))
      {
        $errors[] = '菜單 "' . $names[$i] . '" 不能設置為其子菜單的子菜單!';
      }
    }
    else
    {
      $errors[] = '菜單 "' . $names[$i] . '" 不能設置成自己的上級菜單!';
    }
  }

  if(count($errors) > 0)
  {
    // only update the display and category names
    for($i = 0; $i < $categorycount; $i++)
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "categories SET displayorder = '$displayorders[$i]',
                                                                    name = '$names[$i]'
                                                        WHERE categoryid = '$categoryids[$i]'");
    }

    $errors[] = '提示: 發生設置錯誤, 上級菜單已恢復.';

    PrintErrors($errors, '顯示順序及菜單名稱已更新, 上級菜單設置有錯誤:');
    DisplayCategories();
  }
  else
  {
    for($i = 0; $i < $categorycount; $i++)
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "categories SET displayorder = '$displayorders[$i]',
                                                                    name = '$names[$i]',
                                                                parentid = '$parentids[$i]'
                                                        WHERE categoryid = '$categoryids[$i]'");
    }

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



// ############################## INSERT CATEGORY ##############################

if($action == 'insertcategory')
{
  $name          = $_POST['name'];
  $parentid      = $_POST['parentid'];
  $displayonline = $_POST['displayonline'];
  $menuitem      = $_POST['menuitem'];

  // check for errors
  if(!strlen($name))
  {
    $errors[] = '請輸入菜單名稱!';
  }

  $urlname = 'Menu' . rand(100,999);

  if(!isset($errors))
  {
    // get default design id
    $template   = $DB->query_first("SELECT templateid FROM " . TABLE_PREFIX . "templates WHERE activated = '1'");
    $design = $DB->query_first("SELECT designid, maxmodules FROM " . TABLE_PREFIX . "designs WHERE templateid = '". $template['templateid'] ."' ORDER BY designid");

    // get the display order number for the new category
    $getcategoryrows = $DB->query("SELECT categoryid FROM " . TABLE_PREFIX . "categories");
    $categoryrows    = $DB->get_num_rows($getcategoryrows);
    $displayorder    = ++$categoryrows;

    // insert the new category
    $DB->query("INSERT INTO " . TABLE_PREFIX . "categories (parentid, designid, name, urlname, displayorder, menuwidth) VALUES ('$parentid', '" . $design['designid'] . "', '$name', '$urlname', '$displayorder', 82)");

    // get the auto increment number
    $categoryid = $DB->insert_id();

    // enter --empty-- module into pagesort for new category (this is a must, do not delete)
    for($i = 1; $i <= $design['maxmodules']; $i++)
    {
      $DB->query("INSERT INTO " . TABLE_PREFIX . "pagesort (categoryid, moduleid, displayorder)
                  VALUES ('$categoryid', 1, '$i')");
    }

    // update the usergroup categoryviewids
    if($displayonline == 1)
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "usergroups SET categoryviewids = CONCAT(categoryviewids, '," . $categoryid . "')");
    }

    // update the usergroup categorymenuids
    if($menuitem == 1)
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "usergroups SET categorymenuids = CONCAT(categorymenuids, '," . $categoryid . "')");
    }

    echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';
    PrintRedirect('mycategories.php?categoryid=' . $categoryid, 1);
  }
  else
  {
    PrintErrors($errors, '新建菜單錯誤');
    $action = 'createcategory';
  }
}



// ############################## CREATE CATEGORY ##############################

if($action == 'createcategory')
{
  PrintSection('新建菜單');
  echo '<form method="post" action="categories.php">
        <input type="hidden" name="action" value="insertcategory" />

        <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" size="25" name="name" /></td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">上級菜單</tc>
        </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(0, 1);

  echo '  </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="menuitem" checked value="1">&nbsp;&nbsp;&nbsp;否<input type="radio" name="menuitem" value="0"></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="displayonline" checked value="1">&nbsp;&nbsp;&nbsp;否<input type="radio" name="displayonline" value="0"></td>
        </tr>
        <tr>
          <td class="tdrow1" bgcolor="#FCFCFC" colspan="2" align="center">
            <input type="submit" value=" 提交保存 " />
          </td>
        </tr>
        </table>
        </form>';

  EndSection();
}



// ############################ DISPLAY CATEGORIES #############################

if($action == 'displaycategories')
{
  DisplayCategories();

  // lets see if any categories are lost
  $getallcategories = $DB->query("SELECT * FROM " . TABLE_PREFIX . "categories ORDER BY displayorder");

  if(count($listedcategories) != $DB->get_num_rows($getallcategories))
  {
    PrintSection('提示: 發現丟失的菜單!');
    echo '<form method="post" action="categories.php">
          <input type="hidden" name="action" value="fixlostcategories" />
          <table width="100%" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td class="tdrow2">丟失菜單的可能原因:<br />當設置菜單A的上級菜單為菜單B, 同時又設置菜單B的上級菜單為菜單A, 保存設置時將丟失菜單A和B.<br /><br />

              丟失的菜單列表: ';

    while($category = $DB->fetch_array($getallcategories))
    {
      if(!in_array($category['name'], $listedcategories))
      {
        echo $category['name'] . ' <input type="hidden" name="lostcategoryids[]" value="' . $category[categoryid] . '" />';
      }
    }

    echo '  </td>
          </tr>
          <tr>
            <td class="tdrow1" align="center"><input type="submit" value=" 找回菜單 " /></td>
          </table>
          </form>';
    EndSection();
  }
}



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

PrintFooter();

?>
