<?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      Komarov Ivan
 * @edited      Orlov Alexsey
 */

if (!defined('ACCESS')) {
    header('Location: /');
    exit;
}
loadConfig('sitemap');
global $adminTpl, $db, $core, $sitemap_conf, $lang;
switch ($url[3] ?? null) {
    default:
        $adminTpl->admin_head($lang['modules'] . ' | ' . $lang['sitemap']);
        Scroll('robot');
        $change = '';
        $query = $core->select_data('sitemap', false, 'id ASC');
        if ($db->numRows($query) > 0) {
            echo '<div id="content" class="table-layout animated fadeIn">
   <div class="tray tray-center">';
            alert_info('sitemap');
            echo '<div class="panel panel-dark panel-border top">
         <div class="panel-heading">
            <span class="panel-title">' . $lang['sitemap'] . '</span>
         </div>
         <div class="heading-hr"></div>
         <div class="panel-body pn table-responsive">
            <form id="tablesForm" style="margin:0; padding:0" method="POST">
               <table class="table no-margin table-striped">
                  <thead>
                     <tr>
                        <th class="text-center hidden-xs"><span class="pd-l-sm"></span>#</th>
                        <th class="col-md-5 text-center">' . $lang['title'] . '</th>
                        <th class="text-center">' . $lang['sitemap_update'] . '</th>
                        <th class="text-center">' . $lang['sitemap_rang'] . '</th>
                     </tr>
                  </thead>
                  <tbody>';
            while ($result = $db->getRow($query)) {
                $changear = array('always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never');
                if (in_array($sitemap_conf['change'], $changear)) $change = $lang[$sitemap_conf['change']];
                echo '<tr>
                        <td class="text-center hidden-xs"><span class="pd-l-sm"></span>' . $result['id'] . '</td>
                        <td class="text-left"><a href="' . $result['url'] . '" target="_blank">' . trimtitle($result['name'], 50) . '</a></td>
                        <td class="text-center">' . $change . '</td>
                        <td class="text-center">' . $sitemap_conf['priority'] . '</td>
                     </tr>';
            }
            echo '</tbody>
               </table>
            </form>
            <div class="panel-footer text-right">
               <button  type="button" onclick="window.location.href = \'{MOD_LINK}/truncate\'" class="btn bg-danger btn-sm btn-raised legitRipple">' . faSpan('fa-eraser', true, $lang['truncate_sitemap']) . '</button>
            </div>
         </div>
      </div>
   </div>
<aside data-tray-height="match" class="panel tray-right tray-rescale tray320">
      <form id="robot+" role="form" method="POST" action="">
      <div class="form-group admin-form">
	<div style="padding-right: 1px !important; margin-bottom: 20px; border-width: 0;" class="form-group admin-form">
   <h4 class="text-left pl20 pt10">' . $lang['robot_txt'] . '</h4>
   <hr class="short">
   <div class="section mb5">
      <table class="table table-sm">
         <tr>
            <td class="col-md-3">';
            $robots = file(ROOT . '/robots.txt');
            foreach ($robots as $str) {
                echo $str . '<br/>';
            }
            echo '</td>
         </tr>
      </table>
</div>
</div>
   </aside>
</div>';
        } else {
            $adminTpl->info($lang['sitemap_empty'], 'empty', null, $lang['sitemap'], $lang['sitemap_gen'], ADMIN . '/module/sitemap/create');
        }
        echo '</div>
</div>';
        $adminTpl->admin_foot();
        break;
    case 'truncate':
        $truncate = isset($url[3]) ? filter($url[3]) : false;
        $robotsTXT =  '';
        $sitemapTXT = '';
        $sitemapXML =  '';
        if ($truncate) {
            $core->truncate_data('sitemap');
            $fp = fopen('files/sitemap.txt', 'w+');
            if (!fwrite($fp, $sitemapTXT)) $flag = false;
            fclose($fp);
            $fp = fopen('files/sitemap.xml', 'w+');
            if (!fwrite($fp, $sitemapXML)) $flag = false;
            fclose($fp);
            $fp = fopen(ROOT . '/robots.txt', 'w+');
            if (!fwrite($fp, $robotsTXT)) $flag = false;
            fclose($fp);
            action_alert('urs', 'success', 'sitemap');
        } else {
            action_alert('urs', 'danger', 'sitemap', false, 'truncate_error');
        }
        break;
    case 'create':
        global $db, $core, $config, $sitemap_conf;
        $adminTpl->admin_head($lang['modules'] . ' | ' . $lang['sitemap'] . ' | ' . $lang['sitemap_gens']);
        $core->truncate_data('sitemap');
        $core->ins_data('sitemap', 'id,name,url', 'NULL,"' . $lang['sitemap_main'] . '","' . $config['url'] . '/"');
        $query = $core->select_data('plugins', 'service ="modules"', 'title ASC');
        $flag = '';
        $rflag = '';
        $robotTXT = '';

        $content_maps = '';
        $content_map = array('Ask', 'Bing', 'Google', 'Weblogs', 'Yahoo', 'Yandex');
        foreach ($content_map as $maps) {
            $content_maps .= (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Google") ? $sitemap_conf[$maps] . ', ' : '';
            $content_maps .= (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Bing") ? $sitemap_conf[$maps] . ', ' : '';
            $content_maps .= (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Yahoo") ? $sitemap_conf[$maps] . ', ' : '';
            $content_maps .= (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Ask") ? $sitemap_conf[$maps] . ', ' : '';
            $content_maps .= (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Weblogs") ? $sitemap_conf[$maps] . ', ' : '';
            $content_maps .= (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Yandex") ? $sitemap_conf[$maps] : '';
        }
        $content_maps = !$content_maps ? " User-agent: *" : " User-agent: $content_maps";
        $robotTXT .= $content_maps;
        $robotTXT .= "\r\n";
        $robotTXT .= "\r\n Disallow: /boot/*";
        $robotTXT .= "\r\n Disallow: /etc/*";
        $robotTXT .= "\r\n Disallow: /files/*";
        $robotTXT .= "\r\n Disallow: /langs/*";
        $robotTXT .= "\r\n Disallow: /lib/*";
        $robotTXT .= "\r\n Disallow: /media/*";
        $robotTXT .= "\r\n Disallow: /root/*";
        $robotTXT .= "\r\n Disallow: /tmp/*";
        $robotTXT .= "\r\n Disallow: /usr/*";
        $robotTXT .= "\r\n Disallow: /define.php/*";
        $robotTXT .= "\r\n Disallow: /auth.php/*";
        if ($db->numRows($query) > 0) {
            while ($mod = $db->getRow($query)) {
                $mods = !empty($sitemap_conf[$mod['title']]) ? ($sitemap_conf[$mod['title']] != '' ? $sitemap_conf[$mod['title']] : '') : '';
                $exceMods = array();
                $exceMods = explode(',', $mods);
                $robotTXT .= !empty($mods) ? "\r\n Disallow: /" . $mods . "/*" : "";
                if (!in_array($mod['title'], $exceMods)) {
                    if ($mod['active'] == 1) {
                        $file = ROOT . 'usr/modules/' . $mod['title'] . '/sitemap.php';
                        $core->ins_data('sitemap', 'id,name,url', 'NULL,"' . $mod['content'] . '","' . $config['url'] . '/' . $mod['title'] . '"');
                        if (file_exists($file)) include($file);
                    }
                }
            }
        }
        $sitemapXML = '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="https://www.google.com/schemas/sitemap/0.84"
   xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="https://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd">
   <!-- Last update of sitemap ' . date("Y-m-d H:i:s+06:00") . ' -->';
        $sitemapTXT = NULL;
        $query_sm = $core->select_data('sitemap', false, 'id ASC');
        $ic = $db->numRows($query_sm);
        if ($db->numRows($query_sm) > 0) {
            while ($sm = $db->getRow($query_sm)) {
                $sitemapXML .= "\r\n
   <url>
      <loc>{$sm['url']}</loc>
      <changefreq>{$sitemap_conf['change']}</changefreq>
      <priority>{$sitemap_conf['priority']}</priority>
   </url>";
                $sitemapTXT .= "\r\n" . $sm['url'] . ' ' . $sitemap_conf['change'] . ' ' . $sitemap_conf['priority'];
            }
            $flag = true;
        }
        $sitemapXML .= "\r\n
</urlset>";
        $robotTXT .= "\r\n";
        $robotTXT .= "\r\n Host: " . $config['url'];
        $robotTXT .= "\r\n Sitemap: " . $config['url'] . "/sitemap.xml";
        $fp = fopen('files/sitemap.txt', 'w+');
        if (!fwrite($fp, $sitemapTXT)) $flag = false;
        fclose($fp);
        $fp = fopen('files/sitemap.xml', 'w+');
        if (!fwrite($fp, $sitemapXML)) $flag = false;
        fclose($fp);
        $fp = fopen(ROOT . '/robots.txt', 'w+');
        if (!fwrite($fp, $robotTXT)) $flag = false;
        fclose($fp);
        $rflag = $flag ? $adminTpl->info(str_replace('[numb]', $ic, $lang['sitemap_gen_ok']), 'info', null, $lang['info'], $lang['sitemap'], ADMIN . '/module/sitemap') : $adminTpl->info($lang['sitemap_gen_error'], 'error', null, $lang['error'], $lang['sitemap'], ADMIN . '/module/sitemap');
        echo $rflag;
        $adminTpl->admin_foot();
        break;
    case 'update':
        global $core, $config;
        $adminTpl->admin_head($lang['modules'] . ' | ' . $lang['sitemap'] . ' | ' . $lang['sitemap_searchs']);
        $url_map = $config['url'] . '/sitemap.xml';
        $content_maps = '';
        $content_map = array('Ask', 'Bing', 'Google', 'Weblogs', 'Yahoo', 'Yandex');
        foreach ($content_map as $maps) {
            if (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Google") $content_maps .= str_contains(send_url("https://google.com/webmasters/sitemaps/ping?sitemap=", $url_map), "successfully added") ? 'Google: ' . $lang['sitemap_send_ok'] . '<br/>' : 'Google: <a href="https://google.com/webmasters/sitemaps/ping?sitemap=' . urlencode($url_map) . '">' . $lang['sitemap_send_error'] . '</a><br/>';
            if (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Bing") $content_maps .= !strpos(send_url("https://www.bing.com/webmaster/ping.aspx?siteMap=", $url_map), "https://www.bing.com/ping?sitemap=") ? 'Bing: ' . $lang['sitemap_send_ok'] . '<br/>' : 'Bing: <a href="https://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=' . urlencode($url_map) . '">' . $lang['sitemap_send_error'] . '</a><br/>';
            if (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Yahoo") $content_maps .= !strpos(send_url("https://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=SitemapWriter&amp;url=", $url_map), "https://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=SitemapWriter&amp;url=") ? 'Yahoo: ' . $lang['sitemap_send_ok'] . '<br/>' : 'Yahoo: <a href="https://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=SitemapWriter&amp;url=' . urlencode($url_map) . '">' . $lang['sitemap_send_error'] . '</a><br/>';
            if (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Ask") $content_maps .= !strpos(send_url("https://submissions.ask.com/ping?sitemap=", $url_map), "https://submissions.ask.com/ping?sitemap=") ? 'Ask: ' . $lang['sitemap_send_ok'] . '<br/>' : 'Ask: <a href="https://submissions.ask.com/ping?sitemap=' . urlencode($url_map) . '">' . $lang['sitemap_send_error'] . '</a><br/>';
            if (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Weblogs") $content_maps .= !strpos(send_url("https://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=", $url_map), "https://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=") ? 'Weblogs: ' . $lang['sitemap_send_ok'] . '<br/>' : 'Weblogs: <a href="https://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=' . urlencode($url_map) . '">' . $lang['sitemap_send_error'] . '</a><br/>';
            $curl = str_replace(array('//'), array(''), $config['url']);
            $cport = str_replace(array('http:', 'https:'), array($lang['p443'], $lang['p443']), $curl);
            if (($maps == isset($sitemap_conf[$maps])) && $sitemap_conf[$maps] == "Yandex") $content_maps .= strpos(send_url("&url=", $url_map), "&url=") ? 'Yandex: ' . $lang['sitemap_send_ok'] . '<br/>' : 'Yandex: <a href="https://webmaster.yandex.ru/site/' . $curl . ':' . preg_replace("/[^,0-9]/", '', $cport) . '/indexing/sitemap/">' . $lang['sitemap_send_error'] . '</a><br/>';
        }
        $adminTpl->info($content_maps, 'info', null, $lang['info'], $lang['sitemap'], ADMIN . '/module/sitemap');
        $adminTpl->admin_foot();
        break;
    case 'config':
        $configBox = array(
            'sitemap' => array(
                'varName' => 'sitemap_conf',
                'title' => $lang['sitemap_config'],
                'groups' => array(
                    'main' => array(
                        'title' => $lang['config_main'],
                        'vars' => array(
                            'priority' => array(
                                'title' => $lang['sitemap_config_rang'],
                                'description' => $lang['sitemap_config_rang_desc'] . info_modal('size_post') . modal_form_text('size_post', $lang['info'], 'fa-info-circle', $lang['info_rang'], false, $lang['info_rang_desc']),
                                'content' => conf_range(),
                            ),
                            'change' => array(
                                'title' => $lang['sitemap_config_update'],
                                'description' => $lang['sitemap_config_update_desc'],
                                'content' => change(),
                            ),
                            'modules' => array(
                                'title' => $lang['modules'],
                                'description' => $lang['sitemap_select_module'],
                                'content' => modules(),
                            ),
                            'maps' => array(
                                'title' => $lang['maps'],
                                'description' => $lang['sitemap_select_maps'],
                                'content' => content_map(),
                            ),
                        )
                    ),
                    'seo' => array(
                        'title' => $lang['seo'],
                        'vars' => array(
                            'keywords' => array(
                                'title' => $lang['seo_keywords'],
                                'description' => $lang['seo_settings'],
                                'content' => int_cong('textarea', '{varName}', '{var}', 'keywords'),
                            ),
                            'description' => array(
                                'title' => $lang['seo_description'],
                                'description' => $lang['seo_settings'],
                                'content' => int_cong('textarea', '{varName}', '{var}', 'description'),
                            ),
                        )
                    ),
                ),
            ),
        );
        $ok = false;
        if (isset($_POST['conf_file'])) $ok = true;
        generateConfig($configBox, 'sitemap', '{MOD_LINK}/config', $ok);
        break;
}
function conf_range(): string
{
    global $sitemap_conf;
    return '<input style="width: 170px;" value="' . $sitemap_conf['priority'] . '" type="range" name="priority" step="0.1" min="0" max="1.0" list="rangeList" onchange="document.getElementById(\'rangeValue\').innerHTML = this.value;">
<datalist id="rangeList">
   <option value="0" label="0"' . ($sitemap_conf['priority'] == "0" ? "range" : "") . '></option>
   <option value="0.1" label="0.1"' . ($sitemap_conf['priority'] == "0.1" ? "range" : "") . '></option>
   <option value="0.2" label="0.2"' . ($sitemap_conf['priority'] == "0.2" ? "range" : "") . '></option>
   <option value="0.3" label="0.3"' . ($sitemap_conf['priority'] == "0.3" ? "range" : "") . '></option>
   <option value="0.4" label="0.4"' . ($sitemap_conf['priority'] == "0.4" ? "range" : "") . '></option>
   <option value="0.5" label="0.5"' . ($sitemap_conf['priority'] == "0.5" ? "range" : "") . '></option>
   <option value="0.6" label="0.6"' . ($sitemap_conf['priority'] == "0.6" ? "range" : "") . '></option>
   <option value="0.7" label="0.7"' . ($sitemap_conf['priority'] == "0.7" ? "range" : "") . '></option>
   <option value="0.8" label="0.8"' . ($sitemap_conf['priority'] == "0.8" ? "range" : "") . '></option>
   <option value="0.9" label="0.9"' . ($sitemap_conf['priority'] == "0.9" ? "range" : "") . '></option>
   <option value="1.0" label="1.0"' . ($sitemap_conf['priority'] == "1.0" ? "range" : "") . '></option>
</datalist>
<span id="rangeValue">' . $sitemap_conf['priority'] . '</span>';
}

function change(): string
{
    global $sitemap_conf, $lang;
    return '<select class="form-control" name="change">
<option value="always" ' . ($sitemap_conf['change'] == "always" ? "selected" : "") . '>' . $lang['always'] . '</option>
<option value="hourly" ' . ($sitemap_conf['change'] == "hourly" ? "selected" : "") . '>' . $lang['hourly'] . '</option>
<option value="daily" ' . ($sitemap_conf['change'] == "daily" ? "selected" : "") . '>' . $lang['daily'] . '</option>
<option value="weekly" ' . ($sitemap_conf['change'] == "weekly" ? "selected" : "") . '>' . $lang['weekly'] . '</option>
<option value="monthly" ' . ($sitemap_conf['change'] == "monthly" ? "selected" : "") . '>' . $lang['monthly'] . '</option>
<option value="yearly" ' . ($sitemap_conf['change'] == "yearly" ? "selected" : "") . '>' . $lang['yearly'] . '</option>
<option value="never" ' . ($sitemap_conf['change'] == "never" ? "selected" : "") . '>' . $lang['never'] . '</option>
</select>';
}

function modules(): string
{
    global $sitemap_conf, $core;
    $content = '<div class="panel-body admin-form">';
    foreach ($core->getModList() as $module) {
        if (!empty($core->tpl->modules[$module])) {
            $check = ($module == isset($sitemap_conf[$module])) ? 'checked' : '';
            $content .= '<div class="col-xs-6">
      <label class="field option">
      <input id="checkbox' . $module . '" type="checkbox" name="' . $module . '"' . $check . ' value="' . $module . '">
      <span class="checkbox mr10"></span>' . _mName($module) . '</label><br>
      <div class="alt short mv15"></div>
   </div>';
        }
    }
    $content .= '<br/>
</div>';
    return $content;
}

function content_map(): string
{
    global $sitemap_conf;
    $content_map = array('Ask', 'Bing', 'Google', 'Weblogs', 'Yahoo', 'Yandex');
    $content = '<div class="panel-body admin-form">';
    foreach ($content_map as $maps) {
        $check = ($maps == isset($sitemap_conf[$maps])) ? 'checked' : '';
        $content .= '<div class="col-xs-6">
      <label class="field option">
      <input id="checkbox' . $maps . '" type="checkbox" name="' . $maps . '"' . $check . ' value="' . $maps . '">
      <span class="checkbox mr10"></span>' . _mName($maps) . '</label><br>
      <div class="alt short mv15"></div>
   </div>';
    }
    $content .= '<br/>
</div>';
    return $content;
}

