<?php
/**
 * 人人站CMS
 * ============================================================================
 * 版权所有 2015-2030 山东康程信息科技有限公司，并保留所有权利。
 * 网站地址: http://www.rrzcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 */

namespace app\admin\controller;

use app\BaseController;
use think\facade\Db;

class Import extends BaseController
{

    function index() {
        function_exists('set_time_limit') && set_time_limit(0);
        @ini_set('memory_limit', '-1');
        is_file('inport.lock') and exit('正在执行导入！');
        file_put_contents('inport.lock', '');

        $typeid = $_GET['typeid'];
        $nodeid = $_GET['nodeid'];
        if (!is_numeric($typeid) || !is_numeric($nodeid)) exit('参数错误');
        $rows = Db::query('SELECT id,title,flag,click,keywords,description,litpic,channel FROM ey19.dede_archives WHERE arcrank=0 AND typeid=' . $typeid . ' ORDER BY id');
        if (count($rows) <= 0) {
            exit('没有数据！');
        }
        $list = [];
        foreach ($rows as $item) {
            $content = '';
            if ($item['channel'] == 2) {
                $body = Db::query('SELECT imgurls,body FROM ey19.dede_addonimages WHERE aid=' . $item['id']);
                $imsg = $body[0]['imgurls'] ?? '';
                preg_match_all('/\{dede:img.*ddimg=["|\'](.*)["|\'].*}/isU', $imsg, $matches);
                foreach ($matches[1] as $value) {
                    $url = $this->impImg($value);
                    if (!$url) continue;
                    $content .= '<p style="text-align: center"><img  src="' . $url . '"/></p>';
                }
                $content .= $body[0]['body'] ?? '';
            } else {
                $body = Db::query('SELECT body FROM ey19.dede_addonarticle WHERE aid=' . $item['id']);
                if (!$body || !isset($body[0]['body'])) continue;
                $content = $body[0]['body'];

                $that = $this;
                $content = preg_replace_callback('/<img.*src=["|\'](.*)["|\'].*>/isU', function ($matches) use ($that) {
                    $url = $that->impImg($matches[1]);
                    return str_replace($matches[1], $url, $matches[0]);
                }, $content);
            }
            $content = str_replace(['&ldquo;', '&rdquo;', '&hellip;', '&middot;', '&mdash;'], ['“', '”', '…', '·', '—'], $content);

            $img = $this->impImg($item['litpic']);
            $list[] = [
                'node_id' => $nodeid,
                'title' => $item['title'],
                'img' => $img,
                'content' => $content,
                'seo_description' => $item['description'],
                'seo_keywords' => $item['keywords'],
                'uptime' => time(),
                'pubtime' => time(),
                'ifpub' => 'true',
                'view_count' => $item['click'],
                'add_time' => time(),
                'is_head' => strpos($item['flag'], 'h') === false ? 0 : 1,
                'is_special' => strpos($item['flag'], 'a') === false ? 0 : 1,
                'is_recom' => strpos($item['flag'], 'c') === false ? 0 : 1,
            ];
        }
        $list and M('articles')->insertAll($list);
        @unlink('inport.lock');
        exit('导入成功！');
    }

    function impImg($img) {
        $img = trim($img);
        if (!$img || strpos($img, 'http') !== false || strpos($img, 'data:image') !== false) return '';
        $idx = strpos($img, '?') and $img = substr($img, 0, $idx);

        $ml = 'E:\\Project\\Temp\\eymb\\19\\' . str_replace('/', '\\', ltrim($img, '/'));
        if (!is_file($ml)) {return '';
            $dd = get_curl('http://demoall.adashuo.com/17855/' . ltrim($img, '/'));
            if (!$dd) {
                file_put_contents('import.log', '[图片地址]' . $img . '[不存在]' . "\n", FILE_APPEND);
                return '';
            }
            file_put_contents($ml, $dd);
        }
        $imgList = cache('imgList') ?: [];
        $md5 = md5_file($ml);
        if (isset($imgList[$md5])) return $imgList[$md5];
        $pinfo = pathinfo($img);
        $ret = '/storage/images/20200726/' . $pinfo['basename'];
        $mb = $this->app->getRootPath() . 'public' . $ret;

        if (!@copy($ml, $mb)) {
            file_put_contents('import.log', '[图片地址]' . $img . '[拷贝失败]' . "\n", FILE_APPEND);
            return '';
        }
        $imgList[$md5] = $ret;
        cache('imgList', $imgList);
        return $ret;
    }
}