<?php
defined('EMLOG_ROOT') || exit('access denied!');

/*
 * 插件前台展示页面
 * 前台显示地址为：https://yourdomain/?plugin=tips
 */
$data = json_decode(file_get_contents('php://input'), true);

$url = $data['url'];
$uplaodUrl = BLOG_URL . '/?rest-api=upload';


$strsplit = explode('?', $url);
$explodeimg = explode('/', $strsplit[0]);
$imgName = $explodeimg[count($explodeimg) - 1];

$result = [
  'code' => 0,
  'msg'  => 'ok',
  'data' => [
    'originalURL' => '',
    'url' => ''
  ]
];


if (Option::get('is_openapi') === 'n') {
  $result['code'] = 401;
  $result['msg'] = 'api method is not exist';
  die(json_encode($result, JSON_UNESCAPED_UNICODE));
}

$imgData = file_get_contents($data['url']);



$file_path =  __DIR__ . '/upload/' . $imgName;
$is_upload = file_put_contents($file_path, $imgData);

if (!$is_upload) {
  $result['code'] = 400;
  $result['msg'] = '上传失败';
  die(json_encode($result, JSON_UNESCAPED_UNICODE));
}


// API秘钥，在后台系统-设置-API接口设置里可以找到
$apikey = Option::get('apikey');


// 构造POST数据
$post_data = array(
  'file' => new CURLFile($file_path),
  'api_key' => $apikey
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uplaodUrl); // 设置请求URL
curl_setopt($ch, CURLOPT_POST, 1); // 设置为POST请求
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // 设置POST数据
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 设置返回结果不直接输出
$response = curl_exec($ch); // 执行请求并获取响应数据

$json_response = json_decode($response, true);

if (curl_close($ch)) {
  $result['code'] = 401;
  $result['msg'] = curl_close($ch);
} else {
  $result['data']['originalURL'] = $url;
  $result['data']['url'] = $json_response['data']['url'];
}

curl_close($ch); // 关闭curl

if (file_exists($file_path)) {
  unlink($file_path);
}

die(json_encode($result, JSON_UNESCAPED_UNICODE));
?>
<!--some html code here-->