File "QiNiuService.php"
Full Path: /www/wwwroot/shphe-en.com/wp-content/plugins/proofreading/services/QiNiuService.php
File size: 16.15 KB
MIME-type: --
Charset: utf-8
<?php
require dirname(dirname(dirname(dirname(__DIR__)))). '/admin/extend/vendor/autoload.php';
require dirname(__DIR__) . '/services/BaseService.php';
require dirname(dirname(dirname(dirname(__DIR__))))."/wp-load.php";
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
use Qiniu\Config;
class QiNiuService extends BaseService
{
/**
* 七牛云存储accessKey
* @access private
* @var string $accessKey
*/
private $accessKey = 'RK9e73yt96PIpTWPyE3Bb6J-8vikRt1t5kRGFssR';
/**
* 七牛云存储secretKey
* @access private
* @var string $secretKey
*/
private $secretKey = '13nCzgXWS92SMO_B-QbV7_mNZLKYYdhRGdPRQZpM';
/**
* 七牛云存储访问域名
* @access private
* @var string $fileDomain
*/
private $fileDomain = 'download.goodao.net';
/**
* 七牛云存储空间名称
* @access private
* @var string $bucket
*/
private $bucket = 'goodao-translate';
/**
* 数据初始化
*/
public function __construct()
{
parent::__construct();
}
public function listFiles($marker = null){
$auth = new Auth($this->accessKey, $this->secretKey);
$bucketManager = new BucketManager($auth);
$list = $bucketManager->listFiles($this->bucket,$this->siteDomain."_bak",$marker);
$file_save_path = $this->jsonPath;
foreach ($list[0]["items"] as $file){
$baseUrl = 'http://' . $this->fileDomain . '/' . $file["key"];
$filepath = explode("/", $file["key"]);
// 下载保存文件名
$file_save_name = $file_save_path . '/' . $filepath[1];
// 对链接进行签名
$signedUrl = $auth->privateDownloadUrl($baseUrl);
$result = $this->https_request($signedUrl);
$language_array = json_decode($result, true);
if (!array_key_exists('error', $language_array) && count($language_array) > 0) {
// 判断当前路径是否存在 如果不存在创建文件夹
if (!file_exists($file_save_path)) {
mkdir($file_save_path, 0777, true);
}
file_put_contents($file_save_name, $result);
// echo $file_save_name."<br>";
}
}
if(isset($list[0]["marker"])){
$this->listFiles($list[0]["marker"]);
}
}
public function deleteFile($file_path){
// 构建鉴权对象
$auth = new Auth($this->accessKey, $this->secretKey);
// 要上传文件的本地路径
$filePath = $file_path;
$path_array = explode('/', $file_path);
// 获取需要上传的文件名
$file_name = end($path_array);
$keybak = $this->siteDomain . '_bak/' . $file_name;
$key = $this->siteDomain . '/' . $file_name;
$auth = new Auth($this->accessKey, $this->secretKey);
// $config = new Config();
$bucketManager = new BucketManager($auth);
$res = $bucketManager->delete($this->bucket, $keybak);
$res = $bucketManager->delete($this->bucket, $key);
// 下载文件保存路径
$file_save_path = $this->jsonPath;
// 下载保存文件名
$file_save_name = $file_save_path . '/' . $file_name;
unlink($file_save_name);
if ($res->error !== null) {
// 上传失败 记录日志
$this->writeLog(2, date('H:i:s') . '--七牛云文件删除失败!' . $file_path);
return false;
} else {
return true;
}
}
/**
* 从七牛云下载文件
* @access public
* @param string $file_name
* @return string
*/
public function downloadFile($file_name,$path = null)
{
return $this->transb($file_name,$path);
// 下载文件保存路径
$file_save_path = $this->jsonPath;
// 下载保存文件名
$file_save_name = $file_save_path . '/' . $file_name;
// 判断当前文件本地是否存在 如果存在直接读取本地文件
// 本地不存在 从七牛云中获取
// 构建Auth对象
if (is_file($file_save_name)) {
return $file_save_name;
} else{
$auth = new Auth($this->accessKey, $this->secretKey);
$baseUrl = 'http://' . $this->fileDomain . '/' . $this->siteDomain . '/' . $file_name;
// 对链接进行签名
$signedUrl = $auth->privateDownloadUrl($baseUrl);
$result = $this->https_request($signedUrl);
$language_array = json_decode($result, true);
if (!array_key_exists('error', $language_array) && count($language_array) > 0) {
// 判断当前路径是否存在 如果不存在创建文件夹
if (!file_exists($file_save_path)) {
mkdir($file_save_path, 0777, true);
}
foreach ($language_array["texts"] as $k=> $texts){
unset($language_array["texts"][$k]);
$k = htmlspecialchars_decode(html_entity_decode(trim($k)));
// echo $k."<br>";
$language_array["texts"][$k] = $texts;
}
$result= json_encode($language_array);
file_put_contents($file_save_name, $result);
return $file_save_name;
}else {
// 判断当前路径是否存在 如果不存在创建文件夹
if (!file_exists($file_save_path)) {
mkdir($file_save_path, 0777, true);
}
$this->transb($file_name,$path);
return $file_save_name;
}
}
}
public function transb($file_name = null,$path = 0,$language =0){
$param = $_POST;
if(!$path){
$path = $param['path'];
}
$language = $param['language'];
$html_file_path = $this->htmlPath . $path . 'index.html';
// echo $html_file_path;
if(!is_file($html_file_path)){
$html = file_get_html("http://".$this->siteDomain.$path);
}else{
$html = file_get_html($html_file_path);
}
// $html = file_get_html($html_file_path);
$es = $html->find("text");
$description = $html->find("meta[name=description]",0);
$keywords = $html->find("meta[name=keywords]",0);
$imgses = $html->find("img");
$texts = [];
$texts["tls"] = ["$language"];
$texts["sl"] = "en";
$texts["texts"][] = $description->content?$description->content:"";
$texts["texts"][] = $keywords->content?$keywords->content:"";
$sourcetext[] = $description->content?$description->content:"";
$sourcetext[] = $keywords->content?$keywords->content:"";
$imges = $html->find("img");
foreach ($imges as $ei){
$alt = $ei->alt;
if($alt){
$sourcetext[] = $alt;
$texts["texts"][] = $alt;
}
}
foreach($es as $e){
$tag= $e->parent()->tag;
$tags = ["script","style","root"];
if(!in_array($tag,$tags)){
$t = trim($e->text());
if($t ){
$lanclass = method_exists($e->parent()->parent(),"find")?$e->parent()->parent()->find("b",0)->class:"";
if( $lanclass != "country-flag"){
$sourcetext[] = $e->text();
$texts["texts"][] = htmlspecialchars_decode(html_entity_decode($t));
}
}
}
}
// var_dump($texts);
$json = json_encode($texts,JSON_UNESCAPED_UNICODE);
// echo ($json);
// exit;
// echo $tag;
foreach($imgses as $i=>$img){
$src = $img->src;
$imgs[ $src] = $src;
}
$Http = new WP_Http_Curl();
$args = array(
'method' => 'POST',
'sslverify' => false,
"headers"=>[
'Accept' => 'application/json',
'Accept-Charset' => 'utf-8',
'Content-Type' => 'application/json; charset=utf-8',
"Content-Length"=>strlen($json)
],
'body' => $json,
);
$res = wp_remote_retrieve_body($Http->request("http://translate.waimaoq.com/globalso_trans", $args));
$res = json_decode($res,true);
// print_r($res);
if(isset($res[0]["code"]) && $res[0]["code"] == 200){
$text = [];
$bakfile = $this->jsonPath."/en_{$language}_all.json";
if(is_file($bakfile)){
$baktxt = json_decode(file_get_contents($bakfile),true);
}else{
$baktxt = [];
}
foreach($sourcetext as $k=>$v){
if(isset($baktxt[$v])){
$text[$v] = $baktxt[$v];
}else{
$text[$v] = $res[0]["texts"][$k];
}
}
$json_data["texts"] = $text;
// $json_data["description"] = $res[0]["data"][0][0];
// $json_data["keywords"] = $res[0]["data"][1][0];
$json_data["imgs"] = $imgs;
return $json_data;
// return $json;
// $data = $this->post(,$texts,true);
if($file_name){
$file_name = $this->getJsonFileName($path, $language);
$file_save_path = $this->jsonPath;
// 下载保存文件名
$file_save_name = $file_save_path . '/' . $file_name;
file_put_contents($file_save_name,json_encode($json_data));
}else{
return $json_data;
}
//return json_encode(['status' => 1, 'msg' => '获取成功!', 'data' => $json_data]);
}
}
/**
* 将文件上传至七牛云
* @access protected
* @param string $file_path
* @return bool
* @throws \Exception
*/
public function uploadFile($file_path)
{
return true;
// 构建鉴权对象
$auth = new Auth($this->accessKey, $this->secretKey);
// 要上传文件的本地路径
$filePath = $file_path;
$path_array = explode('/', $file_path);
// 获取需要上传的文件名
$file_name = end($path_array);
// 上传到七牛后保存的文件名
$key = $this->siteDomain . '/' . $file_name;
$path = dirname(dirname(dirname(dirname(__FILE__))));
copy($filePath,$path."/json/$file_name");
// 上传到七牛后保存的文件名
$keybak = $this->siteDomain . '_bak/' . $file_name;
// 初始化 UploadManager 对象并进行文件的上传。
$uploadMgr = new UploadManager();
// 生成上传 Token
$token = $auth->uploadToken($this->bucket, $key);
// 调用 UploadManager 的 putFile 方法进行文件的上传。
list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
// 生成上传 Token
$token = $auth->uploadToken($this->bucket, $keybak);
// 调用 UploadManager 的 putFile 方法进行文件的上传。
list($ret, $err) = $uploadMgr->putFile($token, $keybak, $filePath);
if ($err !== null) {
// 上传失败 记录日志
$this->writeLog(2, date('H:i:s') . '--七牛云文件上传失败!' . $file_path);
return false;
} else {
return true;
}
}
/**
* 远程请求数据
* @param string $url 远程请求地址
* @param array|null $data 请求提交的数据
* @param array|null $header 请求头
* @return string
*/
public function https_request($url, $data = null, $header = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
if (!empty($header)) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
//设置curl默认访问为IPv4
if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
}
$output = curl_exec($curl);
curl_close($curl);
return ($output);
}
/**
* 批量拉取json文件
* @access protected
* @param string $language
* @return string
*/
public function curlBatchDownloadFile ($language)
{
$pages = $this->pages;
$file_path = $this->jsonPath;
$urls = [];
$file_list = [];
$auth = new Auth($this->accessKey, $this->secretKey);
$baseUrl = 'http://' . $this->fileDomain . '/' . $this->siteDomain . '/';
foreach ($pages as $key => $value) {
$file_name = $this->getJsonFileName($value['path'], $language);
if (!file_exists($file_path . '/' . $file_name)) {
$urls[] = $auth->privateDownloadUrl($baseUrl . $file_name);
$file_list[] = $file_name;
}
}
$count = count($urls);
if ($count <= 0) {
return true;
}
$chs = [];
// 创建批处理cURL句柄
$mh = curl_multi_init();
// 创建cURL资源
for($i = 0; $i < $count; $i ++){
$chs[ $i ] = curl_init();
// 设置URL和相应的选项
curl_setopt($chs[ $i ], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($chs[ $i ], CURLOPT_URL, $urls[$i]);
curl_setopt($chs[ $i ], CURLOPT_HEADER, 0);
curl_multi_add_handle($mh, $chs[ $i ]);
}
// 执行批处理句柄
do {
$mrc = curl_multi_exec($mh, $active);
} while ($active > 0);
while ($active and $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
for($i = 0; $i < $count; $i ++){
$content = curl_multi_getcontent($chs[$i]);
$file_path = $this->jsonPath;
// 判断当前路径是否存在 如果不存在创建文件夹
if (!file_exists($file_path)) {
mkdir($file_path, 0777, true);
}
$content_array = json_decode($content, true);
if (!empty($content) && !array_key_exists('error', $content_array)) {
file_put_contents($file_path . '/' . $file_list[$i], $content);
}
}
curl_multi_close($mh);
}
}