<?php
/*
  Id: modules.php,v 6.5.4 2017/12/17 01:41:11 datazen Exp $

  CRE Loaded, Open Source E-Commerce Solutions
  http://www.loadedcommerce.com

  Copyright (c) 2017 Loaded Commerce
  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/
define('FILENAME_AUTHORIZENET_HELP', 'authnet_help.php');
require('includes/application_top.php');

// RCI for global and individual top
echo $cre_RCI->get('global', 'top', false);
echo $cre_RCI->get('modules', 'top', false);

$set = (isset($_GET['set']) && trim($_GET['set']) != '') ? $_GET['set'] : 'payment';
if (tep_not_null($set)) {
  switch ($set) {
    case 'shipping':
      $module_type = 'shipping';
      $module_directory = DIR_FS_CATALOG_MODULES . 'shipping/';
      if(isset($_GET['mod_path']) && $_GET['mod_path'] != 'gen' && $_GET['mod_path'] != '') {
		$arr_path = explode('_', $_GET['mod_path']);
		$module_directory = DIR_FS_CATALOG.'addons/lc_'.$arr_path[1].'/catalog/includes/modules/shipping/';
      }
      $module_key = 'MODULE_SHIPPING_INSTALLED';
      $heading_title = HEADING_TITLE_MODULES_SHIPPING;
      $SSL= 'NONSSL';
      break;
    case 'ordertotal':
      $module_type = 'order_total';
      $module_directory = DIR_FS_CATALOG_MODULES . 'order_total/';
      if(isset($_GET['mod_path']) && $_GET['mod_path'] != 'gen' && $_GET['mod_path'] != '') {
		$arr_path = explode('_', $_GET['mod_path']);
		$module_directory = DIR_FS_CATALOG.'addons/lc_'.$arr_path[1].'/catalog/includes/modules/order_total/';
      }
      $module_key = 'MODULE_ORDER_TOTAL_INSTALLED';
      $heading_title = HEADING_TITLE_MODULES_ORDER_TOTAL;
      $SSL= 'NONSSL';
      break;
    case 'checkout_success':
      $module_type = 'checkout_success';
      $module_directory = DIR_FS_CATALOG_MODULES . 'checkout_success/';
      if(isset($_GET['mod_path']) && $_GET['mod_path'] != 'gen' && $_GET['mod_path'] != '') {
		$arr_path = explode('_', $_GET['mod_path']);
		$module_directory = DIR_FS_CATALOG.'addons/lc_'.$arr_path[1].'/catalog/includes/modules/checkout_success/';
      }
      $module_key = 'MODULE_CHECKOUT_SUCCESS_INSTALLED';
      $heading_title = HEADING_TITLE_MODULES_CHECKOUT_SUCCESS;
      $SSL= 'NONSSL';
      break;
    case 'addons':
      $module_type = 'addons';
      $module_directory = DIR_FS_CATALOG_MODULES . 'addons/';
      if(isset($_GET['mod_path']) && $_GET['mod_path'] != 'gen' && $_GET['mod_path'] != '') {
		$arr_path = explode('_', $_GET['mod_path']);
		$module_directory = DIR_FS_CATALOG.'addons/lc_'.$arr_path[1].'/catalog/includes/modules/addons/';
      }
      $module_key = 'MODULE_ADDONS_INSTALLED';
      $heading_title = HEADING_TITLE_MODULES_ADDONS;
      $SSL= 'NONSSL';
      break;
    case 'payment':
      $module_type = 'payment';
      $module_directory = DIR_FS_CATALOG_MODULES . 'payment/';
      if(isset($_GET['mod_path']) && $_GET['mod_path'] != 'gen' && $_GET['mod_path'] != '') {
		$arr_path = explode('_', $_GET['mod_path']);
		$module_directory = DIR_FS_CATALOG.'addons/lc_'.$arr_path[1].'/catalog/includes/modules/payment/';
      }
      $module_key = 'MODULE_PAYMENT_INSTALLED';
      $heading_title = HEADING_TITLE_MODULES_PAYMENT;
      $SSL= 'SSL';
      break;
    default:
      $cre_RCI->get('modules', 'set');
      if ($module_type == '') {
        $module_type = 'payment';
        $module_directory = DIR_FS_CATALOG_MODULES . 'payment/';
        $module_key = 'MODULE_PAYMENT_INSTALLED';
        $heading_title = HEADING_TITLE_MODULES_PAYMENT;
        $SSL= 'SSL';
      }
      break;
  }
}
$action = (isset($_GET['action']) ? $_GET['action'] : '');
if (tep_not_null($action)) {
  switch ($action) {
    case 'save':
	  foreach($_POST['configuration'] as $key => $value) {
        if( is_array( $value ) ){
          $value = implode( ", ", $value);
          $value = preg_replace ("/, --none--/", "", $value);
        }
        tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '" . tep_db_real_escape_string($value) . "' where configuration_key = '" . $key . "'");
      }
      $cre_RCI->get('modules', 'action');
      tep_redirect(tep_href_link(FILENAME_MODULES, 'set=' . $set . '&module=' . $_GET['module'], $SSL));
      break;
    case 'install':
      $file_extension = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], '.'));
      $class = basename($_GET['module']);
      if (file_exists($module_directory . $class . $file_extension)) {
        include($module_directory . $class . $file_extension);
        $module = new $class;
        $module->install();
      }
      $cre_RCI->get('modules', 'action');
      tep_redirect(tep_href_link(FILENAME_MODULES, 'set=' . $set . '&module=' . $class, $SSL));
      break;
    case 'remove':
      $file_extension = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], '.'));
      $class = basename($_GET['module']);
      if (file_exists($module_directory . $class . $file_extension)) {
        include($module_directory . $class . $file_extension);
        $module = new $class;
        $module->remove();
      }
      $cre_RCI->get('modules', 'action');
      tep_redirect(tep_href_link(FILENAME_MODULES, 'set=' . $set . '&module=' . $class, $SSL));
      break;
    case 'sync':
      $file_extension = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], '.'));
      $class = basename($_GET['module']);
      if (file_exists($module_directory . $class . $file_extension)) {
        include($module_directory . $class . $file_extension);
        $module = new $class;
        $module->sync_permalink();
      }
      $cre_RCI->get('modules', 'action');
      tep_redirect(tep_href_link(FILENAME_MODULES, 'set=' . $set . '&module=' . $class, $SSL));
      break;
    default:
      // RCI call added incase there is an action needed for a called module
      $cre_RCI->get('modules', 'action');
  }
}
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; ?></h1>

  <?php if (file_exists(DIR_WS_INCLUDES . 'toolbar.php')) include(DIR_WS_INCLUDES . 'toolbar.php'); ?>

  <div class="col">
    <?php
    if ($messageStack->size('modules') > 0) {
      echo $messageStack->output('modules');
    }
    ?>
    <!-- begin panel -->
    <div class="dark">
      <!-- body_text //-->
      <div id="table-modules" class="table-modules">
        <div class="row">
          <div class="col-md-9 col-xl-10 dark panel-left rounded-left">
            <table class="table table-hover w-100 mt-2">
              <thead>
              <tr class="th-row">
                <?php
                if ($module_type == 'payment') {
                  echo '<th scope="col" class="th-col dark text-left">PCI</th>';
                }
                ?>
                <th scope="col" class="th-col dark text-left"><?php echo TABLE_HEADING_MODULES; ?></th>
                <?php
                if ($set == 'addons') {
                  echo '<th scope="col" class="th-col dark text-center">' . "\n";
                  echo TABLE_HEADING_INSTALLED;
                } else {
                  echo '<th scope="col" class="th-col dark text-right">' . "\n";
                  echo TABLE_HEADING_SORT_ORDER;
                }
                ?>
                </th>
                <th scope="col" class="th-col dark text-right"><?php echo TABLE_HEADING_ACTION; ?></th>
              </tr>
              </thead>
              <tbody class="row_module_position">
              <?php
              $file_extension = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], '.'));
              $directory_array = array();
              if ($dir = @dir($module_directory)) {
                while ($file = $dir->read()) {
                  if (!is_dir($module_directory . $file)) {
                    if (substr($file, strrpos($file, '.')) == $file_extension) {
                      $directory_array[] = $file;
                    }
                  }
                }
                sort($directory_array);
                $dir->close();
              }
              $modules_wkey = array();  // this array used the file name as the key and the data as the sort order
              $modules_nokey = array();  // standard array

              // custom sort added for payment listing
              $new = '';
              foreach($directory_array as $value) {
                if (substr($value,0,6) == 'loaded') $new .= $value . ',';
              }
              reset($directory_array);
              foreach($directory_array as $value) {
                if (substr($value,0,4) == 'pm2c') $new .= $value . ',';
              }
              reset($directory_array);
              foreach($directory_array as $value) {
                if (substr($value,0,3) == 'cre') $new .= $value . ',';
              }
              reset($directory_array);
              foreach($directory_array as $value) {
                if (substr($value,0,6) == 'paypal') $new .= $value . ',';
              }
              reset($directory_array);
              foreach($directory_array as $value) {
                if (substr($value,0,8) == 'worldpay') $new .= $value . ',';
              }
              reset($directory_array);
              foreach($directory_array as $value) {
                if ((substr($value,0,3) != 'cre') &&
                    (substr($value,0,6) != 'paypal') &&
                    (substr($value,0,6) != 'loaded') &&
                    (substr($value,0,4) != 'pm2c') &&
                    (substr($value,0,8) != 'worldpay')) $new .= $value . ',';
              }
              $new = substr($new, 0, strlen($new)-1);
              $directory_array = explode(",", $new);

              $tmp_directory_array = array();
              foreach($directory_array as $module_file) {
                $mod_class = substr($module_file, 0, strrpos($module_file, '.'));
              	$tmp_directory_array[] = array('mod_path'=>'gen', 'mod_file'=>$module_directory . $module_file, 'mod_lang_file'=> DIR_FS_CATALOG_LANGUAGES . $language . '/modules/' . $module_type . '/' .$module_file, 'mod_class'=>$mod_class);
              }
              $directory_array = $tmp_directory_array;
			  $cre_RCI->get('modules', $set); //RCI for Addon Modules

              // custom sort -eof
              for ($i=0, $n=sizeof($directory_array); $i<$n; $i++) {
                $file = basename($directory_array[$i]['mod_file']);
                if ($file == 'paypal_xc.php') continue;
                include($directory_array[$i]['mod_lang_file']);
                include($directory_array[$i]['mod_file']);
                $class = $directory_array[$i]['mod_class'];
                $mod_path = $directory_array[$i]['mod_path'];
                if (tep_class_exists($class)) {
                  $module = new $class;
                  if ($module->check() > 0) {
                    if ($module->sort_order > 0) {
                      $modules_wkey[$file] = $module->sort_order;
                    } else {
                      $modules_nokey[] = $file;
                    }
                  }
                  //if ($module->code == 'paypal_xc') continue;
                  if ((!isset($_GET['module']) || (isset($_GET['module']) && ($_GET['module'] == $class))) && !isset($mInfo)) {
                    $module_info = array('code' => $module->code,
                                         'title' => $module->title,
                                         'subtitle' => $module->subtitle,
                                         'description' => $module->description,
                                         'status' => $module->check());

                    $module_info['mod_path'] = $mod_path;
                    $module_keys = $module->keys();
                    $keys_extra = array();
                    for ($j=0, $k=sizeof($module_keys); $j<$k; $j++) {
                      $key_value_query = tep_db_query("select configuration_id,configuration_title, configuration_value, configuration_description, use_function,sort_order, set_function from " . TABLE_CONFIGURATION . " where configuration_key = '" . $module_keys[$j] . "'");
                      $key_value = tep_db_fetch_array($key_value_query);
                      $keys_extra[$module_keys[$j]]['title'] = $key_value['configuration_title'];
                      $keys_extra[$module_keys[$j]]['value'] = $key_value['configuration_value'];
                      $keys_extra[$module_keys[$j]]['description'] = $key_value['configuration_description'];
                      $keys_extra[$module_keys[$j]]['use_function'] = $key_value['use_function'];
                      $keys_extra[$module_keys[$j]]['set_function'] = $key_value['set_function'];
                    }
                    $module_info['keys'] = $keys_extra;
                    $mInfo = new objectInfo($module_info);
                  }
                  $selected = (isset($mInfo) && is_object($mInfo) && ($class == $mInfo->code)) ? true : false;
                  if ($selected) {
                    if ($module->check() > 0) {
                      echo '<tr class="paymentrow table-row dark selected" rowid="'.$set.'" onclick="document.location.href=\'' . tep_href_link(FILENAME_MODULES, 'set=' . $set . '&module=' . $class . '&action=edit', $SSL) . '\'">' . "\n";
                    } else {
                      echo '<tr class="table-row dark">' . "\n";
                    }
                  } else {
                    echo '<tr class="paymentrow table-row dark" rowid="'.$set.'" onclick="document.location.href=\'' . tep_href_link(FILENAME_MODULES, 'set=' . $set . '&module=' . $class) . '\'">' . "\n";
                  }
                  $col_selected = ($selected) ? ' selected' : '';
                  if ($module_type == 'payment') {
                    if (isset($module->pci) && $module->pci == true) {
                      echo '<td class="table-col dark text-center'. $col_selected.'"><i class="fa fa-lg fa-lock text-success"></i></td>';
                    } else {
                      echo '<td class="table-col dark text-center'. $col_selected.'"><i class="fa fa-lg fa-times text-danger"></i></td>';
                    }
                  }
                  ?>
                  <td class="table-col dark text-left<?php echo $col_selected; ?>">
                    <?php
                    if (isset($module->subtitle) && $module->subtitle != null) 
                    	echo '<strong>'.$module->title.'</strong><br><span class="smallText"><i>' . $module->subtitle . '</i></span>';
                    else
	                    echo $module->title;
                    ?>
                  </td>
                  <?php
                  if ($set == 'addons') {
                    echo '<td class="table-col dark text-center'. $col_selected .'">' . "\n";
                    if (isset($module->enabled) && $module->enabled == true) echo '<i class="fa fa-lg fa-check-circle text-success mr-2"></i>';
                  } else {
                    echo '<td class="table-col dark text-right'. $col_selected .'">' . "\n";
                     /* if (is_numeric($module->sort_order)&& isset($module->enabled) && $module->enabled == true) echo $module->sort_order; */
                    if (is_numeric($module->sort_order)&& isset($module->enabled) && $module->enabled == true) echo '<i class="fa fa-arrows fa-lg text-success"></i>';

                  }
                  ?>
                  </td>
                  <td class="table-col dark text-right<?php echo $col_selected; ?> d-none d-lg-table-cell col-blank"><?php echo ($selected) ? '<i class="fa fa-long-arrow-right fa-lg text-success"></i>' : '<a href="' . tep_href_link(FILENAME_CURRENCIES, 'page=' . $_GET['page'] . '&cID=' . $currency['currencies_id']) . '"><i class="fa fa-info-circle fa-lg text-muted"></i></a>'; ?>
                  </tr>
                  <?php
                }
              }
              $installed_modules = array();
              asort($modules_wkey, SORT_REGULAR);
              foreach ($modules_wkey as $file => $sort_order) {
                $installed_modules[] = $file;
              }
              $installed_modules = array_merge($installed_modules, $modules_nokey);

              $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = '" . $module_key . "'");
              if (tep_db_num_rows($check_query)) {
                $check = tep_db_fetch_array($check_query);
                if ($check['configuration_value'] != implode(';', $installed_modules)) {
                  tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '" . implode(';', $installed_modules) . "', last_modified = now() where configuration_key = '" . $module_key . "'");
                }
              } else {
                tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Installed Modules', '" . $module_key . "', '" . implode(';', $installed_modules) . "', 'This is automatically updated. No need to edit.', '6', '0', now())");
              }
              ?>
              </tbody>
            </table>
            <table class="data-table-foot w-100 mb-3">
              <tr>
              	 <td><a class="btn btn-success btn-sm mt-2 mb-2 mr-2" style="float:right;" href="javascript:void(0)" onclick="javascript:updateSortOrder()">Update Sort Order</a></td>
              </tr>
              <tr>
                <td class="sidebar-text"><?php echo TEXT_MODULE_DIRECTORY . ' ' . $module_directory; ?></td>
              </tr>
              <?php
              // RCI for global and individual bottom
		          echo $cre_RCI->get('modules', 'bottom');
		          echo $cre_RCI->get('global', 'bottom');
		          ?>
            </table>
          </div>
          <div class="col-md-3 col-xl-2 dark panel-right rounded-right">
            <?php
            $mInfo->code = ($mInfo->code == 'paypal_xc')?'paypal':$mInfo->code;
            $heading = array();
            $contents = array();
            if (!isset($mInfo)) {
              $mInfo = new objectInfo(array());
              $mInfo->title = '';
              $mInfo->status = '';
              $mInfo->keys = '';
              $mInfo->description = '';
              $mInfo->code = '';
            }
            switch ($action) {
              case 'edit':
                $keys = '';
                reset($mInfo->keys);
			    foreach($mInfo->keys as $key => $value) {
                  $keys .= '<div class="pb-3"><label class="control-label sidebar-edit mb-0 w-100">' . $value['title'] . '</label><div class="sidebar-title">' . $value['description'];
                  if ($value['set_function']) {
                    eval('$keys .= ' . $value['set_function'] . "'" . $value['value'] . "', '" . $key . "');");
                  } else {
                    $keys .= tep_draw_input_field('configuration[' . $key . ']', $value['value']);
                  }
                  $keys .= '</div></div>';
                }
                $keys = substr($keys, 0, strrpos($keys, '<br>'));
                $heading[] = array('text' => $mInfo->title);
                $contents[] = array('text' => '<div class="sidebar-text mt-3 mb-3">' . $mInfo->description . '</div>');
                $contents[] = array('text' => tep_draw_form('modules', FILENAME_MODULES, 'set=' . $set . '&module=' . (isset($_GET['module']) ? $_GET['module'] : '') . '&action=save', 'post', '', $SSL));
                $contents[] = array('text' => $keys);
                $contents[] = array('align' => 'center', 'text' => '<div class="mt-2 mb-2"><button class="btn btn-success btn-sm mt-2 mb-2 btn-update" type="submit">' . IMAGE_UPDATE . '</button><a class="btn btn-grey btn-sm mt-2 mb-2 btn-cancel" href="' . tep_href_link(FILENAME_MODULES, 'set=' . $set . '&module=' . (isset($_GET['module']) ? $_GET['module'] : ''), 'SSL') . '">' . IMAGE_CANCEL . '</a></div></form>');
                break;
              default:
                $heading[] = array('text' => (strpos($mInfo->title, "via") > 0) ? substr($mInfo->title, strpos($mInfo->title, "via")+4) : $mInfo->title);
                if ($mInfo->status == '1') {
                  $keys = '';
                  reset($mInfo->keys);
			      foreach($mInfo->keys as $key => $value) {
                    $keys .= '<div class="sidebar-text mt-2">' . $value['title'] . ': <span class="sidebar-title ml-2">';
                    if ($value['use_function']) {
                      $use_function = $value['use_function'];
                      if (preg_match('/->/', $use_function)) {
                        $class_method = explode('->', $use_function);
                        if (!isset(${$class_method[0]}) || !is_object(${$class_method[0]})) {
                          include(DIR_WS_CLASSES . $class_method[0] . '.php');
                          ${$class_method[0]} = new $class_method[0]();
                        }
                        $keys .= tep_call_function($class_method[1], $value['value'], ${$class_method[0]});
                      } else {
                        $keys .= tep_call_function($use_function, $value['value']);
                      }
                    } else {
                      $keys .= $value['value'];
                    }
                    $keys .= '</div>';
                  }

                  //$keys = substr($keys, 0, strrpos($keys, '<br><br>'));
                  $contents[] = array('align' => 'center', 'text' => '<div class="mt-2"><a class="btn btn-success btn-sm mt-2 mb-2 btn-edit" href="' . tep_href_link(FILENAME_MODULES, 'set=' . $set . (isset($_GET['module']) ? '&module=' . $_GET['module'] : '') . '&action=edit', $SSL) . '">' . IMAGE_EDIT . '</a><a class="btn btn-danger btn-sm mt-2 mb-2 btn-remove" href="' . tep_href_link(FILENAME_MODULES, 'set=' . $set . '&module=' . $mInfo->code . '&mod_path='. $mInfo->mod_path .'&action=remove', $SSL) . '">' . IMAGE_MODULE_REMOVE . '</a></div>');
                  if($mInfo->code == 'ultimateseo')
                    $contents[] = array('align' => 'center', 'text' => '<div class="sidebar-text mt-3 mb-3"><a class="btn btn-success btn-sm mt-2 mb-2 btn-buildpermalink" href="' . tep_href_link(FILENAME_MODULES, 'set=' . $set . '&module=' . $mInfo->code . '&mod_path='. $mInfo->mod_path .'&action=sync', $SSL) . '">Build Permalinks</a></div>');
                  $contents[] = array('align' => 'center', 'text' => '<div class="sidebar-img mt-3 well text-center">' . $mInfo->description . '</div>');
                  $contents[] = array('text' => $keys);
                } else {
                  if (isset($_GET['module']) && $_GET['module'] == '') {
                    $contents[] = array('text' => '<div class="sidebar-text mt-3 mb-3">No module selected.</div>');
                  } else {
                    $contents[] = array('align' => 'center', 'text' => '<div class="sidebar-text mt-3 mb-3"><a class="btn btn-success btn-sm mt-2 mb-2 btn-install" href="' . tep_href_link(FILENAME_MODULES, 'set=' . $set . '&module=' . $mInfo->code . '&mod_path='. $mInfo->mod_path .'&action=install', $SSL) . '">' . IMAGE_MODULE_INSTALL . '</a></div>');
                    $contents[] = array('align' => 'center', 'text' => '<div class="sidebar-img mt-3 well text-center">' . $mInfo->description . '</div>');
                  }
                }
                break;
            }

            if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
              $box = new box;
              echo $box->showSidebar($heading, $contents);
            }
            ?>
          </div>
        </div>
      </div>
      <!-- end body_text //-->
    <!-- end panel -->
  </div>
</div>
<script>
$(document).ready(function(){
  $('.sidebar-img img').addClass('img-fluid mb-1');
  $('.sidebar-img p').removeAttr('style').addClass('mb-0');
});

function updateSortOrder(){
     var selectedData = new Array();
     $('.row_module_position .paymentrow').each(function() {
	 selectedData.push($(this).attr("rowid"));
     });
    //alert(selectedData);
     updatemodulepaymentSortOrder(selectedData);

}
$( ".row_module_position" ).sortable({
 delay: 150
});
function updatemodulepaymentSortOrder(data) {
      var requestURL = '<?php echo tep_href_link("ajax_common.php", "action=setpaymentsorting");?>';
        $.ajax({
            url:requestURL,
            type:'post',
            data:{position:data},
            success:function(response){
             $.gritter.add({ text:'Sort order updated successfully!', sticky:false,time:"2500"});
            }
        })
}

</script>
<!-- body_eof //-->
<?php
include(DIR_WS_INCLUDES . 'html_bottom.php');
require(DIR_WS_INCLUDES . 'application_bottom.php');
?>
