<?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 the value of $action
$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : 'displaytemplates');

echo '<script type="text/javascript" language="Javascript">
      <!--
      function ConfirmDelete()
      {
        if(confirm("确定要删除此模板吗?"))
          return true;
        else
          return false;
      }
      //-->
      </script>';



// ############################### INSTALL TEMPLATE ################################

if($action == 'installtemplate')
{
  $installpath = $_POST['installpath'];

  include($installpath);

  // install the template
  $DB->query("INSERT INTO " . TABLE_PREFIX . "templates (name, activated, numdesigns, previewimage, authorname, authorlink)
              VALUES ('$templatename', '0', '$numdesigns', '$previewimage', '$authorname', '$authorlink')");

  // get the template's id that was give to the template
  $templateid = $DB->insert_id();

  // install the templates designs
  for($i = 0; $i < $numdesigns; $i++)
  {
    $DB->query("INSERT INTO " . TABLE_PREFIX . "designs (templateid, maxmodules, designpath, imagepath)
                VALUES ('$templateid','$maxmodules[$i]','$designpath[$i]','$imagepath[$i]')");
  }

  PrintRedirect('templates.php', 1);
}



// ############################## UNINSTALL TEMPLATE ###############################

if($action == 'uninstalltemplate')
{
  $templateid = $_GET['templateid'];

  // make sure not to delete current template
  if(!$currenttemplate = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "templates WHERE templateid = '$templateid' AND activated = '1'"))
  {
    $DB->query("DELETE FROM " . TABLE_PREFIX . "templates   WHERE templateid = '$templateid'");
    $DB->query("DELETE FROM " . TABLE_PREFIX . "designs WHERE templateid = '$templateid'");
  }

  PrintRedirect('templates.php', 1);
}



// ################################ CHANGE TEMPLATE ################################

if($action == 'changetemplate')
{
  $templateid = $_POST['templateid'];
  $savemodulepositions = isset($_POST['savemodulepositions']) ? 1 : 0;

  // update each category with the templates new design
  $numdesigns = $DB->query_first("SELECT numdesigns FROM " . TABLE_PREFIX . "templates WHERE templateid = '$templateid'");
  $designsdefault = $DB->query_first("SELECT templateid FROM " . TABLE_PREFIX . "templates WHERE activated = 1");
  $firstdesignid = $DB->query_first("SELECT designid, maxmodules FROM " . TABLE_PREFIX . "designs WHERE templateid = '$templateid' ORDER BY designid");
  $firstdesigndefaultid = $DB->query_first("SELECT designid FROM " . TABLE_PREFIX . "designs WHERE templateid = '".$designsdefault['templateid']."' ORDER BY designid");
  
  $getcategories = $DB->query("SELECT categoryid, designid FROM " . TABLE_PREFIX . "categories ORDER BY categoryid");
  
  while($setdesignid = $DB->fetch_array($getcategories))
  {
    $interval = $setdesignid['designid'] - $firstdesigndefaultid['designid'];
	if($interval<$numdesigns['numdesigns'])
	{
	    $currentdesignid = $firstdesignid['designid'] + $interval;

	}
	else
	{
	    $currentdesignid = $firstdesignid['designid'] + $numdesigns['numdesigns']-1;
	}
	$DB->query("UPDATE " . TABLE_PREFIX . "categories SET designid = '$currentdesignid' WHERE categoryid = '".$setdesignid['categoryid']."'");
  }

  // save the list of old module positions in case the user has enabled 'save module positions'
  $getmodulepositions = $DB->query("SELECT * FROM " . TABLE_PREFIX . "pagesort ORDER BY displayorder");

  while($moduleposition = $DB->fetch_array($getmodulepositions))
  {
    $modulepositions[$moduleposition['categoryid']][$moduleposition['displayorder']] = $moduleposition['moduleid'];
  }

  // delete pagesort
  $DB->query("DELETE FROM " . TABLE_PREFIX . "pagesort");

  // insert the new module positions
  $getcategories = $DB->query("SELECT categoryid FROM " . TABLE_PREFIX . "categories");

  while($category = $DB->fetch_array($getcategories))
  {
    for($i = 0; $i < $firstdesignid['maxmodules']; $i++)
    {
      $displayorder = $i + 1;

      if($savemodulepositions)
      {
        $moduleid = isset($modulepositions[$category['categoryid']][$displayorder]) ? $modulepositions[$category['categoryid']][$displayorder] : 1;
      }
      else
      {
        $moduleid = 1;
      }

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

  // change templates
  $DB->query("UPDATE " . TABLE_PREFIX . "templates SET activated = '0' WHERE activated = '1'");
  $DB->query("UPDATE " . TABLE_PREFIX . "templates SET activated = '1' WHERE templateid = $templateid");

  PrintRedirect('templates.php', 1);
}



// ############################# DISPLAY NEW TEMPLATES #############################

function DisplayNewTemplates($dirname)
{
  global $DB;
  static $availabletemplates = 0;

  $d = dir($dirname);

  while($entry = $d->read())
  {
    if($entry != "." && $entry != "..")
    {
      if(is_dir($dirname . '/' . $entry))
      {
        DisplayNewTemplates($dirname . '/' . $entry);
      }
      else if( ($entry == 'install.php') AND (substr_count($dirname, '/') == 2) )
      {
        $installpath = $dirname . '/install.php';

        include($installpath);

        // check to see if module has already been installed
        $gettemplate  = $DB->query("SELECT templateid FROM " . TABLE_PREFIX . "templates WHERE name = '$templatename'");
        $templaterows = $DB->get_num_rows($gettemplate);

        if($templaterows == 0)
        {
          $availabletemplates++;

          echo '<tr>
                  <td class="tdrow1" colspan="2">'.$templatename.'</td>
                </tr>
                <tr>
                  <td class="tdrow2" width="70%">
                    <form method="post" action="templates.php?action=installtemplate">

                    <table width="400" border="0" cellpadding="5" cellspacing="0">
                    <tr><td width="200">模板名称:</td><td>'.$templatename.'</td></tr>
                    <tr><td width="200">设计数量:</td><td>'.$numdesigns.'</td></tr>
                    <tr><td width="200">&nbsp;</td><td>&nbsp;</td></tr>
                    <tr><td width="200">作者:</td>';

          if($authorlink)
          {
            echo '<td>'.$authorname.'</td></tr>';
          }

          echo '<tr><td>&nbsp;</td><td>&nbsp;</td></tr>
                <tr>
                  <td colspan="2">
                    <input type="hidden" name="installpath" value="'.$installpath.'" />
                    <input type="submit" name="installtemplate" value="安装模板 '.$templatename.'" />
                  </td>
                </tr>
                </table>

                </form>

                </td>
                <td class="tdrow3" valign="top" align="center">
                  <img src="../templates/'.$previewimage.'" />
                </td>
              </tr>';
        }
      }
      else if($entry == 'install.php' AND ( $dirname != '../modules' AND (substr_count($dirname, '/') > 2) ))
      {
        // the install folder was uploaded to the wrong spot,
        // lets give some information on this error

        $availabletemplates++;

        // find the real template folder name
        $folders = explode('/', $dirname);
        $template_folder_name = $folders[(count($folders) - 1)];

        echo '<tr>
                <td class="tdrow1" colspan="2">上传模板错误</td>
              </tr>
              <tr>
                <td class="tdrow2" colspan="2">
                  上传模板错误.<br /><br />
                  已上传模板至文件夹: ' . substr($dirname, 2) . '/<br /><br />
                  模板文件夹应上传至: /templates/' . $template_folder_name . '/<br /><br />
                </td>
              </tr>';
      }
    }
  } // end while

  return $availabletemplates;
}



// ############################### SWITCH TEMPLATES ################################

if($action == 'switchtemplate')
{
  $templateid = $_GET['templateid'];

  $template = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "templates WHERE templateid = $templateid");

  PrintSection('切换模板');
  echo '<form method="POST" action="templates.php">
        <input type="hidden" name="action" value="changetemplate" />
        <input type="hidden" name="templateid" value="' . $template['templateid'] . '" />

        <table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow1" colspan="2">切换至: ' . $template['name'] . '</td>
        </tr>
        <tr>
          <td class="tdrow2" width="70%" valign="top">
            <input type="checkbox" name="savemodulepositions" value="1" checked /> <b>保存模块位置</b><br />
            保存模块位置选项使得在切换模板后保持当前模板中所有模块位置不变，否则您需要重新设置各模块的位置.<br /><br />

            <b>提示:</b> 不选此项需要为新模板重新设置各模块位置!<br /><br /><br />

             <input type="submit" value="切换到此模板" />
          </td>
          <td class="tdrow3" align="center">
            <img alt="模板: ' . $template['name'] . '" src="../templates/' . $template['previewimage'] . '" />
          </td>
        </tr>
        </table>

        </form>';
  EndSection();
}



// ############################### DISPLAY TEMPLATES ###############################

if($action == 'displaytemplates')
{
  // display the install a template form
  PrintSection('安装模板');
  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">';

  if(!DisplayNewTemplates('../templates'))
  {
    echo '<tr>
            <td class="tdrow1" colspan="2">暂无可安装的模板，请先将需要安装的模板文件夹上传到网站根目录下的"templates/"目录!</td>
          </tr>
          <tr>
            <td class="tdrow2" width="70%" valign="top">
              所有模板已安装在您的企业网站系统中.
              </td>
          </tr>';
  }

  echo '</table>';
  EndSection();

  // configure and use a template display
  PrintSection("切换模板");

  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">';

  $gettemplates = $DB->query("SELECT * FROM " . TABLE_PREFIX . "templates ORDER BY templateid ASC");
  $templaterows = $DB->get_num_rows($gettemplates);

  for($i = 0; $i < $templaterows; $i++)
  {
    $template = $DB->fetch_array($gettemplates);

    if(!$template['activated'])
    {
      $uninstall[] = '<br /><br /><a href="templates.php?action=uninstalltemplate&templateid='.$template['templateid'].'" onClick="return ConfirmDelete()">删除模板</a>';
    }
    else
    {
      $uninstall[] = '<br /><br />当前模板';
    }

    $templateid[]      = $template['templateid'];
    $templatename[]    = $template['name'] . ' (作者: ' . $template['authorname'].')';
    $templatepreview[] = $template['previewimage'];
  }

  for($i = 0; $i < $templaterows; $i++)
  {
    echo '<tr>
            <td class="tdrow1" align="center">'.$templatename[$i].'</td>
            <td class="tdrow1" align="center">'.iif($i+1 != $templaterows, $templatename[$i+1], '&nbsp;').'</td>
          </tr>
          <tr>
            <td style="padding-bottom: 25px;" class="tdrow2" width="50%" valign="top" align="center"><a href="templates.php?action=switchtemplate&templateid='.$templateid[$i].'"><img alt="点击切换到此模板" src="../templates/'.$templatepreview[$i].'" /></a>'.$uninstall[$i].'</td>
            <td style="padding-bottom: 25px;" class="tdrow3" width="50%" valign="top" align="center">'.iif($i+1 != $templaterows, '<a href="templates.php?action=switchtemplate&templateid='.$templateid[$i+1].'"><img alt="点击切换到此模板" src="../templates/'.$templatepreview[$i+1].'" /></a>'.$uninstall[$i+1], '&nbsp').'</td>
          </tr>';

    $i++;
  }

  echo '</table>';

  EndSection();
}



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

PrintFooter();

?>