<?php

namespace pictpostpersonal;

class RssFeed
{
    private $setting;


    function __construct(model\Setting $setting)
    {
        $this->setting = $setting;
    }


    /**
     * 最新10件のデータを含むRSSを作成する
     *
     * @param model\Article $article_model
     * 
     * @return void
     * 
     */
    function createFeed(model\Article $article_model): void
    {
        try {
            $articles = $article_model->search('hidden_at_list = false and status = 0 and [type] = 0', [], ['created_at desc'], 10, 1);
            foreach ($articles as $index => $article) {
                if ($index == 0) {
                    //サイト情報の出力
                    $atom = new \AtomFeed(['xmlns:ppp' => 'https://ppp.kannagi.net/ppp-namespace', 'xml:lang' => 'ja']);
                    $atom->title($this->setting->getValue('site_title', ''));
                    $atom->link(SITE_URL, 'alternate', 'text/html', 'url');
                    $atom->link(SITE_URL . '/atom.xml', 'self');
                    $atom->id(SITE_URL . '/atom.xml');

                    $atom->updated($article['created_at']); //1件目の記事の日時

                    $atom->author([
                        'name' => $this->setting->getValue('display_name', '')
                    ]);
                    $atom->addCustomElement('ppp:nsfw', $this->setting->getValue('nsfw', ''));
                    $atom->addCustomElement('ppp:description', h($this->setting->getValue('twitter_card_text', '')));
                    $atom->addCustomElement('ppp:site_tags', h($this->setting->getValue('portal_tags', '')));
                }

                //記事情報の出力
                $entry = new \AtomEntry();
                $entry->title($article['title']);
                $entry->link(SITE_URL . Environment::getLogUrl($article), 'alternate', 'text/html', 'url');
                $entry->id(SITE_URL . Environment::getLogUrl($article));
                $entry->addCustomElement('ppp:nsfw', $article['nsfw']);
                $entry->addCustomElement('ppp:tags', htmlspecialchars(trim($article['tags'])));
                $entry->addCustomElement('ppp:images', htmlspecialchars($article['media_count']));

                $summary = '';
                if ($article['contents'] && $article['contents'] != '') {
                    $summary = Utility::createCaption($article['contents']);
                } else {
                    $summary = $article['title'];
                }
                $entry->summary($summary);

                if ($article['media_count'] > 0) {
                    $entry->link(Utility::getThumbnailUrl($article, false), 'related', 'image/jpeg', 'thumbnail');
                }

                $entry->updated($article['created_at']);
                $entry->author([
                    'name' => $this->setting->getValue('display_name', '')
                ]);
                $atom->addEntry($entry);
            }
            $file_name = './atom.xml';
            if ($index > 0) {
                file_put_contents($file_name, $atom->saveXml());
            }
        } catch (\Exception $ex) {
            exit;
        }
    }

    /**
     * ポータル送信用ATOMを生成（非送信タグの記事を含まない）
     *
     * @param model\Article $article_model
     * 
     * @return void
     * 
     */
    function createPortalFeed(model\Article $article_model): void
    {
        try {
            //送信タグ一覧
            $select_tags = explode(' ', $this->setting->getValue('portal_post_tags', ''));
            $tag_select = '';
            if ($this->setting->getValue('portal_post_tags', '')) {
                foreach ($select_tags as $tag) {
                    $tag_select = $tag_select .  ' or tags like \'% ' . h($tag) . ' %\' or tags like \'% -' . h($tag) . ' %\'';
                }
                $tag_select = ' and ( ' . substr($tag_select, 4) . ' )';
            }

            //非送信タグ一覧
            $exclude_portal_post_tags = explode(' ', $this->setting->getValue('exclude_portal_post_tags', ''));
            $tag_exclude = '';
            if ($this->setting->getValue('exclude_portal_post_tags', '')) {
                foreach ($exclude_portal_post_tags  as $tag) {
                    $tag_exclude = $tag_exclude .  ' or tags not like \'% ' . h($tag) . ' %\' or tags not like \'% -' . h($tag) . ' %\'';
                }
                $tag_exclude = ' and ( ' . substr($tag_exclude, 4) . ' )';
            }
            $tag_select_exist = '';
            if ($tag_exclude !== '' && $tag_select !== '') {
                $tag_select_exist = 'and';
            }
            $articles = $article_model->search("hidden_at_list = false and status = 0 and [type] = 0] {$tag_select_exist} {$tag_select} {$tag_exclude} ", [], ['created_at desc'], 10, 1);

            foreach ($articles as $index => $article) {
                if ($index == 0) {
                    //サイト情報の出力
                    $atom = new \AtomFeed(['xmlns:ppp' => 'https://ppp.kannagi.net/ppp-namespace', 'xml:lang' => 'ja']);
                    $atom->title($this->setting->getValue('site_title', ''));
                    $atom->link(SITE_URL, 'alternate', 'text/html', 'url');
                    $atom->link(SITE_URL . '/atom.xml', 'self');
                    $atom->id(SITE_URL . '/atom.xml');

                    $atom->updated($article['created_at']); //1件目の記事の日時

                    $atom->author([
                        'name' => $this->setting->getValue('display_name', '')
                    ]);
                    $atom->addCustomElement('ppp:nsfw', $this->setting->getValue('nsfw', ''));
                    $atom->addCustomElement('ppp:description', h($this->setting->getValue('twitter_card_text', '')));
                    $atom->addCustomElement('ppp:site_tags', h($this->setting->getValue('portal_tags', '')));
                }

                //記事情報の出力
                $entry = new \AtomEntry();
                $entry->title($article['title']);
                $entry->link(SITE_URL . Environment::getLogUrl($article), 'alternate', 'text/html', 'url');
                $entry->id(SITE_URL . '/view.php?id=' . $article['id']);
                $entry->addCustomElement('ppp:nsfw', $article['nsfw']);
                $entry->addCustomElement('ppp:tags', htmlspecialchars(trim($article['tags'])));
                $entry->addCustomElement('ppp:images', htmlspecialchars($article['media_count']));

                $summary = '';
                if ($article['contents'] && $article['contents'] != '') {
                    $summary = Utility::createCaption($article['contents']);
                } else {
                    $summary = $article['title'];
                }
                $entry->summary($summary);

                if ($article['media_count'] > 0) {
                    $entry->link(Utility::getThumbnailUrl($article, false), 'related', 'image/jpeg', 'thumbnail');
                }

                $entry->updated($article['created_at']);
                $entry->author([
                    'name' => $this->setting->getValue('display_name', '')
                ]);
                $atom->addEntry($entry);
            }
            $file_name = './portal.xml';
            if ($index > 0) {
                file_put_contents($file_name, $atom->saveXml());
            }
        } catch (\Exception $ex) {
            exit;
        }
    }

    function sendRequest($article_model)
    {
        try {
            $this->createPortalFeed($article_model);

            // POSTするデータ
            $post_data = array(
                'feed_url' => SITE_URL . '/portal.xml'
            );
            $url_origin = $this->setting->getValue('portal_feed_urls', '') ?? 'https://ppp.kannagi.net/portal/index.php';
            if ($url_origin == '') {
                $url_origin = 'https://ppp.kannagi.net/portal/index.php';
            }
            $urls = explode(',', $url_origin);
            foreach ($urls as $url) {
                // cURLを初期化して設定
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_data));
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                // リクエストを実行してレスポンスを取得
                $response = curl_exec($curl);
            }
            // cURLを終了
            curl_close($curl);
        } catch (\Exception $ex) {
            return;
        }
    }
    function removeRequest($id)
    {
        $atom = new \AtomFeed(['xmlns:ppp' => 'https://ppp.kannagi.net/ppp-namespace', 'xml:lang' => 'ja']);
        $atom->title($this->setting->getValue('site_title', ''));
        $atom->link(SITE_URL, 'alternate', 'text/html', 'url');
        $atom->link(SITE_URL . '/remove_request.xml', 'self');
        $atom->id(SITE_URL . '/remove_request.xml');
        $atom->author([
            'name' => $this->setting->getValue('display_name', '')
        ]);
        if ($id == 'ALL') {
            //IDとして"ALL"が渡された場合はサイト情報自体を削除
            $atom->addCustomElement('ppp:request', 'remove_site');
        } else {
            $atom->addCustomElement('ppp:request', 'remove_feed');
        }
        $entry = new \AtomEntry();
        $entry->id(SITE_URL . '/view.php?id=' . $id);
        $atom->addEntry($entry);
        $file_name = './remove_request.xml';
        file_put_contents($file_name, $atom->saveXml());

        try {
            if ($this->setting->getValue('use_portal_feed', '')) {
                // POSTするデータ
                $post_data = array(
                    'remove_request_url' => SITE_URL . '/remove_request.xml'
                );
                $urls = explode(',', $this->setting->getValue('portal_feed_urls', ''));
                if ($urls == '') {
                    $urls = 'https://ppp.kannagi.net/portal/index.php';
                }
                foreach ($urls as $url) {
                    // cURLを初期化して設定
                    $curl = curl_init();
                    curl_setopt($curl, CURLOPT_URL, $url);
                    curl_setopt($curl, CURLOPT_POST, true);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_data));
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

                    // リクエストを実行してレスポンスを取得
                    $response = curl_exec($curl);
                }
                // cURLを終了
                curl_close($curl);
            }
        } catch (\Exception $ex) {
            exit;
        }
    }
}
