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

?>