<?php
/*
  $Id: header_tags_controller.php,v 1.2 2004/08/07 22:50:52 hpdl Exp $
  header_tags_controller Originally Created by: Jack York
  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/
 
  require('includes/application_top.php');
  require_once('includes/functions/header_tags.php');
  require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_HEADER_TAGS_CONTROLLER);
 
  $filenameInc = DIR_FS_CATALOG . 'includes/header_tags.php';
  $filenameEng = DIR_FS_CATALOG . DIR_WS_LANGUAGES . $language . '/header_tags.php';

  if (GetPermissions(DIR_FS_CATALOG_IMAGES) != Getpermissions($filenameInc))
   $messageStack->add('htcontroller', "Permissions settings for the $filenameInc file appear to be incorrect. Change to " . Getpermissions(DIR_WS_IMAGES));
  if (GetPermissions(DIR_FS_CATALOG_IMAGES) != Getpermissions($filenameEng))
   $messageStack->add('htcontroller', "Permissions settings for the $filenameEng file appear to be incorrect. Change to " . Getpermissions(DIR_WS_IMAGES)); 
  
  $action       = (isset($_POST['action']) ? $_POST['action'] : '');
  $actionDelete = (isset($_POST['action_delete']) ? $_POST['action_delete'] : '');
  $actionCheck  = (isset($_POST['action_check']) ? $_POST['action_check'] : '');
  
  if (tep_not_null($action)) 
  {
    $args = array();
    $args['page'] = $_POST['page'];
    $args['title'] = addslashes($_POST['title']);
    $args['desc'] = addslashes($_POST['desc']);
    $args['keyword'] = addslashes($_POST['keyword']);
    $args['htta'] = (isset($_POST['htta']) && $_POST['htta'] == 'on') ? 1 : 0;
    $args['htda'] = (isset($_POST['htda']) && $_POST['htda'] == 'on') ? 1 : 0;
    $args['htka'] = (isset($_POST['htka']) && $_POST['htka'] == 'on') ? 1 : 0;
    $args['htca'] = (isset($_POST['htca']) && $_POST['htca'] == 'on') ? 1 : 0;    
    
    if (($pos = strpos($args['page'], ".php")) !== FALSE)  //remove .php from page 
       $args['page'] = substr($args['page'], 0, $pos);     //if present
   
    $fp = file($filenameEng);  
    $checkOnce = true;
    $lastSection = '';
    $insertPoint = 0;
    $markPoint = count($fp) - 1; 
    
    if (ValidPageName($args['page']) && NotDuplicatePage($fp, $args['page']))
    {
      /*********************** ENGLISH SECTION ************************/
      for ($idx = 0; $idx < count($fp); ++$idx)  //find where to insert the new page
      {     
         if ($checkOnce && strpos($fp[$idx], "// DEFINE TAGS FOR INDIVIDUAL PAGES") === FALSE)
            continue;
         
         $checkOnce = false;   
         $section = GetSectionName($fp[$idx]);   
         
         if (! empty($section))
         {
            if (strcasecmp($section, $args['page']) < 0)
            {         
               $lastSection = $section;    
               $markPoint = $idx;       
            }   
            else if (strcasecmp($section, $args['page']) > 0)
            {
               if ($insertPoint == 0)
                 $insertPoint = $idx;
            }      
         }
      }
      
      if ($insertPoint != count($fp))              //backup one line for appearance
        $insertPoint--;
         
      $fileUpper = ConvertDash(strtoupper($args['page']));      //prepare the english array
      $engArray = array();
      $engArray['page'] = sprintf("// %s.php\n", $args['page']);  
      $engArray['htta'] = sprintf("define('HTTA_%s_ON','%d');\n", $fileUpper, $args['htta']);
      $engArray['htda'] = sprintf("define('HTDA_%s_ON','%d');\n", $fileUpper, $args['htda']);
      $engArray['htka'] = sprintf("define('HTKA_%s_ON','%d');\n", $fileUpper, $args['htka']);
      $engArray['title'] = sprintf("define('HEAD_TITLE_TAG_%s','%s');\n", $fileUpper, $args['title']);
      $engArray['desc'] = sprintf("define('HEAD_DESC_TAG_%s','%s');\n", $fileUpper, $args['desc']);
      $engArray['keyword'] = sprintf("define('HEAD_KEY_TAG_%s','%s');\n", $fileUpper, $args['keyword']);
               
      array_splice($fp, $insertPoint, 0, $engArray);  
      WriteHeaderTagsFile($filenameEng, $fp);   
           
      /*********************** INCLUDES SECTION ************************/     
      $fp = file($filenameInc); 
      $checkOnce = true;
      $insertPoint = 0;
      $markPoint = count($fp) - 1;
      
      for ($idx = 0; $idx < count($fp); ++$idx)  //find where to insert the new page
      {     
         if ($checkOnce && strpos($fp[$idx], "switch (true)") === FALSE)
            continue;
         $checkOnce = false;   
         $section = GetSectionName($fp[$idx]);   
                 
         if (! empty($section))
         {
            if (strcasecmp($section, $args['page']) < 0)
            {         
               $lastSection = $section;    
               $markPoint = $idx;       
            }   
            else if (strcasecmp($section, $args['page']) > 0)
            {
               if ($insertPoint == 0)
                 $insertPoint = $idx;
            }                  
         }
         else if (strpos($fp[$idx], "// ALL OTHER PAGES NOT DEFINED ABOVE") !== FALSE)
         { 
            $insertPoint = $idx;
            break;
         }    
      }
  
      if ($insertPoint != count($fp))              //backup one line for appearance
        $insertPoint--;      

      $incArray = array();
      $fileUpper = ConvertDash(strtoupper($args['page']));
      $spaces = 10;
      $incArray['page'] = sprintf("\n// %s.php\n", $args['page']);  
      $incArray['case'] = sprintf("  case (strstr(\$_SERVER['PHP_SELF'], FILENAME_%s));\n",$fileUpper, $fileUpper);
      $incArray['line'] = sprintf("    \$tags_array = tep_header_tag_page(HTTA_%s_ON, HEAD_TITLE_TAG_%s, \n%38sHTDA_%s_ON, HEAD_DESC_TAG_%s, \n%38sHTKA_%s_ON, HEAD_KEY_TAG_%s );\n   break;\n",$fileUpper, $fileUpper, " ", $fileUpper, $fileUpper, " ", $fileUpper, $fileUpper );  
   
      array_splice($fp, $insertPoint, 0, $incArray);  
      WriteHeaderTagsFile($filenameInc, $fp);   
    } 
    else
    {
      if (! ValidPageName($args['page']))
        $error = HEADING_TITLE_CONTROLLER_PAGENAME_INVALID_ERROR  . $args['page'];
      else
        $error = HEADING_TITLE_CONTROLLER_PAGENAME_ERROR . $args['page'];
      $messageStack->add('htcontroller', $error);
    }
  } 
  else if (tep_not_null($actionDelete))
  {
     /******************** Delete the English entries ********************/
     $page_to_delete = $_POST['delete_page'].'.php';
     $nodelete_pages = array(0 => 'index.php', 
                             1 => 'product_info.php', 
                             2 => 'product_reviews_info.php', 
                             3 => 'products_new.php',
                             4 => 'specials.php');
     $fp = file($filenameEng);
     $found = false; 
     $delStart = 0;
     $delStop = 0;
     for ($idx = 0; $idx < count($fp); ++$idx)
     {
        if (! $found && strpos($fp[$idx], $page_to_delete) !== FALSE)
        {
            $delStart = $idx;   //adjust for 0 start
            $found = true;
        }
        else if ($found && (tep_not_null($fp[$idx]) && strpos($fp[$idx], ".php") === FALSE))
            $delStop++;
        else if ($found && (! tep_not_null($fp[$idx]) || strpos($fp[$idx], ".php") !== FALSE))
        {
            $delStop++;
            break;
        }    
     }

     if ($found == true)          //page entry may not be present
     {
        if (in_array($page_to_delete, $nodelete_pages)) 
        {
          $error = sprintf(HEADING_TITLE_CONTROLLER_NO_DELETE_ERROR, $page_to_delete);
          $messageStack->add('htcontroller', $error);
        }
        else
        {
          array_splice($fp, $delStart, $delStop);
          WriteHeaderTagsFile($filenameEng, $fp);
        }  
     } 
     
     /******************** Delete the includes entries *******************/
     $fp = file($filenameInc);
     $checkOnce = true;
     $found = false; 
     $delStart = 0;
     $delStop = 0;
     
     for ($idx = 0; $idx < count($fp); ++$idx)
     {
        if ($checkOnce && strpos($fp[$idx], "switch") === FALSE)
           continue;
        
        $checkOnce = false;
        if (! $found && (strpos($fp[$idx], $page_to_delete) !== FALSE || strpos($fp[$idx], strtoupper($page_to_delete))) !== FALSE)
        {
            $delStart = $idx; // + 1;  //adjust for 0 start
            $found = true;
        }
        else if ($found && ( strpos($fp[$idx], "ALL OTHER PAGES NOT DEFINED ABOVE") === FALSE && strpos($fp[$idx], ".php") === FALSE))
        {
           $delStop++;
        }   
        else if ($found && (strpos($fp[$idx], "ALL OTHER PAGES NOT DEFINED ABOVE") !== FALSE  || strpos($fp[$idx], ".php") !== FALSE))
        {
           $delStop++; 
           break;
        }                  
     }     
     
     if ($found == true)          //page entry may not be present
     {
        if (in_array($page_to_delete, $nodelete_pages))     
        {
          $error = sprintf(HEADING_TITLE_CONTROLLER_NO_DELETE_ERROR, $page_to_delete);
          $messageStack->add('htcontroller', $error);
        }
        else
        {
          array_splice($fp, $delStart, $delStop);
          WriteHeaderTagsFile($filenameInc, $fp);
        }  
     }   
  }
  else if (tep_not_null($actionCheck)) 
  {
     $filelist = array();
     $newfiles = array();
     $fp = file($filenameEng);
  
     for ($idx = 0; $idx < count($fp); ++$idx) 
     {
        $section = GetSectionName($fp[$idx]);
        if (empty($section) || strpos($section, "header_tags") !== FALSE)
           continue;
        $section .= '.php';
        $section = str_replace("-", "_", $section);  //ensure the scoring is the same
        $filelist[] = $section;
     }
 
     if ($handle = opendir(DIR_FS_CATALOG)) 
     {
        $fp = file($filenameEng); 
        $found = false;
        while (false !== ($file = readdir($handle))) 
        { 
           if (strpos($file, '.php') === FALSE)
              continue;       
 
           if (FileNotUsingHeaderTags($file))
           {
              foreach($filelist as $name) 
              {           
                 $tmp_file = str_replace("-", "_", $file);  //ensure the scoring is the same
                 if (strcasecmp($name, $tmp_file) === 0)
                 {
                    $found = true;
                    break;
                 }
              }   
              if (! $found)
                 $newfiles[] = array('id' => $file, 'text' => $file);
              else
                 $found = false;
           }
        }
        closedir($handle); 
     }
  }
  
  // added to sort the non header tags file list for the dropdown alphabetically
  foreach ($newfiles as $fkey => $row) {
    $id[$fkey]  = $row['id'];
    $text[$fkey] = $row['text'];
  }
  $array_lowercase = array_map('strtolower', $text);
  array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $newfiles);
  
  $deleteArray = array();
  $fp = file($filenameEng);
  $checkOnce = true;
  for ($idx = 0; $idx < count($fp); ++$idx)
  {
     if ($checkOnce && strpos($fp[$idx], "// DEFINE TAGS FOR INDIVIDUAL PAGES") === FALSE)
        continue;
     $checkOnce = false;
     $l = GetSectionName($fp[$idx]);
     if (tep_not_null($l))
       $deleteArray[] = array('id' => $l, 'text' => $l);
  }

include(DIR_WS_INCLUDES . 'html_top.php');
include(DIR_WS_INCLUDES . 'header.php');
include(DIR_WS_INCLUDES . 'column_left.php');
?>
<div id="content" class="content p-relative">         
  <h1 class="page-header"><i class="fa fa-laptop"></i> <?php echo HEADING_TITLE_CONTROLLER; ?></h1>

  <?php if (file_exists(DIR_WS_INCLUDES . 'toolbar.php')) include(DIR_WS_INCLUDES . 'toolbar.php'); ?>
  
  <div class="col">   
    <!-- begin button bar --> 
    <div id="button-bar" class="row">
      <div class="col-9 m-b-10 w-100 pt-1 pl-0 pr-0"> 
        <button type="button" onclick="updateTags();" class="btn btn-primary m-r-3"><i class="fa fa-plus"></i> <?php echo IMAGE_UPDATE; ?></button>
      </div>
      <div class="col-3 m-b-10 pt-1 pr-2">
      </div>
    </div>
    <!-- end button bar -->    
    <?php
    if ($messageStack->size('htcontroller') > 0) {
      echo $messageStack->output('htcontroller'); 
    }
    ?>    
    <!-- begin panel -->
    <div class="dark">
      <!-- body_text //-->     
      <div id="table-headertagscontroller" class="table-headertagscontroller">
        <div class="row">
          <div class="col-md-12 col-xl-12 dark panel-left rounded">

			      <div class="sidebar-title mt-2">
              <div class="row">
                <div class="col p-0 mt-3 ml-2 mr-2">
                  <div class="note note-warning m-0">
                    <p class="mb-0 mt-0 f-w-400"><?php echo TEXT_PAGE_TAGS; ?></p>
                  </div>
                </div>
              </div>
            </div>
			      <hr>
            <div class="sidebar-title mt-2">
              <div class="row">
                <div class="col p-0 mt-0 ml-2 mr-2">
                  <div class="note note-info m-0">
                    <p class="mb-0 mt-0 f-w-400"><?php echo TEXT_INFORMATION_ADD_PAGE; ?></p>
                  </div>
                </div>
              </div>
            </div>

            <table border="0" width="100%" cellspacing="0" cellpadding="2">
    		      <?php echo tep_draw_form('header_tags', FILENAME_HEADER_TAGS_CONTROLLER, '', 'post') . tep_draw_hidden_field('action', 'process'); ?></td>
              <tr>
                <td><table border="0" width="100%">
                  <tr>
                    <td width="10%" style="font-weight: bold;"><label class="control-label sidebar-edit mb-0"><?php echo HEADING_TITLE_CONTROLLER_PAGENAME; ?></label></td>
                    <td><?php echo tep_draw_input_field('page', tep_not_null($page) ? $page : '', 'class="form-control" maxlength="255", size="30"', false); ?> </td>
                  <tr>             
                </table></td>
              </tr>
         
              <tr>
                <td><table border="0" width="100%">
                  <tr>
                    <td><label class="control-label sidebar-edit mb-0">Switches:</label></td>
                    <td class="sidebar-title">HTTA: </td>
                    <td align="left"><?php echo tep_draw_checkbox_field('htta', '', FALSE, '', 'class="js-switch"'); ?> </td>
                    <td class="sidebar-title">HTDA: </td>
                    <td><?php echo tep_draw_checkbox_field('htda', '', FALSE, '', 'class="js-switch"'); ?> </td>
                    <td class="sidebar-title">HTKA: </td>
                    <td><?php echo tep_draw_checkbox_field('htka', '', FALSE, '', 'class="js-switch"'); ?> </td>
                    <td class="sidebar-title">HTCA: </td>
                    <td><?php echo tep_draw_checkbox_field('htca', '', FALSE, '', 'class="js-switch"'); ?> </td>
                    <td width="50%"> <a href="#modal-explain" class="btn btn-sm btn-info" data-toggle="modal"><?php echo HEADING_TITLE_CONTROLLER_EXPLAIN; ?></a></td>
                  </tr>
                </table></td>
              </tr>
         
              <tr>
                <td><table border="0" width="100%">
                  <tr>
                    <td width="10%"><label class="control-label sidebar-edit mb-0"><?php echo HEADING_TITLE_CONTROLLER_TITLE; ?></label></td>
                    <td><?php echo tep_draw_input_field('title', tep_not_null($title) ? $title : '', 'class="form-control mb-1" maxlength="255", size="60"', false); ?> </td>
                  </tr> 
                  <tr>
                    <td width="10%"><label class="control-label sidebar-edit mb-0"><?php echo HEADING_TITLE_CONTROLLER_DESCRIPTION; ?></label></td>
                    <td ><?php echo tep_draw_input_field('desc', tep_not_null($desc) ? $desc : '', 'class="form-control mb-1" maxlength="255", size="60"', false); ?> </td>
                  </tr> 
                  <tr>
                    <td width="10%"><label class="control-label sidebar-edit mb-0"><?php echo HEADING_TITLE_CONTROLLER_KEYWORDS; ?></label></td>
                    <td ><?php echo tep_draw_input_field('keyword', tep_not_null($key) ? $key : '', 'class="form-control mb-1" maxlength="255", size="60"', false); ?> </td>
                  </tr>
                </table></td>
              </tr>
         
              <tr> 
                <td align="right"><button class="btn btn-success btn-sm mt-3" type="submit"><?php echo IMAGE_UPDATE; ?></button></td>
              </tr>
             
              <tr><hr></tr>
              </form>
            </table>
        
            <div class="sidebar-title mt-2">
              <div class="row">
                <div class="col p-0 mt-0 ml-2 mr-2">
                  <div class="note note-info m-0">
                    <p class="mb-0 mt-0 f-w-400"><?php echo TEXT_INFORMATION_DELETE_PAGE; ?></p>
                  </div>
                </div>
              </div>
            </div>          
   
            <div>
              <?php echo tep_draw_form('header_tags_delete', FILENAME_HEADER_TAGS_CONTROLLER, '', 'post') . tep_draw_hidden_field('action_delete', 'process'); ?></td>
              <table border="0" width="100%" cellspacing="0" cellpadding="2">
                <tr>
                  <td><table border="0" width="100%">
                    <tr>
                      <td width="10%"><label class="control-label sidebar-edit mb-0"><?php echo HEADING_TITLE_CONTROLLER_PAGENAME; ?></label></td>
                      <td align="left"><?php   echo tep_draw_pull_down_menu('delete_page', $deleteArray, '', '', false);?></td>
                    </tr>             
                  </table></td>
                </tr>        
                <tr> 
                  <td align="right"><button class="btn btn-success btn-sm mt-3" type="submit"><?php echo IMAGE_UPDATE; ?></button></td>
                </tr>       
              </table>
              </form>
            </div>
            <hr>

            <div class="sidebar-title mt-2">
              <div class="row">
                <div class="col p-0 mt-0 ml-2 mr-2">
                  <div class="note note-info m-0">
                    <p class="mb-0 mt-0 f-w-400"><?php echo TEXT_INFORMATION_CHECK_PAGES; ?></p>
                  </div>
                </div>
              </div>
            </div> 

            <div>
              <?php echo tep_draw_form('header_tags_auto', FILENAME_HEADER_TAGS_CONTROLLER, '', 'post') . tep_draw_hidden_field('action_check', 'process'); ?></td>
              <table border="0" width="100%" cellspacing="0" cellpadding="2">
                <tr>
                  <td><table border="0" width="100%">
                   <tr>
                    <td width="10%"><label class="control-label sidebar-edit mb-0"><?php echo HEADING_TITLE_CONTROLLER_PAGENAME; ?></label></td>
                    <td align="left"><?php   echo tep_draw_pull_down_menu('new_files', $newfiles, '', '', false);?></td>
                   </tr>             
                  </table></td>
                </tr>            
                <tr> 
                  <td align="right"><button class="btn btn-success btn-sm mt-3" type="submit"><?php echo IMAGE_UPDATE; ?></button></td>
                </tr>       
                <tr><td><hr></td></tr>      
              </table>
              </form>
            </div>
    
          </div>
        </div>
      </div>
      <!-- end body_text //-->
    </div>
    <!-- end panel -->
  </div>
</div>
<!-- body_eof //-->
<!-- #modal-dialog -->
<div class="modal fade" id="modal-explain">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title">What are HTTA, HTDA, HTKA and HTCA used for?</h4>
        <button type="button" class="close modal-close-fix" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>        
			</div>
			<div class="modal-body">
				<?php include_once(DIR_WS_LANGUAGES . $language . '/header_tags_popup_help.php'); ?>
			</div>
			<div class="modal-footer">
				<a href="javascript:;" class="btn btn-sm btn-default" data-dismiss="modal">Close</a>
			</div>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){

  //  instantiate checkbox switches
  var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
  elems.forEach(function(html) {
    var switchery = new Switchery(html, { size: 'small', 
                                          color: '#ff4044',
                                          secondaryColor: '#a8acb1' });
  }); 
}); 

function updateTags() {
  document.forms["header_tags"].submit();
}

// sticky menu bar
$(function () {
  var y = 60;
  $(window).on('scroll', function () {
    if (y <= $(window).scrollTop()) {
      // if so, add the fixed class
      $('#button-bar').addClass('button-bar-fixed');
    } else {
      // otherwise remove it
      $('#button-bar').removeClass('button-bar-fixed');
    }
  })
});   
</script>
<?php
include(DIR_WS_INCLUDES . 'html_bottom.php');
require(DIR_WS_INCLUDES . 'application_bottom.php');
?>
