<?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.less",
        ".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" );
        hook_add_fn( "api",           "cms_rss_api", 20 );
    }

    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;
    if ( is_admin_header_on( "rss.mod.php" ) ) {
        echo "        <link rel=stylesheet href='{$cms["base_path"]}css/rss.css'>\n";
        echo "        <script src='{$cms["base_path"]}js/rss.js'></script>\n";
    }
}


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["pdo"] ) ) {
        cms_base_connect();
    }
    if ( empty( $cms["pdo"] ) ) {
        return;
    }

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

    $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();
    // Исключить только что созданные.
    // Сортировать по созданию, но измененные вылезут в ленте - изменится guid
    $query = "SELECT title, seo_title, url, created, modified, description, text, published FROM pages WHERE created <= ? AND published AND modified != created";
    
    try {
        $stmt = $cms["pdo"]->prepare( $query );
        $stmt->execute( array( $date ) );

        while ( $page = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
            if ( $page["url"] === "" ) {
                $channel_title = htmlspecialchars( $page["title"], ENT_XML1 );
                $channel_link = htmlspecialchars( $domain . $cms["base_path"], ENT_XML1 );
                $channel_description = htmlspecialchars( $page["description"], ENT_XML1 );
            }
            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;
                            }
                            $img_escaped = htmlspecialchars($img, ENT_XML1);
                            $enclosure = "<enclosure url='{$img_escaped}' type='{$mime}'/>";
                        }
                    }

                    if ( ! empty( $page["seo_title"] ) ) {
                        $page["title"] = $page["seo_title"];
                    }
                    $cms["rss_links"][$link] = true;
                    $cms["rss"][] = array(
                        "title"       => htmlspecialchars( $page["title"], ENT_XML1 ),
                        "link"        => htmlspecialchars( $link, ENT_XML1 ),
                        "description" => htmlspecialchars( $page["description"], ENT_XML1 ),
                        "guid"        => "{$page['modified']}",
                        "sort"        => $sort,
                        "enclosure"   => $enclosure,
                    );
                    $n++;
                }
            }
        }
    } catch ( PDOException $e ) {
        error_log( "RSS generation failed: " . $e->getMessage() );
        return "";
    }

    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>";
    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>";
    }
    $content .= "
   </channel>
</rss>";
    return $content;
}


function cms_rss_admin() {
    global $cms;
    if ( is_admin_header_on( "rss.mod.php" ) ) {

    // 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['url']['port']}{$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();
        $cms["status"] = "302";
        $cms["status_302_location"] = $cms["base_path"] . $cms["config"]["admin.mod.php"]["admin_url"];
        return;
    }

    // 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['url']['port']}{$cms['base_path']}rss.xml";

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

<form method=post>

    <div class='links panel'>
        <div class=title>" . __( "excluded_links" ) . "</div>
        <textarea name=exclude rows=12 autocomplete=off>{$cms['config']['rss.mod.php']['exclude']}</textarea>
        <div class=controls>
            <div class='dropdown autoinput'>
                <input type=search name=search class=search-field autocomplete=off placeholder='" . __( "placeholder" ) . "'>
                <div class=options>
                    
                </div>
            </div>
            <button class=button name=save_settings_rss value=save>
                <span>" . __( "save" ) . "</span>
            </button>
        </div>
    </div>

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

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

    }

}


function cms_rss_api() {
    global $cms;
    if ( empty( $cms["pdo"] ) ) {
        return;
    }
    
    if ( ! empty( $_POST["fn"] ) ) {
        switch ( $_POST["fn"] ) {
            case "rss_pages_list":
                $s = preg_replace( "/\s/u", "", $_POST["search"] );
                $s = preg_split( '//u', $s, -1, PREG_SPLIT_NO_EMPTY );
                $s = implode( "%", $s );
                $search_param = "%{$s}%";

                // Список страниц
                $q = "SELECT id, title, url, pin
                      FROM pages 
                      WHERE ( title LIKE ? OR url LIKE ? )
                            AND url != ''
                      ORDER BY pin DESC, modified DESC
                      LIMIT 100";
                $li_arr = array();

                try {
                    $stmt = $cms["pdo"]->prepare( $q );
                    $stmt->execute( array( $search_param, $search_param ) );
                    while ( $page = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
                        $title = htmlspecialchars( $page["title"] );
                        $li_arr[] = "<div class=option data-id={$page['id']} data-url='{$page['url']}'>{$title}</div>";
                    }
                } catch ( PDOException $e ) {
                    error_log( "RSS pages list failed: " . $e->getMessage() );
                    // Return empty list on error
                }

                // Хук для других модулей если хотят пополнить список
                // $cms["menu.mod.php"]["s"] = $s;
                // $cms["menu.mod.php"]["pages_list"] = &$html;
                // do_hook( "mod_menu_pages_for_selector" );
                // Передавать через параметры хука

                echo( json_encode( array( "result" => array( "html" => implode( "", $li_arr ), ) ) ) );

            break;
        }
    }
}