<?php

$cms['modules']['sitemap.mod.php'] = array(
    'name' => __('Sitemap', 'sitemap.mod.php'),
    'description' => __('Module for configure sitemap.xml', 'sitemap.mod.php'),
    'url_title' => __('Module page'),
    'url_link' => __('https://coffee-cms.com/en/modules/sitemap/', 'sitemap.mod.php'),
    'author' => __('Coffee CMS team'),
    'version' => '20.07',
    'files' => array(
        '.cms/mod/sitemap.mod.php',
        '.cms/js/sitemap.js',
    ),
    'sort'    => 20,
);

// Return if module disabled
if ( isset($cms['config']['sitemap.mod.php']['disabled'])
&& $cms['config']['sitemap.mod.php']['disabled'] === true ) return;

/* Default Settings */

if (empty($cms['config']['sitemap.mod.php']['update_interval'])) {
    $cms['config']['sitemap.mod.php']['update_interval'] = 60;
}
if (empty($cms['config']['sitemap.mod.php']['exclude'])) {
    $cms['config']['sitemap.mod.php']['exclude'] = '';
}
if (empty($cms['config']['sitemap.mod.php']['include'])) {
    $cms['config']['sitemap.mod.php']['include'] = '';
}
if (empty($cms['config']['sitemap.mod.php']['gen'])) {
    $cms['config']['sitemap.mod.php']['gen'] = 'static';
}
if (empty($cms['config']['sitemap.mod.php']['lastrun'])) {
    $cms['config']['sitemap.mod.php']['lastrun'] = '';
}
if (empty($cms['config']['sitemap.mod.php']['excluded_types'])) {
    $cms['config']['sitemap.mod.php']['excluded_types'] = array('redirect','admin');
}


cms_add_function('admin', 'cms_sitemap_admin');

if ( $cms['config']['sitemap.mod.php']['gen'] === 'static' ) {
    cms_add_function('cron', 'cms_sitemap_cron');
} else {
    $cms['urls']['^'.$cms['base_url'].'sitemap.xml$'] = 'sitemap.xml';
    cms_add_function('sitemap.xml', 'cms_sitemap_xml');
}

function cms_sitemap_cron() {
    global $cms;
    if ( $cms['config']['sitemap.mod.php']['lastrun'] < date('Y-m-d H:i:s', time() - $cms['config']['sitemap.mod.php']['update_interval'] * 60) ) {
        $sitemap = cms_sitemap_generate();
        file_put_contents($cms['site_dir'].'/sitemap.xml', $sitemap);
        $cms['config']['sitemap.mod.php']['lastrun'] = date('Y-m-d H:i:s');
        cms_save_config();
    }
}

function cms_sitemap_xml() {
    header('Content-Type: text/xml');
    echo cms_sitemap_generate();
}

function cms_sitemap_update() {
    global $cms;
    // Return if module disabled
    if ( isset($cms['config']['sitemap.mod.php']['disabled'])
    && $cms['config']['sitemap.mod.php']['disabled'] === true ) return;
    if ( $cms['config']['sitemap.mod.php']['gen'] === 'static' ) {
        $sitemap = cms_sitemap_generate();
        file_put_contents($cms['site_dir'].'/sitemap.xml', $sitemap);
    }
}

function cms_sitemap_generate() {
    global $cms;
    if (empty($cms['base'])) cms_base_connect();
    if (empty($cms['base'])) return;
    if ($cms['base']->connect_error) return;

    if ( $cms['config']['sitemap.mod.php']['gen'] === 'static' && !empty( $cms['config']['sitemap.mod.php']['domain'] ) ) {
        $domain = $cms['config']['sitemap.mod.php']['domain'];
    } else {
        $domain = $cms['url']['scheme'].'://'.$_SERVER['SERVER_NAME'];
    }

    $exclude = explode("\n", $cms['config']['sitemap.mod.php']['exclude']);

    $excluded_types = "'".implode("','", $cms['config']['sitemap.mod.php']['excluded_types'])."'";
    $content = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    $q = "SELECT title,url,created,modified FROM pages WHERE `created`<='".date('Y-m-d H:i:s')."' AND `type` NOT IN ($excluded_types) ORDER BY created DESC";
    if ( $res = mysqli_query( $cms['base'], $q ) ) {
        $links = array();
        while ( $page = mysqli_fetch_assoc( $res ) ) {
            if ( !empty( $page['url'] ) ) {
                $link = $domain.$page['url'];
                $modified = '';
                $created  = strtotime( $page['created'] );
                if ( $created > 0 and $modified = max( $created, (int)$page['modified'] ) ) {
                    $modified = '<lastmod>'.date( 'c', $modified ).'</lastmod>';
                }
                if (!in_array($page['url'], $exclude) && !in_array($link, $links)) {
                    $links[] = $link;
                    $content .= "<url><loc>{$link}</loc>{$modified}</url>";
                }
            }
        }
        $link = $domain.'/';
        if (!in_array($link, $links)) $links[] = $link;

    }
    foreach( explode("\n", $cms['config']['sitemap.mod.php']['include']) as $link ) {
        $link = trim($link);
        if ( !empty( $link ) ) {
            $content .= "<url><loc>{$link}</loc></url>";
        }
    }
    $content .= '</urlset>';
    return $content;
}


function cms_sitemap_admin() {
    global $cms;
    if ( !is_admin() ) return;
    // Save settings
    if ( !empty( $_POST['save_settings_sitemap'] ) ) {
        $list = preg_split("/\r\n|\n\r|\r|\n/", $_POST['exclude']);
        $site = $cms['url']['scheme'].'://'.$_SERVER['SERVER_NAME'];
        foreach ($list as $key => $value) {
            // Удаляем адрес сайта из ссылок
            $list[$key] = trim(str_replace($site, '', $value));
            if (empty($list[$key])) {
                unset($list[$key]);
            } else {
                if (substr($list[$key], 0, 1) !== '/') $list[$key] = '/'.$list[$key];
            }
        }
        $list = implode("\n", $list);
        $cms['config']['sitemap.mod.php']['gen'] = $_POST['gen'];
        $cms['config']['sitemap.mod.php']['exclude'] = $list;
        $cms['config']['sitemap.mod.php']['include'] = $_POST['include'];
        $cms['config']['sitemap.mod.php']['domain'] = rtrim( $_POST['domain'], '/' );
        $cms['config']['sitemap.mod.php']['update_interval'] = trim($_POST['update_interval']);
        cms_save_config();
        if ( $cms['config']['sitemap.mod.php']['gen'] === 'dynamic' ) {
            unlink( $cms['site_dir'].'/sitemap.xml' );
        }
        cms_sitemap_update();
        header('Location: ' . $cms["config"]["admin.mod.php"]["admin_url"]);
        exit;
    }

    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['sitemap.mod.php']['menu']['sitemap'] ) ) {
        $cms['config']['sitemap.mod.php']['menu']['sitemap'] = array(
            'title'    => 'Sitemap',
            'sort'     => 60,
            'class'    => '',
            'section'  => 'Settings',
        );
        cms_save_config();
    }

    $ch['static'] = '';
    $ch['dynamic'] = '';
    $ch[$cms['config']['sitemap.mod.php']['gen']] = 'checked';
    @$page = "
    <form method=post>
	<div class=xml-wrapper-grid>
		<div class=xml-wrapper-hidden>
			<h1>".__("Excluded links", 'sitemap.mod.php')."</h1>
			<textarea class=style-textarea-xml name=exclude rows=12>{$cms['config']['sitemap.mod.php']['exclude']}</textarea>
		</div>
		<div class=xml-wrapper-link>
			<h1>".__("Included links", 'sitemap.mod.php')."</h1>
			<textarea class=style-textarea-xml name=include rows=12>{$cms['config']['sitemap.mod.php']['include']}</textarea>
		</div>
		<div class='xml-static-dynamic'>
			<h1>".__('Rules for processing sitemap.xml file', 'sitemap.mod.php')."</h1>
			<p><label class=radio><input class=custom-control-input name=gen type=radio value=dynamic {$ch['dynamic']}> ".__('Dynamic generation', 'sitemap.mod.php')."<span class=radio-design></span></label></p>
            <p><label class=radio><input class=custom-control-input name=gen type=radio value=static {$ch['static']}> ".__('Static generation (recommended)', 'sitemap.mod.php')."<span class=radio-design></span></label></p>
            <h1>".__('Protocol and Domain for static map (leave empty for auto)*:', 'sitemap.mod.php')."</h1>
            <p><input type=text name=domain value='{$cms['config']['sitemap.mod.php']['domain']}' class='settingx domain' placeholder='http://example.com'></p>
			<button name=save_settings_sitemap value=1 class=button-save>".__('Save', 'sitemap.mod.php')."</button>
		</div>
		<div class='xml-static-cron'>
			<h1>".__('Frequency Recreate', 'sitemap.mod.php')."</h1>
            <p>".__('Static CRON generation at', 'sitemap.mod.php')." <input type=text name=update_interval value={$cms['config']['sitemap.mod.php']['update_interval']} class='settingx cron'> ".__('-minute intervals', 'sitemap.mod.php')."</p>
            <p>".__('This function works when CRON is on. Information on using CRON can be obtained from your hosting provider.', 'sitemap.mod.php')."</p>
		</div>
	</div>
	</form>
	<div class=info>
        <h1>".__("Help on sitemap.xml options", 'sitemap.mod.php')."</h1>
        <p>".__('If you don\'t need to do pending auto posts - you need to keep static generation. When you save the page or page properties, the site map is recreated.', 'sitemap.mod.php')."</p>
        <p>".__("If you have pending publications for the future, you can set the dynamic generation of the sitemap or static using the CRON scheduler.", 'sitemap.mod.php')." ".__("The CRON scheduler should poll the site at", 'sitemap.mod.php')." ".$cms['url']['scheme']."://".$_SERVER['SERVER_NAME']."/cron ".__("and thereby recreate the site map with the time interval you set.", 'sitemap.mod.php')."</p>
        <p>".__("We recommend using static generation to reduce server load.", 'sitemap.mod.php')."</p>
        <p>".__("* This option is needed if the site operates on two domains.", 'sitemap.mod.php')."</p>
    </div>
    ";

    $cms['admin_pages']['sitemap'] = $page;
}