<?php
/*
Plugin Name: 工具箱
Version: 0.3
Plugin URL: https://www.emlog.net/plugin/detail/622
Description: 一些emlog系统常用的工具
Author: emlog
Author URL: https://www.emlog.net/plugin/index/author/577
*/

!defined('EMLOG_ROOT') && exit('access denied!');

class EmToolKit
{

    //插件标识
    const ID = 'em_toolkit';
    const NAME = '工具箱';

    //实例
    private static $_instance;

    //数据库连接实例
    private $_db;

    //是否初始化
    private $_inited = false;

    /**
     * 单例入口
     * @return EmToolKit
     */
    public static function getInstance()
    {
        if (self::$_instance === null) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 私有构造函数，保证单例
     */
    private function __construct() {}

    public function init()
    {
        if ($this->_inited === true) {
            return;
        }
        $this->_inited = true;

        addAction('index_head', function () {
            echo EmToolKit::getInstance()->getHeadCode();
        });
        addAction('index_footer', function () {
            echo EmToolKit::getInstance()->getFooterCode();
        });
    }

    /**
     * 获取数据表
     */
    public function getTable($table = null)
    {
        return DB_PREFIX . $table;
    }

    /**
     * 获取数据库连接
     */
    public function getDb()
    {
        if ($this->_db !== null) {
            return $this->_db;
        }
        $this->_db = Database::getInstance();
        return $this->_db;
    }

    public function importMarkdowns($md_files)
    {
        $success = 0;
        $fail = 0;
        // 引入Log_Model
        if (!class_exists('Log_Model')) {
            include_once EMLOG_ROOT . '/admin/model/log_model.php';
        }
        $CACHE = Cache::getInstance();
        $Log_Model = new Log_Model();

        for ($i = 0; $i < count($md_files['tmp_name']); $i++) {
            $tmp_name = $md_files['tmp_name'][$i];
            $name = $md_files['name'][$i];
            if (!$tmp_name || strtolower(pathinfo($name, PATHINFO_EXTENSION)) !== 'md') {
                $fail++;
                continue;
            }
            $content = file_get_contents($tmp_name);
            if (!$content) {
                $fail++;
                continue;
            }
            // 解析YAML元数据
            $meta = [
                'title' => pathinfo($name, PATHINFO_FILENAME),
                'date' => time(),
            ];
            if (preg_match('/^---\s*(.*?)\s*---\s*(.*)$/s', $content, $matches)) {
                $yaml = $matches[1];
                $body = $matches[2];
                $meta = array_merge($meta, $this->parseYamlMeta($yaml));
                $content = $body;
            }

            $title = str_replace(['"', "'"], '', $meta['title']);
            $date = is_numeric($meta['date']) ? $meta['date'] : strtotime($meta['date']);
            $excerpt = ''; // 可根据需要自动生成摘要
            $logData = [
                'title'   => extractHtmlData(trim($title, "*#"), 120),
                'content' => $content,
                'excerpt' => $excerpt,
                'author'  => 1,
                'sortid'  => -1,
                'cover'   => '',
                'date'    => $date,
                'hide'    => 'n',
            ];
            $Log_Model->addlog($logData);
            $CACHE->updateArticleCache();
            $success++;
        }
        emMsg("导入完成，成功：$success 篇，失败：$fail 篇", "./plugin.php?plugin=em_toolkit");
    }

    private function parseYamlMeta($yaml)
    {
        $meta = [];
        if (preg_match_all('/^([a-zA-Z0-9_]+):\s*(.*)$/m', $yaml, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $m) {
                $key = strtolower(trim($m[1]));
                $val = trim($m[2]);
                // 处理数组格式
                if (preg_match('/^\[(.*?)\]$/', $val, $arrMatch)) {
                    $arr = array_map('trim', explode(',', $arrMatch[1]));
                    $meta[$key] = $arr;
                } else {
                    $meta[$key] = $val;
                }
            }
        }
        return $meta;
    }

    private function getOrCreateCategory($catName)
    {
        $catName = addslashes($catName);
        $query = $this->getDb()->query("SELECT sid FROM " . DB_PREFIX . "sort WHERE sortname='$catName' LIMIT 1");
        $row = $this->getDb()->fetch_array($query);
        if ($row && isset($row['sid'])) {
            return (int)$row['sid'];
        }
        $this->getDb()->query("INSERT INTO " . DB_PREFIX . "sort (sortname,taxis,description) VALUES ('$catName',0,'')");
        return (int)$this->getDb()->insert_id();
    }

    public function changeDomain($oldDomain, $newDomain)
    {
        if (!$this->isValidUrl($oldDomain)) {
            Output::error('地址格式错误，域名只能由字母、数字和短横线组成');
        }
        if (!$this->isValidUrl($newDomain)) {
            Output::error('站点地址格式错误，域名只能由字母、数字和短横线组成');
        }

        // 去除地址最后的 /
        if (substr($oldDomain, strlen($oldDomain) - 1, 1) == '/') {
            $oldDomain = strtolower(substr($oldDomain, 0, strlen($oldDomain) - 1));
        }
        if (substr($newDomain, strlen($newDomain) - 1, 1) == '/') {
            $newDomain = strtolower(substr($newDomain, 0, strlen($newDomain) - 1));
        }
        $sql = 'UPDATE ' . DB_PREFIX . "blog SET content = replace(content,'$oldDomain','$newDomain'), excerpt = replace(excerpt,'$oldDomain','$newDomain'), cover = replace(cover,'$oldDomain','$newDomain')";
        $this->getDb()->query($sql);
        $sql = 'UPDATE ' . DB_PREFIX . "options SET option_value = '$newDomain/' WHERE option_name = 'blogurl'";
        $this->getDb()->query($sql);
        $CACHE = Cache::getInstance();
        $CACHE->updateCache();
        Output::ok('站点域名更换成功!');
    }

    function repairTables()
    {
        $db = MySqlii::getInstance();
        $tables = $db->listTables();
        $msg = '';
        foreach ($tables as $table) {
            if (empty($table)) {
                continue;
            }
            if (!empty($table)) {
                $db->query('REPAIR TABLE `' . $table . '`');
                $msg .= '数据表: ' . $table . ' 修复完成<br>';
            }
        }

        $tables = [
            'attachment' => [
                "aid int unsigned NOT NULL AUTO_INCREMENT comment '资源文件表' primary key",
                "alias varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL default '' comment '资源别名'",
                "author int unsigned NOT NULL default '1' comment '作者UID'",
                "sortid int NOT NULL default '0' comment '分类ID'",
                "blogid int unsigned NOT NULL default '0' comment '文章ID（已废弃）'",
                "filename varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL default '' comment '文件名'",
                "filesize int NOT NULL default '0' comment '文件大小'",
                "filepath varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL default '' comment '文件路径'",
                "addtime bigint NOT NULL default '0' comment '创建时间'",
                "width int NOT NULL default '0' comment '图片宽度'",
                "height int NOT NULL default '0' comment '图片高度'",
                "mimetype varchar(40) COLLATE utf8mb4_unicode_ci NOT NULL default '' comment '文件mime类型'",
                "thumfor int NOT NULL default '0' comment '缩略图的原资源ID（已废弃）'",
                "download_count bigint unsigned NOT NULL default 0 comment '下载次数'",
                "key thum_uid (thumfor, author)",
                "key addtime (addtime)",
            ],
            'comment'    => [
                "cid int unsigned NOT NULL AUTO_INCREMENT comment '评论表' primary key",
                "gid int unsigned NOT NULL DEFAULT '0' comment '文章ID'",
                "pid int unsigned NOT NULL DEFAULT '0' comment '父级评论ID'",
                "top enum('n', 'y') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'n' comment '置顶'",
                "poster varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' comment '发布人昵称'",
                "avatar varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' comment '头像URL'",
                "uid int NOT NULL DEFAULT '0' comment '发布人UID'",
                "comment text COLLATE utf8mb4_unicode_ci NOT NULL comment '评论内容'",
                "mail varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' comment 'email'",
                "url varchar(75) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' comment 'homepage'",
                "ip varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' comment 'ip address'",
                "agent varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' comment 'user agent'",
                "hide enum('n', 'y') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'n' comment '是否审核'",
                "like_count int unsigned NOT NULL DEFAULT '0' COMMENT '点赞量'",
                "date bigint NOT NULL comment '创建时间'",
                "KEY `gid` (`gid`), KEY `date` (`date`), KEY `hide` (`hide`)",
            ],
            'sort'       => [
                "sid int unsigned NOT NULL AUTO_INCREMENT comment '分类表' primary key",
                "sortname varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL default '' comment '分类名'",
                "alias varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL default '' comment '别名'",
                "taxis int unsigned NOT NULL default '0' comment '排序序号'",
                "pid int unsigned NOT NULL default '0' comment '父分类ID'",
                "description text COLLATE utf8mb4_unicode_ci NOT NULL comment '备注'",
                "kw varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL default '' comment '关键词'",
                "title varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL default '' comment '页面标题'",
                "template varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL default '' comment '分类模板'",
                "sortimg varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL default '' comment '分类图像'",
                "page_count int unsigned NOT NULL default '0' comment '每页文章数量'",
            ],
            'user'       => [
                "uid int(11) unsigned NOT NULL auto_increment comment '用户表' primary key",
                "username varchar(32) NOT NULL default '' comment '用户名'",
                "password varchar(64) NOT NULL default '' comment '用户密码'",
                "nickname varchar(20) NOT NULL default '' comment '昵称'",
                "role varchar(60) NOT NULL default '' comment '用户组'",
                "ischeck enum('n', 'y') NOT NULL default 'n' comment '内容是否需要管理员审核'",
                "photo varchar(255) NOT NULL default '' comment '头像'",
                "email varchar(60) NOT NULL default '' comment '邮箱'",
                "description varchar(255) NOT NULL default '' comment '备注'",
                "ip varchar(128) NOT NULL default '' comment 'ip地址'",
                "state tinyint(4) NOT NULL default '0' comment '用户状态 0正常 1禁用'",
                "credits int(11) unsigned NOT NULL default '0' comment '用户积分'",
                "create_time int(11) NOT NULL comment '创建时间'",
                "update_time int(11) NOT NULL comment '更新时间'",
            ],
            'twitter'    => [
                "id int NOT NULL AUTO_INCREMENT COMMENT '微语笔记表' primary key",
                "content text COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '微语内容'",
                "img varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '图片'",
                "author int NOT NULL DEFAULT '1' COMMENT '作者UID'",
                "date bigint NOT NULL COMMENT '创建时间'",
                "replynum int unsigned NOT NULL DEFAULT '0' COMMENT '回复数量'",
                "private enum('n', 'y') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'n' COMMENT '是否私密'",
                "key author (author)",
            ],
            'link'       => [
                "id int unsigned NOT NULL AUTO_INCREMENT COMMENT '链接表' primary key",
                "sitename varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '名称'",
                "siteurl varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '地址'",
                "icon varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '图标URL'",
                "description varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '备注信息'",
                "hide enum('n', 'y') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'n' COMMENT '是否隐藏'",
                "taxis int unsigned NOT NULL DEFAULT '0' COMMENT '排序序号'",
            ],
            'blog'       => [
                "gid int unsigned NOT NULL AUTO_INCREMENT COMMENT '文章表' primary key",
                "title varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '文章标题'",
                "date bigint NOT NULL COMMENT '发布时间'",
                "content longtext COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '文章内容'",
                "excerpt longtext COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '文章摘要'",
                "cover varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '封面图'",
                "alias varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '文章别名'",
                "author int NOT NULL DEFAULT '1' COMMENT '作者UID'",
                "sortid int NOT NULL DEFAULT '-1' COMMENT '分类ID'",
                "type varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'blog' COMMENT '文章OR页面'",
                "views int unsigned NOT NULL DEFAULT '0' COMMENT '阅读量'",
                "comnum int unsigned NOT NULL DEFAULT '0' COMMENT '评论数量'",
                "like_count int unsigned NOT NULL DEFAULT '0' COMMENT '点赞量'",
                "attnum int unsigned NOT NULL DEFAULT '0' COMMENT '附件数量（已废弃）'",
                "top enum('n', 'y') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'n' COMMENT '置顶'",
                "sortop enum('n', 'y') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'n' COMMENT '分类置顶'",
                "hide enum('n', 'y') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'n' COMMENT '草稿y'",
                "checked enum('n', 'y') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'y' COMMENT '文章是否审核'",
                "allow_remark enum('n', 'y') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'y' COMMENT '允许评论y'",
                "password varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '访问密码'",
                "template varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '模板'",
                "tags text COLLATE utf8mb4_unicode_ci COMMENT '标签'",
                "link varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '文章跳转链接'",
                "feedback varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT 'audit feedback'",
                "parent_id bigint unsigned NOT NULL DEFAULT '0' COMMENT '文章层级关系-父级ID'",
                "KEY author (author)",
                "KEY views (views)",
                "KEY comnum (comnum)",
                "KEY sortid (sortid)",
                "KEY top (top, date)",
                "KEY date (date)",
            ],
            'tag'        => [
                "tid int unsigned NOT NULL AUTO_INCREMENT COMMENT '标签表' primary key",
                "tagname varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '标签名'",
                "description varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '页面描述'",
                "title varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '页面标题'",
                "kw varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '关键词'",
                "gid text COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '文章ID'",
                "KEY tagname (tagname)",
            ],
            'like'        => [
                "id int unsigned NOT NULL AUTO_INCREMENT COMMENT '点赞表' primary key",
                "gid int unsigned NOT NULL DEFAULT '0' COMMENT '文章ID'",
                "poster varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '昵称'",
                "avatar varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '头像URL'",
                "uid int NOT NULL DEFAULT '0'",
                "ip varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT ''",
                "agent varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT ''",
                "date bigint NOT NULL",
                "KEY gid (gid)",
                "KEY date (date)",
            ],
            'order'       => [
                "id bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '订单表' primary key",
                "app_name varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '应用英文别名'",
                "order_id varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '订单编号'",
                "order_uid int unsigned NOT NULL COMMENT '用户id'",
                "out_trade_no varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '支付平台流水号'",
                "pay_type varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '支付方式（alipay/wechat）'",
                "sku_name varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '商品类型'",
                "sku_id int NOT NULL",
                "price decimal(10, 2) NOT NULL COMMENT '应付金额'",
                "pay_price decimal(10, 2) DEFAULT '0.00' COMMENT '实付金额'",
                "refund_amount decimal(10, 2) NOT NULL DEFAULT '0.00' COMMENT '退款金额'",
                "update_time int unsigned NOT NULL COMMENT '更新时间'",
                "create_time int unsigned NOT NULL COMMENT '创建时间'",
                "UNIQUE KEY `order_id` (`order_id`)",
                "KEY `idx_uid_ctime` (`order_uid`, `create_time`)",
                "KEY `idx_ctime` (`create_time`)",
            ],
        ];

        foreach ($tables as $table => $fields) {
            $tableName = DB_PREFIX . $table;
            $sql = "CREATE TABLE IF NOT EXISTS $tableName (";
            $lastField = end($fields);
            foreach ($fields as $field) {
                if ($field === $lastField) {
                    $sql .= "$field \n";
                } else {
                    $sql .= "$field, \n";
                }
            }
            $sql .= ')';
            $db->query($sql, true);
            foreach ($fields as $field) {
                $alterQuery = "ALTER TABLE $tableName ADD COLUMN $field";
                @$db->query($alterQuery, true);
            }
        }
        Output::ok($msg);
    }

    public function importCode($headerCode, $footerCode)
    {
        $plugin_storage = Storage::getInstance(self::ID);
        $plugin_storage->setValue('header_code', $headerCode);
        $plugin_storage->setValue('footer_code', $footerCode);
        Output::ok('代码导入成功!');
    }

    function resetCookie()
    {
        $PHPASS = new PasswordHash(8, true);
        $newAuthKey = $PHPASS->HashPassword(getRandStr(32) . md5(getIp()) . getUA() . microtime());
        $newAuthCookieName = 'EM_AUTHCOOKIE_' . sha1(getRandStr(32, false) . md5(getIp()) . getUA() . microtime());

        $configContent = file_get_contents(EMLOG_ROOT . '/config.php');
        $configContent = preg_replace("/const AUTH_KEY = '.*';/", "const AUTH_KEY = '$newAuthKey';", $configContent);
        $configContent = preg_replace("/const AUTH_COOKIE_NAME = '.*';/", "const AUTH_COOKIE_NAME = '$newAuthCookieName';", $configContent);

        if (!file_put_contents(EMLOG_ROOT . '/config.php', $configContent)) {
            Output::error('无法更新配置文件，请检查文件权限。');
        } else {
            Output::ok('已重置成功🎉，请 <a href="./">重新登录</a>');
        }
    }

    public function getHeadCode()
    {
        $plugin_storage = Storage::getInstance(self::ID);
        $header_code = $plugin_storage->getValue('header_code');
        return stripslashes($header_code);
    }

    public function getFooterCode()
    {
        $plugin_storage = Storage::getInstance(self::ID);
        $footer_code = $plugin_storage->getValue('footer_code');
        return stripslashes($footer_code);
    }

    private function isValidUrl($url)
    {
        // 使用filter_var函数验证URL格式
        if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
            // 检查URL是否以http或https开头
            if (strpos($url, 'http://') === 0 || strpos($url, 'https://') === 0) {
                return true;
            }
        }
        return false;
    }

    function rssImport($rssFile)
    {
        // 增加程序的最大执行时间
        ini_set('max_execution_time', '600');
        $items = array();
        $rss = new rss_php;

        if (empty($rssFile)) {
            emMsg('导入失败，未读取到文件');
        }

        $rss->loadFromUrl($rssFile);
        $items = $rss->getItems();
        if (empty($items)) {
            emMsg('导入失败，RSS数据未读取到');
        }

        // 分类缓存
        $categorycache = array();
        $query = $this->getDb()->query('SELECT sid,sortname FROM ' . DB_PREFIX . 'sort');
        while ($row = $this->getDb()->fetch_array($query)) {
            $categorycache[$row['sid']] = $row['sortname'];
        }
        // 用户缓存
        $usercache = array();
        $query = $this->getDb()->query('SELECT uid,username FROM ' . DB_PREFIX . 'user');
        while ($row = $this->getDb()->fetch_array($query)) {
            $usercache[$row['uid']] = $row['username'];
        }

        foreach ($items as $key => $item) {
            // 标题
            if (isset($item['title'])) {
                $title = addslashes($item['title']);
            }
            // 内容
            if (isset($item['description'])) {
                $content = addslashes($item['description']);
            }

            // wordpress
            if (isset($item['description'])) {
                $excerpt = addslashes($item['description']);
            }
            if (isset($item['content:encoded'])) {
                $content = addslashes($item['content:encoded']);
            }

            // 分类
            $sortid = -1;
            if (isset($item['category'])) {
                // 多个分类默认取第一个
                if (is_array($item['category'])) {
                    $category = $item['category'][0];
                }

                if (is_string($item['category'])) {
                    $category = $item['category'];
                }
                // 判断该分类是否已经添加了
                if (in_array($category, $categorycache)) {
                    $sortid = array_search($category, $categorycache);
                    if (empty($sortid)) {
                        $sortid = -1;
                    }
                } else {
                    // 自动增加分类
                    $sql = 'INSERT INTO ' . DB_PREFIX . "sort (sortname,taxis,description) VALUES ('$category',0,'')";
                    $this->getDb()->query($sql);
                    $tmpid = (string)$this->getDb()->insert_id();
                    // 增加到分类缓存中
                    $categorycache[$tmpid] = $category;
                    $sortid = $tmpid;
                }
            }
            // 发布时间
            if (isset($item['pubDate'])) {
                $date = strtotime($item['pubDate']);
            }
            // 发布人
            $useid = array_keys($usercache);
            $author = $useid[0];

            $sql = 'INSERT INTO ' . DB_PREFIX . "blog (title, date, content, excerpt, author, sortid, type, views, comnum, attnum, top, hide, allow_remark, password) VALUES ('$title', '$date', '$content', '$excerpt', $author, $sortid,'blog',0,0,0,'n','n','y','')";
            $this->getDb()->query($sql);
        }
        emDirect("./plugin.php?plugin=em_toolkit&rss_ok=1");
    }
}

/*
	RSS_PHP - the PHP DOM based RSS Parser
	Author: <rssphp.net>
	Published: 200801 :: blacknet :: via rssphp.net

	RSS_PHP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.

	Usage:
		See the documentation at http://rssphp.net/documentation
	Examples:
		Can be found online at http://rssphp.net/examples
*/

class rss_php
{

    public $document;
    public $channel;
    public $items;

    # load RSS by URL
    public function loadFromUrl($rssFile)
    {
        if ($rssFile) {
            $content = file_get_contents($rssFile);
            $content = strip_invalid_xml_chars2($content);
            $this->loadParser($content);
        }
    }

    private function fetchUrlContent($url)
    {
        $ch = curl_init($url);

        // Set cURL options
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // You may want to handle SSL verification better in production
        // Add any other cURL options you need...

        $content = curl_exec($ch);

        if ($content === false) {
            // Handle cURL error
            throw new Exception('cURL error: ' . curl_error($ch));
        }

        curl_close($ch);

        return $content;
    }

    # load raw RSS data
    public function loadRSS($rawxml = false)
    {
        if ($rawxml) {
            $this->loadParser($rawxml);
        }
    }

    # return full rss array
    public function getRSS($includeAttributes = false)
    {
        if ($includeAttributes) {
            return $this->document;
        }
        return $this->valueReturner();
    }

    # return channel data
    public function getChannel($includeAttributes = false)
    {
        if ($includeAttributes) {
            return $this->channel;
        }
        return $this->valueReturner($this->channel);
    }

    # return rss items
    public function getItems($includeAttributes = false)
    {
        if ($includeAttributes) {
            return $this->items;
        }
        return $this->valueReturner($this->items);
    }


    private function loadParser($rss = false)
    {
        if ($rss) {
            $this->document = array();
            $this->channel = array();
            $this->items = array();
            $DOMDocument = new DOMDocument;
            $DOMDocument->strictErrorChecking = false;
            libxml_use_internal_errors(true);
            if ($DOMDocument->loadXML($rss) !== false) {
                $this->document = $this->extractDOM($DOMDocument->childNodes);
            } else {
                emMsg("导入失败，无法读取的导入文件");
            }
        }
    }

    private function valueReturner($valueBlock = false)
    {
        if (!$valueBlock) {
            $valueBlock = $this->document;
        }
        foreach ($valueBlock as $valueName => $values) {
            if (isset($values['value'])) {
                $values = $values['value'];
            }
            if (is_array($values) && !empty($values)) {
                $valueBlock[$valueName] = $this->valueReturner($values);
            } else {
                $valueBlock[$valueName] = $values;
            }
        }
        return $valueBlock;
    }

    private function extractDOM($nodeList, $parentNodeName = false)
    {
        $itemCounter = 0;
        $tempNode = array();
        foreach ($nodeList as $values) {
            if (substr($values->nodeName, 0, 1) != '#') {
                if ($values->nodeName == 'item') {
                    $nodeName = $values->nodeName . ':' . $itemCounter;
                    $itemCounter++;
                } else {
                    $nodeName = $values->nodeName;
                }
                if (is_array($tempNode) == false)
                    $tempNode = array();
                $tempNode[$nodeName] = array();
                if ($values->attributes) {
                    for ($i = 0; $values->attributes->item($i); $i++) {
                        $tempNode[$nodeName]['properties'][$values->attributes->item($i)->nodeName] = $values->attributes->item($i)->nodeValue;
                    }
                }
                if (!$values->firstChild) {
                    $tempNode[$nodeName]['value'] = $values->textContent;
                } else {
                    $tempNode[$nodeName]['value'] = $this->extractDOM($values->childNodes, $values->nodeName);
                }
                if (in_array($parentNodeName, array('channel', 'rdf:RDF'))) {
                    if ($values->nodeName == 'item') {
                        $this->items[] = $tempNode[$nodeName]['value'];
                    } elseif (!in_array($values->nodeName, array('rss', 'channel'))) {
                        $this->channel[$values->nodeName] = $tempNode[$nodeName];
                    }
                }
            } elseif (substr($values->nodeName, 1) == 'text') {
                $tempValue = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", ' ', $values->textContent)));
                if ($tempValue) {
                    $tempNode = $tempValue;
                }
            } elseif (substr($values->nodeName, 1) == 'cdata-section') {
                $tempNode = $values->textContent;
            }
        }
        return $tempNode;
    }
}

// 过滤xml中的非法字符
function strip_invalid_xml_chars2($in)
{
    $out = "";
    $length = strlen($in);
    for ($i = 0; $i < $length; $i++) {
        $current = ord($in[$i]);
        if (($current == 0x9) || ($current == 0xA) || ($current == 0xD) || (($current >= 0x20) && ($current <= 0xD7FF)) || (($current >= 0xE000) && ($current <= 0xFFFD)) || (($current >= 0x10000) && ($current <= 0x10FFFF))) {
            $out .= chr($current);
        } else {
            $out .= " ";
        }
    }
    return $out;
}

EmToolKit::getInstance()->init();
