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

?>
