<?php

$cms["modules"]["rss.mod.php"] = array(
    "name"        => __( "rss_module_name" ),
    "description" => __( "rss_module_description" ),
    "files"       => array(
        ".cms/mod/rss.mod.php",
        ".cms/js/rss.js",
        ".cms/css/rss.css",
        ".cms/lang/ru_RU.UTF-8/rss.mod.php",
        ".cms/lang/en_US.UTF-8/rss.mod.php",
        ".cms/lang/uk_UA.UTF-8/rss.mod.php",
    ),
);

// Return if module disabled
if ( ! empty( $cms["config"]["rss.mod.php"]["disabled"] ) ) {

    return;

} else {

    // Default Settings

    if ( empty( $cms["config"]["rss.mod.php"]["update_interval"] ) ) {
        $cms["config"]["rss.mod.php"]["update_interval"] = 60;
    }

    if ( empty( $cms["config"]["rss.mod.php"]["exclude"] ) ) {
        $cms["config"]["rss.mod.php"]["exclude"] = "";
    }

    if ( empty( $cms["config"]["rss.mod.php"]["gen"] ) ) {
        $cms["config"]["rss.mod.php"]["gen"] = "dynamic";
    }

    if ( empty( $cms["config"]["rss.mod.php"]["lastrun"] ) ) {
        $cms["config"]["rss.mod.php"]["lastrun"] = "";
    }

    if ( is_admin() ) {
        hook_add_fn( "admin",         "cms_rss_admin" );
        hook_add_fn( "admin_header",  "cms_rss_admin_header" );
    }

    if ( $cms["config"]["rss.mod.php"]["gen"] === "static" ) {
        hook_add_fn( "cron", "cms_rss_cron" );
    }
        
    $cms["urls"]["^{$cms['base_path']}rss.xml$"] = "rss.xml";
    hook_add_fn( "rss.xml", "cms_rss_xml" );

    // Количество элементов в ленте
    if ( empty( $cms["config"]["rss.mod.php"]["count"] ) ) {
        $cms["config"]["rss.mod.php"]["count"] = 30;
    }

}


function cms_rss_admin_header() {
    global $cms;
    $conf = @$cms["config"]["rss.mod.php"]["menu"]["rss"];
    if ( empty( $conf["hide"] ) && empty( $cms["config"]["admin_sections"][ $conf["section"] ]["hide"] ) ) {
        echo "<link rel=stylesheet href='{$cms['base_path']}css/rss.css'>";
        echo "<script src='{$cms['base_path']}js/rss.js'></script>";
    }
}


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


function cms_rss_xml() {
    global $cms;
    header( "Content-Type: application/xml;charset=UTF-8" );
    $rss = cms_rss_generate();
    echo $rss;
    if ( $cms["config"]["rss.mod.php"]["gen"] === "static" ) {
        file_put_contents( "{$cms['site_dir']}/rss.xml", $rss );
    }
}


function cms_rss_update() {
    global $cms;
    // disable remove file
    if ( ! empty( $cms["config"]["rss.mod.php"]["disabled"] ) ) {
        return;
    }

    $file = "{$cms['site_dir']}/rss.xml";
    if ( file_exists( $file ) ) unlink( $file );
}


function cms_rss_generate() {
    global $cms;
    if ( empty( $cms["base"] ) ) cms_base_connect();
    if ( empty( $cms["base"] ) ) return;
    if ( mysqli_connect_error() ) return;

    $domain = "{$cms['url']['scheme']}://{$cms['url']['host']}";

    $cms["rss"] = array();

    $exclude = explode( "\n", $cms["config"]["rss.mod.php"]["exclude"] );
    foreach( $exclude as $n => $link ) {
        $t = trim( $link );
        if ( empty( $t ) ) {
            // delete empty lines
            unset( $exclude[$n] );
        }
    }

    $channel_title = "";
    $channel_link = "";
    $channel_description = "";
    $date = date( "Y-m-d H:i:s" );
    $n = 0;
    $cms["rss_links"] = array();
    $q = "SELECT `title`, `seo_title`, `url`, `created`, `modified`, `description`, `text`, `published` FROM `pages` WHERE `created`<='{$date}' AND `published` ORDER BY `created` DESC";
    if ( $res = mysqli_query( $cms["base"], $q ) ) {
        while ( $page = mysqli_fetch_assoc( $res ) ) {
            if ( $page["url"] === "" ) {
                $channel_title = $page["title"];
                $channel_link = $domain . $cms["base_path"];
                $channel_description = $page["description"];
            }
            if ( ! in_array( $page["url"], $exclude ) && $n < $cms["config"]["rss.mod.php"]["count"] ) {
                $sort = max( strtotime( $page["created"] ), (int) $page["modified"] );
                $link = $domain . $cms["base_path"] . $page["url"];
                if ( ! isset( $cms["rss_links"][$link] ) ) {

                    // image
                    $enclosure = "";
                    if ( preg_match( '/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/us', $page['text'], $m ) ) {
                        $img = $m[1];
                        $img_file = $cms["site_dir"] . $img;
                        if ( is_file( $img_file ) ) {
                            $mime = mime_content_type( $img_file );
                            if ( substr( $img, 0, 4 ) !== "http" ) {
                                if ( substr( $img, 0, 1 ) === "/" ) $img = substr( $img, 1 );
                                $img = $domain . $cms["base_path"] . $img;
                            }
                            $enclosure = "<enclosure url='{$img}' type='{$mime}'/>";
                        }
                    }

                    if ( ! empty( $page["seo_title"] ) ) {
                        $page["title"] = $page["seo_title"];
                    }
                    $cms["rss_links"][$link] = true;
                    $cms["rss"][] = array(
                        "title"       => $page["title"],
                        "link"        => $link,
                        "description" => $page["description"],
                        "guid"        => "{$page['modified']}",
                        "sort"        => $sort,
                        "enclosure"   => $enclosure,
                    );
                    $n++;
                }
            }
        }
    }

    do_hook( "rss" );

    cms_asort( $cms["rss"] );
    $cms["rss"] = array_reverse( $cms["rss"] );

    $content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<rss version=\"2.0\">
    
    <channel>
        <title>{$channel_title}</title>
        <link>{$channel_link}</link>
        <description>{$channel_description}</description>\n";
    foreach( $cms["rss"] as $item ) {
        $content .= "        <item>
            <title>{$item['title']}</title>
            <link>{$item['link']}</link>
            <guid>{$item['guid']}</guid>
            <description>{$item['description']}</description>
            {$item['enclosure']}
        </item>\n";
    }
    $content .= "   </channel>\n</rss>";
    return $content;
}


function cms_rss_admin() {
    global $cms;

    $conf = @$cms["config"]["rss.mod.php"]["menu"]["rss"];
    if ( empty( $conf["hide"] ) && empty( $cms["config"]["admin_sections"][ $conf["section"] ]["hide"] ) ) {

    // Save settings
    if ( ! empty( $_POST["save_settings_rss"] ) ) {
        $list = preg_split( "/\r\n|\n\r|\r|\n/u", $_POST["exclude"] );
        $base_url = "{$cms['url']['scheme']}://{$cms['url']['host']}{$cms['base_path']}";
        foreach ( $list as $key => $value ) {
            // remove domain
            $list[$key] = trim( str_replace( $base_url, "", $value ) );
            if ( substr( $list[$key], 0, 1 ) === "/" ) $list[$key] = substr( $list[$key], 1 );
        }
        $list = implode( "\n", $list );
        $cms["config"]["rss.mod.php"]["gen"]             = $_POST["gen"];
        $cms["config"]["rss.mod.php"]["exclude"]         = $list;
        $cms["config"]["rss.mod.php"]["update_interval"] = (int) $_POST["update_interval"];
        $cms["config"]["rss.mod.php"]["count"]           = (int) $_POST["count"];
        cms_save_config();
        if ( $cms["config"]["rss.mod.php"]["gen"] === "dynamic" ) {
            unlink( "{$cms['site_dir']}/rss.xml" );
        }
        cms_rss_update();
        header( "Location: {$cms['base_path']}{$cms['config']['admin.mod.php']['admin_url']}" );
        exit;
    }

    // Create menu item if not exists
    if ( empty( $cms["config"]["rss.mod.php"]["menu"]["rss"] ) ) {
        $cms["config"]["rss.mod.php"]["menu"]["rss"] = array(
            "title"    => "rss_module_name",
            "sort"     => 65,
            "section"  => "settings",
        );
        cms_save_config();
    }

    $ch["static"] = "";
    $ch["dynamic"] = "";
    $ch[ $cms["config"]["rss.mod.php"]["gen"] ] = "checked";

    $rss = "{$cms['url']['scheme']}://{$cms['url']['host']}{$cms['base_path']}rss.xml";

    $page = "
<div class=rss>" . __( "view_rss" ) . " <a href='{$rss}' target=_blank>{$rss}</a></div>

<form method=post>

    <div class=xml-wrapper-hidden>
        <div>" . __( "excluded_links" ) . "</div>
        <textarea name=exclude rows=12 autocomplete=off>{$cms['config']['rss.mod.php']['exclude']}</textarea>
        <div class=save_2_col>
            <button name=save_settings_rss value=save>" . __( "save" ) . "</button>
                <div class=select-dropdown>
                    <div class=field-search>
                        <input class=search-field autocomplete=off placeholder='" . __( "placeholder" ) . "'>
                    </div>
                    <ul class=list-search>
                        
                    </ul>
                </div>
        </div>
    </div>

    <div class=xml-static-dynamic>
        <div>" . __( "rss_gen" ) . "</div>
        <label><input name=gen type=radio value=dynamic {$ch['dynamic']}> " . __( "dynamic" ) . "</label>
        <label><input name=gen type=radio value=static {$ch['static']}> " . __( "static" ) . "</label>
        <p>" . __( "rss_items_count" ) . ": <input type=text name=count value={$cms['config']['rss.mod.php']['count']}></p>
        <button name=save_settings_rss value=save>" . __( "save" ) . "</button>
    </div>
    <div class=xml-static-cron>
        <div>" . __( "update_freq" ) . "</div>
        <p>" . __( "static_freq" ) . " <input type=text name=update_interval value={$cms['config']['rss.mod.php']['update_interval']}> " . __( "minutes" ) . "</p>
        <p>" . __( "freq_help" ) . "</p>
        <p>" . __( "help_p3" ) . " {$cms['url']['scheme']}://{$cms['url']['host']}{$cms['base_path']}{$cms['config']['admin.mod.php']['cron_url']} " . __( "help_p4" ) . "</p>
        <button name=save_settings_rss value=save>" . __( "save" ) . "</button>
    </div>
</form>
    ";

    $cms["admin_pages"]["rss"] = $page;

    }

}
