<?php

/*
 * @name        JMY CMS
 * @link        https://jmy.su/
 * @copyright   Copyright (C) 2012-2025 JMY LTD
 * @license     LICENSE.txt (see attached file)
 * @version     VERSION.txt (see attached file)
 * @author      Orlov Alexsey
 */

if (!defined('ADMIN_SWITCH')) {
    header('Location: /');
    exit;
}
global $adminTpl, $config, $core, $db, $admin_conf, $redirectst_conf, $lang;
switch ($url[3] ?? null) {
    default:
    case 'redirects':
        redirects();
        break;
    case 'add':
        redirects_add();
        break;
    case 'edit':
        $id = isset($url[4]) ? intval($url[4]) : 0;
        redirects_add($id);
        break;
    case 'save':
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        $oldurl = strip_tags(filter($_POST['oldurl'], 'oldurl'), 'html');
        $newurl = strip_tags(filter($_POST['newurl'], 'newurl'), 'html');
        $desc = strip_tags(filter($_POST['desc'], 'desc'), 'html');
        $oldurl = str_ireplace(array('document.cookie'), array('d&#111;cument.cookie'), $oldurl);
        $oldurl = preg_replace(array('/javascript:/i'), array('j&#1072;vascript:'), $oldurl);
        $oldurl = preg_replace(array('/data:/i'), array('d&#1072;ta:'), $oldurl);
        $oldurl = str_replace(array('<br>'), array('\n'), $oldurl);
        $oldurl = str_replace(array('<br/>'), array('\n'), $oldurl);
        $newurl = str_ireplace(array('document.cookie'), array('d&#111;cument.cookie'), $newurl);
        $newurl = preg_replace(array('/javascript:/i'), array('j&#1072;vascript:'), $newurl);
        $newurl = preg_replace(array('/data:/i'), array('d&#1072;ta:'), $newurl);
        $newurl = str_replace(array('<br>'), array('\n'), $newurl);
        $newurl = str_replace(array('<br/>'), array('\n'), $newurl);
        $active = isset($_POST['active']) ? intval($_POST['active']) : 0;
        if ($oldurl == $newurl) {
            $adminTpl->info($lang['redirects_error1'], 'error', null, $lang['error'], $lang['go_back'], 'javascript:history.go(-1)');
        } elseif ($oldurl && $newurl) {
            if (isset($_POST['edit'])) {
                $core->upd_data('redirects', '`oldurl` ="' . $db->safesql($oldurl) . '", `newurl` ="' . $db->safesql($newurl) . '", `desc` ="' . $db->safesql($desc) . '", `active` ="' . $active . '"', 'id ="' . $id . '"');
                action_alert('urs', 'success', 'redirects', false, 'redirects_edit_ok');
            } else {
                $core->ins_data('redirects', 'id,oldurl,newurl,desc,active', 'NULL,"' . $db->safesql(processText($oldurl)) . '","' . $db->safesql(processText($newurl)) . '","' . $db->safesql(processText($desc)) . '","' . $active . '"');
                action_alert('urs', 'success', 'redirects', false, 'redirects_add_ok');
            }
            htacceess();
        } else {
            action_alert('urs', 'danger', 'redirects', 'add', 'not_field');
        }
        break;
    case 'retivate':
        $id = isset($url[4]) ? intval($url[4]) : 0;
        retivate($id);
        break;
    case 'delete':
        $id = isset($url[4]) ? intval($url[4]) : 0;
        delete($id);
        break;
    case 'action':
        $type = $_POST['act'];
        if (is_array($_POST['checks'])) {
            switch ($type) {
                case 'activate':
                    foreach ($_POST['checks'] as $id) {
                        $core->upd_data('redirects', 'active = 1', 'id ="' . intval($id) . '"');
                        action_alert('urs', 'success', 'redirects');
                    }
                    break;
                case 'deActivate':
                    foreach ($_POST['checks'] as $id) {
                        $core->upd_data('redirects', 'active = 0', 'id ="' . intval($id) . '"');
                        action_alert('urs', 'success', 'redirects');
                    }
                    break;
                case 'delete':
                    foreach ($_POST['checks'] as $id) {
                        delete(intval($id));
                        htacceess();
                        action_alert('urs', 'success', 'redirects');
                    }
                    break;
            }
            htacceess();
        } else {
            if (empty($_POST['checks'])) action_alert('urs', 'danger', 'redirects');
        }
        break;
    case 'config':
        init_count_text();
        require(ROOT . 'etc/redirects.config.php');
        $configBox = array(
            'redirects' => array(
                'varName' => 'redirects_conf',
                'title' => $lang['redirects_config'],
                'groups' => array(
                    'main' => array(
                        'title' => $lang['redirects_config'],
                        'vars' => array(
                            'allow_redirects' => array(
                                'title' => $lang['redirects_stat'],
                                'description' => $lang['redirects_stat_desc'],
                                'content' => yesNo('redirects', 'redirects_conf', 'allow_redirects'),
                            ),
                        )
                    ),
                ),
            ),
        );
        $ok = false;
        if (isset($_POST['conf_file'])) $ok = true;
        generateConfig($configBox, 'redirects', '{MOD_LINK}/config', $ok);
        break;
}
function redirects(): void
{
    global $adminTpl, $core, $url, $db, $lang;
    InitCheck();
    init_count_text();
    Scroll('search');
    Clearform('search');
    $where = '';
    $order = '';
    $s_id = isset($_POST['s_id']) ? intval($_POST['s_id']) : '';
    $s_oldurl = isset($_POST['s_oldurl']) ? filter($_POST['s_oldurl'], 'a') : '';
    $s_newurl = isset($_POST['s_newurl']) ? filter($_POST['s_newurl'], 'a') : '';
    $s_desc = isset($_POST['s_desc']) ? filter($_POST['s_desc'], 'a') : '';
    $s_active = isset($_POST['s_active']);
    $s_search = isset($_POST['s_search']);
    if ($s_search) $s_search = $_POST['s_search'] == 1;
    if ($s_active) {
        if ($_POST['s_active'] == 1) {
            $where = 'active = 1';
        } else {
            $s_active = false;
            $where = 'active = 0';
        }
    } else {
        $s_active = true;
    }
    if (isset($url[3]) && $url[3] == 'order') {
        switch ($url[4]) {
            case 'abc':
                $order .= '`newurl` ASC';
                break;
            case 'id':
                $order .= 'id ASC';
                break;
        }
    } else {
        $order .= 'id DESC';
    }
    if ($s_id) {
        $where .= "AND `id` LIKE '%" . $db->safesql($s_id) . "%'";
    } else {
        $s_id = '';
    }
    if ($s_oldurl) $where .= "AND `oldurl` LIKE '%" . $db->safesql($s_oldurl) . "%'";
    if ($s_newurl) $where .= "AND `newurl` LIKE '%" . $db->safesql($s_newurl) . "%'";
    if ($s_desc) $where .= "AND `desc` LIKE '%" . $db->safesql($s_desc) . "%'";
    $query = $core->select_data('redirects', $where, $order . ' LIMIT ' . limit_page());
    $adminTpl->admin_head($lang['redirects']);
    if ($db->numRows($query) > 0) {
        echo '<div id="content" class="table-layout animated fadeIn">
   <div class="tray tray-center">';
        alert_info('redirects');
        echo '<div class="panel panel-dark panel-border top">
         <div class="panel-heading">
            <span class="panel-title">' . $lang['redirects'] . '</span>
            ' . sort_head('urs', 4, false) . '
         </div>
         <div class="heading-hr"></div>
         <div class="panel-body pn table-responsive">
            <form id="tablesForm" style="margin:0; padding:0" method="POST" action="{MOD_LINK}/action" onclick="lihtTable(getSource(event))">
               <table class="table table-xs table-striped">
                  <thead>
                     <tr>
                        <th class="text-center hidden-xs"><span class="pd-l-sm"></span>#</th>
                        <th>' . $lang['redirects_old'] . '</th>
                        <th>' . $lang['redirects_new'] . '</th>
                        <th>' . $lang['redirects_desc'] . '</th>
                        <th class="text-center">' . $lang['status'] . '</th>';
        init_checkbox('th', false, false, true);
        echo '</tr>
                  </thead>
                  <tbody>';
        while ($redirects = $db->getRow($query)) {
            echo '<tr>
                        <td class="text-center hidden-xs"><span class="pd-l-sm"></span>' . $redirects['id'] . '</td>
                        <td>' . $redirects['oldurl'] . '</td>
                        <td><a href="' . $redirects['newurl'] . '" target="_blank">' . $redirects['newurl'] . '</a></td>
                        <td>' . $redirects['desc'] . '</td>
                        <td class="text-center">' . status_icon('redirects', $redirects['id']) . '</td>';
            init_checkbox('td', $redirects['id'], false, '<li><a href="{MOD_LINK}/edit/' . $redirects['id'] . '">' . faSpan('fa-external-link', true, $lang['edit']) . '</a></li>
                              <li><a href="{MOD_LINK}/retivate/' . $redirects['id'] . '">' . faSpan('fa-power-off', true, (($redirects['active'] == 0) ? $lang['do_activation'] : $lang['do_deactivation'])) . '</a></li>
                              <li class="divider"></li>
                              <li><a href="' . $core->fullURL() . '#" onclick="modal_o(\'#modal-form-' . $redirects['id'] . '\')">' . faSpan('fa-trash-o text-danger', true, $lang['delete']) . '</a></li>');
            echo '</tr>';
            modal_form_delete($redirects['id'], $redirects['oldurl'], $lang['redirects_delete_title'], 'redirects', $lang['redirects_delete_text'], '{MOD_LINK}/delete/' . $redirects['id']);
        }
        echo '</tbody>';
        init_tfoot('<option value="activate">' . $lang['do_activation'] . '</option>
                           <option value="deActivate">' . $lang['do_deactivation'] . '</option>
                           <option value="delete">' . $lang['delete'] . '</option>');
        echo '</table>
            </form>
         </div>
      </div>';
        page_list('urs', 'redirects', 'redirects', $where);
        echo '</div>
   <aside data-tray-height="match" class="panel tray-right tray-rescale tray290">
      <form id="search" name="search" role="form" method="POST" action=""> 
         <div style="margin-bottom: 20px; border-width: 0;" class="form-group admin-form p15">
            <h4 class="text-left pt10";>' . $lang['panel_menu_user'] . '</h4>
            <hr class="short">
            <div class="section mb5">
               <label for="s_id" class="field prepend-icon">
               <input id="s_id" type="text" name="s_id" placeholder="' . $lang['redirects_id'] . '" class="form-control" value="' . $s_id . '" onkeypress="if (isNaN(this.value + String.oldurlCharCode(event.keyCode))) return false;">
               <label for="s_id" class="field-icon">' . faI(false, false, '#', true) . '</label>
               </label>
            </div>
            <div class="section mb5">
               <label for="s_oldurl" class="field prepend-icon">
               <input id="s_oldurl" type="text" name="s_oldurl" placeholder="' . $lang['redirects_old'] . '" class="form-control" value="' . $s_oldurl . '">
               <label for="s_oldurl" class="field-icon">' . faI('fa-pencil', false, false, true) . '</label>
               </label>
            </div>
            <div class="section mb5">
               <label for="s_newurl" class="field prepend-icon">
               <input id="s_newurl" type="text" name="s_newurl" placeholder="' . $lang['redirects_new'] . '" class="form-control" value="' . $s_newurl . '">
               <label for="s_newurl" class="field-icon">' . faI('fa-pencil', false, false, true) . '</label>
               </label>
            </div>
            <div class="section mb10">
               <label for="s_desc" class="field prepend-icon">
               <input id="s_desc" type="text" name="s_desc" placeholder="' . $lang['redirects_desc'] . '" class="form-control" value="' . $s_desc . '">
               <label for="s_desc" class="field-icon">' . faI('fa-keyboard-o', false, false, true) . '</label>
               </label>
            </div>
            <div class="section mb5">
               <label class="field option">
               <input type="hidden" name="s_active" value="0">
               <input type="checkbox" name="s_active"' . ($s_active ? 'checked' : '') . ' value="1"><span class="checkbox"></span>' . $lang['redirects_active'] . '</label>
            </div>
            ' . init_sfoot(true, true, false, '{MOD_LINK}') . '            
         </div>
      </form>
   </aside>
</div>';
    } else {
        list_empty('urs', 'redirects', 'url', $s_search, false, true, $s_search);
    }
    $adminTpl->admin_foot();
}

function redirects_add($id = null): void
{
    global $adminTpl, $core, $lang;
    if (isset($id)) {
        $redirects = $core->row_data('redirects', 'id ="' . $id . '"');
        $oldurl = $redirects['oldurl'];
        $newurl = $redirects['newurl'];
        $desc = $redirects['desc'];
        $active = $redirects['active'];
        $admhead = $lang['redirects_edit'];
    } else {
        $oldurl = false;
        $newurl = false;
        $desc = false;
        $active = false;
        $admhead = $lang['redirects_add'];
    }
    $validation_array = array(
        'oldurl' => array(
            'required' => array('true', $lang['add_title_err']),
            'maxlength' => array(99, str_replace('[count]', '100', $lang['count_text_err_2']))
        ),
        'newurl' => array(
            'required' => array('true', $lang['add_descr_err']),
            'maxlength' => array(99, str_replace('[count]', '100', $lang['count_text_err_2']))
        ),
        'desc' => array(
            'required' => array('true', $lang['add_descr_err']),
            'maxlength' => array(199, str_replace('[count]', '200', $lang['count_text_err_2']))
        ),
    );
    validationInit($validation_array);
    init_count_text();
    $adminTpl->admin_head($admhead);
    echo '<div id="content" class="table-layout animated fadeIn">
<div class="tray tray-center">
<div class="panel panel-dark panel-border top">
   <div class="panel-heading">
      <span class="panel-title">' . $admhead . '</span>
   </div>
  <div class="heading-hr"></div>
   <div class="panel-body admin-form">
      <form id="admin-form" class="form-horizontal parsley-form" role="form" action="{MOD_LINK}/save" method="post">
         <div class="form-group">
            <label for="oldurl" class="col-lg-3 col-sm-3 control-label">' . $lang['redirects_old'] . '</label>
            <div class="col-lg-5 col-md-5 col-sm-8">
               <label for="oldurl" class="field prepend-icon">
               <input id="oldurl" type="text" name="oldurl" value="' . $oldurl . '" onkeyup="count_down(this, \'oldurl\', 100);getRedir(gid(\'oldurl\').value, \'related_oldurl\');" maxlength="100" placeholder="' . $lang['redirects_old_pre'] . '" class="form-control" data-parsley-required="true" data-parsley-trigger="change">
               <label for="oldurl" class="field-icon">' . faI('fa-link', false, false, true) . '</label>
               </label>
          <div class="text-align:right;text-right">
                              <span id="char_oldurl"></span>
                           </div>
                           <span id="related_oldurl"></span>
                           <span class="input-footer text-left">' . faI('fa-bell') . $lang['redirects_old1'] . '</span>
                        </div>
                     </div>
         <div class="form-group">
            <label for="newurl" class="col-lg-3 col-sm-3 control-label">' . $lang['redirects_new'] . '</label>
            <div class="col-lg-5 col-md-5 col-sm-8">
               <label for="newurl" class="field prepend-icon">
               <input id="newurl" type="text" name="newurl" value="' . $newurl . '" onkeyup="count_down(this, \'newurl\', 100)" maxlength="100" placeholder="' . $lang['redirects_new_pre'] . '" class="form-control" data-parsley-required="true" data-parsley-trigger="change">
               <label for="newurl" class="field-icon">' . faI('fa-link', false, false, true) . '</label>
               </label>
               <div class="text-align:right;text-right">
                              <span id="char_newurl"></span>
                           </div>
                           <span id="related_tag"></span>
                           <span class="input-footer text-left">' . faI('fa-bell') . $lang['redirects_new1'] . '</span>
                        </div>
                     </div>
         <div class="form-group">
              <label for="desc" class="col-lg-3 col-sm-3 control-label">' . $lang['description'] . '</label>
                  <div class="col-lg-5 col-md-5 col-sm-8">
                     <label for="desc" class="field prepend-icon">
                     <textarea id="desc" name="desc" onkeyup="count_down(this, \'desc\', 200)" maxlength="200" placeholder="' . $lang['redirects_stat_desc1'] . '" class="form-control br-light bg-light" style="height: 124px; margin: 0 auto">' . $desc . '</textarea>
                     <label for="desc" class="field-icon">' . faI('fa-keyboard-o', false, false, true) . '</label>
                     </label>
                  <div class="text-align:right;text-right">
                      <span id="char_desc"></span>
                  </div>
              <span class="input-footer text-left">' . faI('fa-bell') . $lang['redirects_stat_desc1'] . '</span>
           </div>
         </div>
         <div class="form-group">
            <div class="col-xs-6">
               <label class="field option">
               <input type="checkbox" name="active" ' . ($active ? 'checked' : '') . ' value="1" checked><span class="checkbox mr10"></span>' . $lang['redirects_on'] . '</label><br>
               <hr class="alt short mv15">
            </div>
         </div>
   </div>
   ' . init_dfoot(true, 'fa-floppy-o', 'save', 'system');
    if (isset($id)) {
        echo '<input type="hidden" name="edit" value="1">';
        echo '<input type="hidden" name="id" value="' . $id . '">';
    }
    echo '</form>
</div>';
    $adminTpl->admin_foot();
}

function yesNo($file, $global, $var): string
{
    global $$global;
    $conf = $$global;
    $but_1 = ($conf[$var] == 1) ? "checked" : "";
    return '<div class="switch switch-info round switch-inline">
   <input type="hidden" name="{varName}" value="0">
   <input id="ch{varName}" name="{varName}" type="checkbox" ' . $but_1 . ' value="1">
   <label for="ch{varName}"></label>
</div>';
}

function htacceess(): void
{
    global $config, $core, $db, $redirects_conf, $redirectst_conf;
    $redirectsTXT = '';
    $redirectsHTTPS = '';
    $s_standartTXT = '';
    $f_standartTXT = '';
    $brTXT = '
    ';
    $redirectsTXT .= 'AddDefaultCharset UTF-8
RewriteEngine on' . $brTXT;
    $redirectsHTTPS .= 'RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]' . $brTXT;
    $s_standartTXT .= '#RewriteBase /
RewriteRule ^captcha$ ajax.php?do=captcha [L]
RewriteRule ^ajax/(.*)$ ajax.php?$1 [L]
RewriteRule ^index(.html|.htm)$ index.php [L]
RewriteRule ^sitemap.xml$ files/sitemap.xml [L]' . $brTXT;
    $f_standartTXT .= 'RewriteRule ^admin$ administration [L]
RewriteRule ^administrator$ administration [L]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{REQUEST_URI} !\.(css|js|jpe?g|gif|png|bmp|ico)$
RewriteRule ^(.*)$ index.php?url=$1 [L]' . $brTXT;
    $pos = strpos($config['url'], 'https://');
    $redirects_url = $pos === false ? '' : $redirectsHTTPS;
    $query = $core->select_data('redirects', 'active = 1');
    if ($redirects_conf['allow_redirects'] == 1) {
        $redirectsTXT .= $redirects_url . $s_standartTXT . $brTXT;
        if ($db->numRows($query) > 0) {
            while ($sm = $db->getRow($query)) {
                $redirectsTXT .= 'RewriteRule ^' . $sm['newurl'] . '$ ' . $sm['oldurl'] . $redirectst_conf['change'] . ' [L]' . $brTXT;
            }
            $redirectsTXT .= $brTXT;
            $flag = true;
        }
        $redirectsTXT .= $f_standartTXT;
    } else {
        $redirectsTXT .= $redirects_url . $s_standartTXT . $f_standartTXT;
    }
    $fp = fopen(ROOT . '/.htaccess', 'w+');
    if (!fwrite($fp, $redirectsTXT)) $flag = false;
    fclose($fp);
}

function retivate($id): void
{
    global $core;
    if (!empty($id)) {
        $rows = $core->row_data('redirects', 'id ="' . $id . '"');
        $active = $rows['active'] == 0 ? 1 : 0;
        $core->upd_data('redirects', 'active ="' . $active . '"', 'id ="' . $id . '"');
        htacceess();
        action_alert('urs', 'success', 'redirects');
    } else {
        action_alert('urs', 'danger', 'redirects', false, 'unknown_error');
    }
}

function delete($id): void
{
    global $core;
    if (!empty($id)) {
        $core->del_data('redirects', 'id ="' . $id . '"');
        htacceess();
        action_alert('urs', 'success', 'redirects');
    } else {
        action_alert('urs', 'danger', 'redirects', false, 'unknown_error');
    }
}