<?php
// +----------------------------------------------------------------------
// | WindSNS 国内领先企业级社交开源SNS框架系统
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2020 http://windsns.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 常州微诺信息科技有限公司 http://www.weinuo.net
// +----------------------------------------------------------------------
// | E-mail: open@weinuo.net
// +----------------------------------------------------------------------
namespace app\index\controller;
use app\common\controller\Frontend;
use think\Config;
use think\Hook;
use think\Db;
use think\Route;
use think\Request;
use think\Session;
use think\Validate;


class Circlepost extends Frontend
{

   protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
   
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });

    }
	/**
	 * 协议
	 * @author   Devil
	 * @blog     http://www.weinuo.net
	 * @version  0.0.1
	 * @datetime 2020-03-04
	 */
    public function addcircle()    //发布的页面
    {
    	$this->view->assign('title', __('兴趣发布'));

       $getcircleid  =  input('get.circleid'); // 获取链接上面的文章ID
       $sqlcircleid  = Db::name('circle_group')->where(['wscircleid'=>$getcircleid,'circle_open_state'=>1])->find(); //数据库查询这个圈子ID
       $this->assign('getcircleid', $getcircleid);


       if(!$sqlcircleid){
				echo '圈子不存在，或者关闭！';
				 exit;
			}else{

				return $this->view->fetch('index@circle/windsns_circleadd');

			}



    }




 public function editor($circleid)
    {
        /**
         * 如果允许 webuploader 图片插件到编辑器，那么
         * 1. 开启点击图片插入到编辑器功能
         * 2. 文章正文 base64 替换为原图
         * 3. 文章正文 过滤 webuploader 图片id，更改附件状态
         */
        $getcircleid  =  input('get.circleid'); // 获取链接上面的文章的圈子ID
        $subject = Request::instance()->param('subject');//获取文章标题
        $content = htmlspecialchars($_POST['content']);//获取文章内容
        $userid = $this->auth->getUserinfo()['user_id'];//获取这个用户的ID


        if (! empty($subject) && ! empty($content)) {
            $data = [
                'circleid' => $getcircleid,
                'user_id' => $userid,
                'subject' => $subject,
                'content' => $content,
                'create_time' => time(),
                'circle_state' => 1,  // 内容发布状态：1正常2隐藏3用户端删除
                'circle_hottype' => 0,//内容推荐状态：0、正常1、推荐2精华
            ];



            $result = Db::name('circlecontent')->insertGetId($data);

            if ($result) {
                // 数据写入成功
			                $weblist = [];
			                $weblist = Request::instance()->param('slide/a');
				                if (! empty($weblist)) {
				                    foreach ($weblist as $list) {
				                        $updateNum = Db::name('circleattachment')
				                            ->where('fileId', $list)
				                            ->update(['aid' => $result]);
				                        if ($updateNum) {
				                            // 数据更新成功
				                        } else {
				                            // 数据更新失败
				                        }
				                    }
				            }



			                $wanglist = [];
			                preg_match_all('/WANG_[0-9]{13}/', $content, $wanglist, PREG_PATTERN_ORDER);
			                if (! empty($wanglist[0])) {
			                    foreach ($wanglist[0] as $list) {
			                        $updateNum = Db::name('circleattachment')
			                            ->where('fileId', $list)
			                            ->update(['aid' => $result]);
			                        if ($updateNum) {
			                            // 数据更新成功
			                        } else {
			                            // 数据更新失败
			                        }
			                    }
			                }
		            } else {
		                // 数据写入失败

		                echo '保存失败！';
		                // exit;

		            }


		            $unfiles = DB::name('circleattachment')
		                ->whereTime('create_time', '<=', '48 hours')
		                // ->whereTime('create_time', '>=', '1 hours')
		                ->where('aid', null)
		                ->column('filePath');

		            if (! empty($unfiles)) {
		                foreach ($unfiles as $unfile) {
		                    $result = @unlink($unfile);
		                    if ($result) {
		                        Db::name('circleattachment')->where('filePath', $unfile)->delete();
		                    }
		                }
		            }
        }

        return  $this->fetch('circlepost_addok');//发布OK！

    }






    public function wangupload()
    {
        $files = request()->file('imgs');  // 获取上传图片
        // if (empty($files)) {
        //     die('{"errno" : "2", "data" : null, "msg" : "未选择图片文件"}');
        // }
        $images = [];
        $identi = [];
        $errors = [];
        $imageTypeArray = [
            0 => 'UNKNOWN',
            1 => 'GIF',
            2 => 'JPEG',
            3 => 'PNG',
            4 => 'SWF',
            5 => 'PSD',
            6 => 'BMP',
            7 => 'TIFF_II',
            8 => 'TIFF_MM',
            9 => 'JPC',
            10 => 'JP2',
            11 => 'JPX',
            12 => 'JB2',
            13 => 'SWC',
            14 => 'IFF',
            15 => 'WBMP',
            16 => 'XBM',
            17 => 'ICO',
            18 => 'COUNT',
        ];

        foreach ($files as $file) {
            $info = $file->move('uploads');
            if ($info) {
                $wangInfo = $info->getInfo();
                $filePath = 'uploads/' . str_replace('\\', '/', $info->getSaveName());
                $fileId = 'WANG_' . self::getMicroTime();
                $images[] = $filePath;
                $identi[] = $fileId;
                list($fileWidth, $fileHeight, $fileType, $fileAttr) = getimagesize($filePath);
                $data = [
//                  'user_id' => request()->param('user_id'),
                    'fileId' => $fileId,
                    'fileName' => $wangInfo['name'],  // $info->getFilename()
                    'filePath' => $filePath,
                    'fileWidth' => $fileWidth,
                    'fileHeight' => $fileHeight,
                    'fileSize' => $wangInfo['size'],
                    'fileType' => $imageTypeArray[$fileType],
                    'create_time' => time(),
                ];
                $result = Db::name('circleattachment')->insertGetId($data);
                if ($result) {
                    // 数据写入成功
                } else {
                    // 数据写入失败
                }
            } else {
                // 图片上传失败
                $errors[] = $file->getError();
            }
        }
        if (!$errors) {
            $msg['errno'] = 0;
            $msg['data'] = $images;
            $msg['identi'] = $identi;
            $msg['msg'] = null;
            return json($msg);
        } else {
            $msg['errno'] = 1;
            $msg['data'] = $images;
            $msg['identi'] = null;
            $msg['msg'] = "上传出错";
            return json($msg);
        }
    }

    public function webupload()
    {
        // Make sure file is not cached (as it happens for example on iOS devices)
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        // Support CORS
        // header("Access-Control-Allow-Origin: *");
        // other CORS headers if any...
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }

        if ( !empty($_REQUEST[ 'debug' ]) ) {
            $random = rand(0, intval($_REQUEST[ 'debug' ]) );
            if ( $random === 0 ) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }

        // 5 minutes execution time
        @set_time_limit(5 * 60);

        // Settings
        $targetDir = 'uploads_tmp' . DIRECTORY_SEPARATOR . date('Ymd');
        $uploadDir = 'uploads' . DIRECTORY_SEPARATOR . date('Ymd');
        // $targetDir = str_replace('\\', '/', $targetDir);
        // $uploadDir = str_replace('\\', '/', $uploadDir);

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        // Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }

        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }

        $saveName = md5($fileName) . '.' . strtolower(substr(strrchr($fileName, '.'), 1));

        // $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $saveName;
        // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $saveName;

        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }
                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
        if ( $done ) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }
            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }
                flock($out, LOCK_UN);
            }
            @fclose($out);

            $imageTypeArray = [
                0 => 'UNKNOWN',
                1 => 'GIF',
                2 => 'JPEG',
                3 => 'PNG',
                4 => 'SWF',
                5 => 'PSD',
                6 => 'BMP',
                7 => 'TIFF_II',
                8 => 'TIFF_MM',
                9 => 'JPC',
                10 => 'JP2',
                11 => 'JPX',
                12 => 'JB2',
                13 => 'SWC',
                14 => 'IFF',
                15 => 'WBMP',
                16 => 'XBM',
                17 => 'ICO',
                18 => 'COUNT',
            ];
            $uploadPath = str_replace('\\', '/', $uploadPath);
            list($fileWidth, $fileHeight, $fileType, $fileAttr) = getimagesize($uploadPath);
            $data = [
//              'user_id' => request()->param('user_id'),
                'fileId' => request()->param('id') . '_' . request()->param('dataId'),
                'fileName' => $fileName,  // md5($fileName) . '.' . strtolower(substr(strrchr($fileName, '.'), 1))
                'filePath' => $uploadPath,
                'fileWidth' => $fileWidth,
                'fileHeight' => $fileHeight,
                'fileSize' => request()->param('size'),
                'fileType' => $imageTypeArray[$fileType],
                'create_time' => time(),
            ];
            $result = Db::name('circleattachment')->insertGetId($data);
            if ($result) {
                // 数据写入成功
            } else {
                // 数据写入失败
            }
        }

        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }

    public static function getMicroTime()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (string) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }







}
