<?php
/*
  PHP version 5
  Copyright (c) 2002-2020 ECISP.CN、EarcLink.COM
  警告：这不是一个免费的软件，请在许可范围内使用，请尊重知识产权，侵权必究，举报有奖
  作者：黄祥云 E-mail:6326420@qq.com  QQ:6326420 TEL:18665655030 / 13797552220
*/

use modul_application\ESPCMS_MemberAuthority;
use modul_application\ESPCMS_Dialog;
use modul_application\ESPCMS_ArticleDB;
use modul_application\ESPCMS_ArticleTypeDB;

class Download {
    public static function in_Export() {
        $did = $_GET['did'];
        $attr = $_GET['attr'];
        if (!$did || !espcms_ismatches($did) || !$attr) {
            ESPCMS_Dialog::Message_Page('db_err');
        }
        $doc_read = ESPCMS_ArticleDB::get_article_read($did);
        if (!$doc_read || !$doc_read['isclass']) {
            ESPCMS_Dialog::Message_Page('doc_read_err');
        }
        if ($doc_read['purview'] && $member_app_config['isetup'] && $member_app_config['isopen']) {
            ESPCMS_MemberAuthority::authorityRandVerify($doc_read['purview']);
        }
        $type_read = ESPCMS_ArticleTypeDB::get_article_type_view($doc_read['tid']);
        if (!$type_read || !$type_read['isclass']) {
            ESPCMS_Dialog::Message_Page('type_read_err');
        }
        if ($type_read['purview'] && $member_app_config['isetup'] && $member_app_config['isopen']) {
            ESPCMS_MemberAuthority::authorityRandVerify($type_read['purview']);
        }
        $attr_read = ESPCMS_ArticleDB::get_article_attr_read($did);
        $read = is_array($attr_read) ? array_merge($doc_read, $attr_read) : $doc_read;
        $downFile = $read[$attr];
        if (!preg_match('/^[\w\/\.]+$/i', $downFile)) {
            ESPCMS_Dialog::Message_Page('doc_read_err');
        }
        $file_path = ESPCMS_WEB_PATH . $downFile;
        if (!is_file($file_path)) {
            ESPCMS_Dialog::Message_Page('doc_read_err');
        }
        $options = pathinfo($downFile);
        if (!$options['extension'] || $options['extension'] == 'php') {
            ESPCMS_Dialog::Message_Page('doc_read_err');
        }
        $file_key = time() . $file_path;
        $file_name = md5($file_key) . '.' . $options['extension'];
        $db_table = ESPCMS_DB_PREFIX . "document";
        $db_where = "WHERE did=$did";
        espcms_db_update_set_save($db_table, $db_where, "downhot=downhot+1");
        $file_content = file_get_contents($file_path);
        if (!$file_content) {
            ESPCMS_Dialog::Message_Page('doc_read_err');
        }
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: " . filesize($file_path));
        Header("Content-Disposition: attachment; filename=" . $file_name);
        exit($file_content);
    }
}