imgur upload support

pull/128/head
mashiro 2019-11-14 02:39:22 +08:00
parent c3a0d671ed
commit 89656306f4
6 changed files with 446 additions and 234 deletions

View File

@ -28,8 +28,6 @@ if ( !function_exists( 'optionsframework_init' ) ) {
require_once dirname( __FILE__ ) . '/inc/options-framework.php';
}
function akina_setup() {
/*
* Make theme available for translation.
@ -214,6 +212,7 @@ add_action( 'wp_enqueue_scripts', 'sakura_scripts' );
*/
require get_template_directory() .'/inc/decorate.php';
require get_template_directory() .'/inc/swicher.php';
require get_template_directory() .'/inc/api.php';
/**
* Custom template tags for this theme.
@ -1633,68 +1632,6 @@ add_action( 'pre_get_posts', function( $q ){
$q->set( 'post__not_in', get_option( 'sticky_posts' ) );
});
/*
* 定制实时搜索 rest api
* @rest api接口路径https://sakura.2heng.xin/wp-json/cache_search/v1/json/
* @可在cache_search_json()函数末尾通过设置 HTTP header 控制 json 缓存时间
*/
function cache_search_json() {
$vowels = array("[", "{","]","}","<",">","\r\n", "\r", "\n","-","'",'"','`'," ",":",";",'\\'," ","toc");
$regex = <<<EOS
/<\/?[a-zA-Z]+("[^"]*"|'[^']*'|[^'">])*>|begin[\S\s]*\/begin|hermit[\S\s]*\/hermit|img[\S\s]*\/img|{{.*?}}|:.*?:/m
EOS;
$posts = new WP_Query('posts_per_page=-1&post_status=publish&post_type=post');
while ($posts->have_posts()) : $posts->the_post();
$output .= '{"type":"post","link":"'.get_post_permalink().'","title":'.json_encode(get_the_title()).',"comments":"'.get_comments_number('0', '1', '%').'","text":'.json_encode(str_replace($vowels, " ",preg_replace($regex,' ',get_the_content()))).'},';
endwhile;
wp_reset_postdata();
$pages = get_pages();
foreach ($pages as $page) {
$output .= '{"type":"page","link":"'.get_page_link($page).'","title":'.json_encode($page->post_title).',"comments":"'.$page->comment_count.'","text":'.json_encode(str_replace($vowels, " ",preg_replace($regex,' ',$page->post_content))).'},';
}
$tags = get_tags();
foreach ($tags as $tag) {
$output .= '{"type":"tag","link":"'.get_term_link($tag).'","title":'.json_encode($tag->name).',"comments":"","text":""},';
}
$categories = get_categories();
foreach ($categories as $category) {
$output .= '{"type":"category","link":"'.get_term_link($category).'","title":'.json_encode($category->name).',"comments":"","text":""},';
}
if(akina_option('live_search_comment')){
$comments = get_comments();
foreach ($comments as $comment) {
$is_private = get_comment_meta($comment->comment_ID, '_private', true);
if($is_private){
$output .= '{"type":"comment","link":"'.get_comment_link($comment).'","title":'.json_encode(get_the_title($comment->comment_post_ID)).',"comments":"","text":'.json_encode($comment->comment_author."".__("The comment is private","sakura")/*该评论为私密评论*/).'},';
continue;
}else{
$output .= '{"type":"comment","link":"'.get_comment_link($comment).'","title":'.json_encode(get_the_title($comment->comment_post_ID)).',"comments":"","text":'.json_encode(str_replace($vowels, " ",preg_replace($regex," ",$comment->comment_author."".$comment->comment_content))).'},';
}
}
}
$output = substr($output,0,strlen($output)-1);
$data = '['.$output.']';
$result = new WP_REST_Response(json_decode($data), 200);
$result->set_headers(array('Content-Type' => 'application/json',
'Cache-Control' => 'max-age=3600')); // json 缓存控制
return $result;
}
if(akina_option('live_search')){
add_action( 'rest_api_init', function () {
register_rest_route( 'cache_search/v1', '/json/', array(
'methods' => 'GET',
'callback' => 'cache_search_json',
) );
} );
}
//评论回复
function sakura_comment_notify($comment_id){
if ( !$_POST['mail-notify'] )

177
inc/api.php 100644
View File

@ -0,0 +1,177 @@
<?php
/**
* Router
*/
add_action('rest_api_init', function () {
register_rest_route('sakura/v1', '/image/upload', array(
'methods' => 'POST',
'callback' => 'upload_image',
));
register_rest_route('sakura/v1', '/cache_search/json', array(
'methods' => 'GET',
'callback' => 'cache_search_json',
));
});
/**
* Image uploader response
*/
function upload_image(WP_REST_Request $req)
{
// see: https://developer.wordpress.org/rest-api/requests/
// handle file params $file === $_FILES
/**
* curl \
* -F "filecomment=This is an img file" \
* -F "cmt_img_file=@screenshot.jpg" \
* https://dev.2heng.xin/wp-json/sakura/v1/image/upload
*/
$file = $req->get_file_params();
$image = file_get_contents($_FILES["cmt_img_file"]["tmp_name"]);
switch (akina_option("img_upload_api")) {
case 'imgur':
$API_Request = Imgur_API($image);
break;
case 'smms':
$API_Request = SMMS_API($image);
break;
}
$result = new WP_REST_Response($API_Request, 200);
$result->set_headers(array('Content-Type' => 'application/json',
'Cache-Control' => 'max-age=3600')); // json 缓存控制
return $result;
}
/**
* Imgur upload interface
*/
function Imgur_API($image)
{
$client_id = akina_option('imgur_client_id');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, akina_option('imgur_upload_image_proxy'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode($image)));
$reply = curl_exec($ch);
curl_close($ch);
$reply = json_decode($reply);
if ($reply->success && $reply->status == 200) {
$status = 200;
$message = "success";
$link = $reply->data->link;
$proxy = akina_option('cmt_image_proxy') . $link;
} else {
$status = $reply->status;
$message = $reply->data->error;
$link = 'https://view.moezx.cc/images/2019/10/28/default_d_h_large.gif';
$proxy = akina_option('cmt_image_proxy') . $link;
}
$output = array(
'status' => $status,
'message' => $message,
'link' => $link,
'proxy' => $proxy,
);
return $output;
}
function SMMS_API($image)
{
$client_id = akina_option('smms_client_id');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://sm.ms/api/v2/upload');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $client_id));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type ' . 'multipart/form-data'));
curl_setopt($ch, CURLOPT_POSTFIELDS, array('smfile' => $image));
$reply = curl_exec($ch);
curl_close($ch);
$reply = json_decode($reply);
if ($reply->success && $reply->code == 'success') {
$status = 200;
$message = $reply->message;
$link = $reply->data->url;
$proxy = akina_option('cmt_image_proxy') . $link;
} else {
$status = 0; // sm.ms 接口不规范,谁给提个意见?我要状态码!
$message = $reply->message;
$link = 'https://view.moezx.cc/images/2019/10/28/default_d_h_large.gif';
$proxy = akina_option('cmt_image_proxy') . $link;
}
$output = array('status' => $status,
'message' => $message,
'link' => $link,
'proxy' => $proxy,
);
return $output;
}
/*
* 定制实时搜索 rest api
* @rest api接口路径https://sakura.2heng.xin/wp-json/cache_search/v1/json/
* @可在cache_search_json()函数末尾通过设置 HTTP header 控制 json 缓存时间
*/
function cache_search_json()
{
$vowels = array("[", "{", "]", "}", "<", ">", "\r\n", "\r", "\n", "-", "'", '"', '`', " ", ":", ";", '\\', " ", "toc");
$regex = <<<EOS
/<\/?[a-zA-Z]+("[^"]*"|'[^']*'|[^'">])*>|begin[\S\s]*\/begin|hermit[\S\s]*\/hermit|img[\S\s]*\/img|{{.*?}}|:.*?:/m
EOS;
$posts = new WP_Query('posts_per_page=-1&post_status=publish&post_type=post');
while ($posts->have_posts()): $posts->the_post();
$output .= '{"type":"post","link":"' . get_post_permalink() . '","title":' . json_encode(get_the_title()) . ',"comments":"' . get_comments_number('0', '1', '%') . '","text":' . json_encode(str_replace($vowels, " ", preg_replace($regex, ' ', get_the_content()))) . '},';
endwhile;
wp_reset_postdata();
$pages = get_pages();
foreach ($pages as $page) {
$output .= '{"type":"page","link":"' . get_page_link($page) . '","title":' . json_encode($page->post_title) . ',"comments":"' . $page->comment_count . '","text":' . json_encode(str_replace($vowels, " ", preg_replace($regex, ' ', $page->post_content))) . '},';
}
$tags = get_tags();
foreach ($tags as $tag) {
$output .= '{"type":"tag","link":"' . get_term_link($tag) . '","title":' . json_encode($tag->name) . ',"comments":"","text":""},';
}
$categories = get_categories();
foreach ($categories as $category) {
$output .= '{"type":"category","link":"' . get_term_link($category) . '","title":' . json_encode($category->name) . ',"comments":"","text":""},';
}
if (akina_option('live_search_comment')) {
$comments = get_comments();
foreach ($comments as $comment) {
$is_private = get_comment_meta($comment->comment_ID, '_private', true);
if ($is_private) {
$output .= '{"type":"comment","link":"' . get_comment_link($comment) . '","title":' . json_encode(get_the_title($comment->comment_post_ID)) . ',"comments":"","text":' . json_encode($comment->comment_author . "" . __("The comment is private", "sakura") /*该评论为私密评论*/) . '},';
continue;
} else {
$output .= '{"type":"comment","link":"' . get_comment_link($comment) . '","title":' . json_encode(get_the_title($comment->comment_post_ID)) . ',"comments":"","text":' . json_encode(str_replace($vowels, " ", preg_replace($regex, " ", $comment->comment_author . "" . $comment->comment_content))) . '},';
}
}
}
$output = substr($output, 0, strlen($output) - 1);
$data = '[' . $output . ']';
$result = new WP_REST_Response(json_decode($data), 200);
$result->set_headers(array('Content-Type' => 'application/json',
'Cache-Control' => 'max-age=3600')); // json 缓存控制
return $result;
}

BIN
inc/test.jpg 100644

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

31
inc/test.php 100644
View File

@ -0,0 +1,31 @@
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$image = file_get_contents("test.jpg");
function Imgur_API($image) {
$client_id = "98cd21cdfc58130";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mashiro.top/imgur-api/3/image');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode($image)));
$reply = curl_exec($ch);
curl_close($ch);
$reply = json_decode($reply);
var_dump($reply);
printf('<img height="180" src="%s" >', $reply->data->link);
$res = $reply->data->link;
$res = 'https://images.weserv.nl/?url='.$res;
echo $res;
printf('<img height="180" src="%s" >', $res);
}
Imgur_API($image);

View File

@ -73,6 +73,7 @@ function post_list_show_animation() {
}
var io = new IntersectionObserver(callback, options);
var articles = document.querySelectorAll('.post-list-thumb');
function callback(entries) {
entries.forEach((article) => {
if (article.target.classList.contains("post-list-show")) {
@ -179,9 +180,9 @@ function attach_image() {
for (var i = 0; i < this.files.length; i++) {
var f = this.files[i];
var formData = new FormData();
formData.append('smfile', f);
formData.append('cmt_img_file', f);
$.ajax({
url: 'https://sm.ms/api/upload',
url: '/wp-json/sakura/v1/image/upload',
type: 'POST',
processData: false,
contentType: false,
@ -195,18 +196,24 @@ function attach_image() {
setTimeout(function () {
cached.html('<i class="fa fa-picture-o" aria-hidden="true"></i>');
}, 1000);
var get_the_url = res.data.url;
var get_the_url = res.proxy;
$('#upload-img-show').append('<img class="lazyload upload-image-preview" src="https://cdn.jsdelivr.net/gh/moezx/cdn@3.0.2/img/svg/loader/trans.ajax-spinner-preloader.svg" data-src="' + get_the_url + '" onclick="window.open(\'' + get_the_url + '\')" onerror="imgError(this)" />');
lazyload();
addComment.createButterbar("图片上传成功~<br>Uploaded successfully~");
grin(res.data.url.replace('https://i.loli.net/', '{UPLOAD}'), type = 'Img');
grin(get_the_url, type = 'Img');
},
error: function () {
error: function (jqXHR, textStatus, errorThrown) {
cached.html('<i class="fa fa-times" aria-hidden="true" style="color:red"></i>');
alert("上传失败,请重试.\nUpload failed, please try again.");
setTimeout(function () {
cached.html('<i class="fa fa-picture-o" aria-hidden="true"></i>');
}, 1000);
// console.info(jqXHR.responseText);
// console.info(jqXHR.status);
// console.info(jqXHR.readyState);
// console.info(jqXHR.statusText);
// console.info(textStatus);
// console.info(errorThrown);
}
})
}
@ -297,6 +304,7 @@ function checkskinSecter() {
$(".headertop-bar-sakura").removeClass('headertop-bar-sakura').addClass('headertop-bar');
}
}
function checkBgImgCookie() {
var bgurl = getCookie("bgImgSetting");
if (!bgurl) {
@ -321,6 +329,7 @@ $(document).ready(function() {
function checkskin_bg(a) {
return a == "none" ? "" : a
}
function changeBG() {
var cached = $(".menu-list");
cached.find("li").each(function () {
@ -533,7 +542,9 @@ function coverVideoIni() {
function copy_code_block() {
$('pre code').each(function (i, block) {
$(block).attr({ id: 'hljs-' + i });
$(block).attr({
id: 'hljs-' + i
});
$(this).after('<a class="copy-code" href="javascript:" data-clipboard-target="#hljs-' + i + '" title="拷贝代码"><i class="fa fa-clipboard" aria-hidden="true"></i></a>');
});
var clipboard = new ClipboardJS('.copy-code');
@ -773,15 +784,21 @@ if(mashiro_option.float_player_on) {
});
var apSwitchTag = 0;
var aplayerlist = $(".aplayer-list");
aplayerlist.removeClass( "aplayer-list-hide" ).css({maxHeight:'0px'});
aplayerlist.removeClass("aplayer-list-hide").css({
maxHeight: '0px'
});
$(".aplayer.aplayer-fixed .aplayer-body").addClass("ap-hover");
$(".aplayer-miniswitcher").click(function () {
if (apSwitchTag == 0) {
aplayerlist.removeClass( "aplayer-list-hide" ).animate({maxHeight:'250px'});
aplayerlist.removeClass("aplayer-list-hide").animate({
maxHeight: '250px'
});
$(".aplayer.aplayer-fixed .aplayer-body").removeClass("ap-hover");
apSwitchTag = 1;
} else {
aplayerlist.css({maxHeight:'0px'});
aplayerlist.css({
maxHeight: '0px'
});
$(".aplayer.aplayer-fixed .aplayer-body").addClass("ap-hover");
apSwitchTag = 0;
}
@ -829,7 +846,8 @@ if(mashiro_option.float_player_on) {
}
function getqqinfo() {
var is_get_by_qq = false,cached = $('input');
var is_get_by_qq = false,
cached = $('input');
if (!getCookie('user_qq') && !getCookie('user_qq_email') && !getCookie('user_author')) {
cached.filter('#qq,#author,#email,#url').val('');
}
@ -1297,7 +1315,9 @@ var home = location.href,
if (resizeFlag = null) {
clearTimeout(resizeFlag);
}
resizeFlag = setTimeout(function(){ Siren.AH();}, 1000);
resizeFlag = setTimeout(function () {
Siren.AH();
}, 1000);
})
}
} else {
@ -1352,7 +1372,7 @@ var home = location.href,
$('html').css('overflow-y', 'hidden');
if (mashiro_option.live_search) {
var QueryStorage = [];
search_a("https://"+document.domain+"/wp-json/cache_search/v1/json/");
search_a("https://" + document.domain + "/wp-json/sakura/v1/cache_search/json");
var otxt = addComment.I("search-input"),
list = addComment.I("PostlistBox"),
@ -1402,6 +1422,7 @@ var home = location.href,
}
return val;
}
function Cx(arr, q) {
q = q.replace(q, "^(?=.*?" + q + ").+$").replace(/\s/g, ")(?=.*?");
i = arr.filter(
@ -1411,6 +1432,7 @@ var home = location.href,
);
return i;
}
function div_href() {
$(".ins-selectable").each(function () {
$(this).click(function () {
@ -1420,6 +1442,7 @@ var home = location.href,
});
});
}
function search_result(keyword, link, fa, title, iconfont, comments, text) {
if (keyword) {
var s = keyword.trim().split(" "),
@ -1492,7 +1515,8 @@ var home = location.href,
NH: function () {
var h1 = 0;
$(window).scroll(function () {
var s = $(document).scrollTop(),cached = $('.site-header');
var s = $(document).scrollTop(),
cached = $('.site-header');
if (s == h1) {
cached.removeClass('yya');
}
@ -1512,7 +1536,9 @@ var home = location.href,
var load_time = addComment.I("add_post_time").title;
if (load_time != "233") {
console.log("%c 自动加载时倒计时 %c", "background:#9a9da2; color:#ffffff; border-radius:4px;", "", "", load_time);
load_post_timer=setTimeout(function(){load_post();},load_time*1000);
load_post_timer = setTimeout(function () {
load_post();
}, load_time * 1000);
}
}
});
@ -1524,6 +1550,7 @@ var home = location.href,
load_post();
return false;
});
function load_post() {
$('#pagination a').addClass("loading").text("");
$.ajax({
@ -1542,7 +1569,9 @@ var home = location.href,
//加载完成上滑
var tempScrollTop = $(window).scrollTop();
$(window).scrollTop(tempScrollTop);
$body.animate({ scrollTop: tempScrollTop + 300 }, 666)
$body.animate({
scrollTop: tempScrollTop + 300
}, 666)
} else {
$("#pagination").html("<span>很高兴你翻到这里,但是真的没有了...</span>");
}

View File

@ -1005,6 +1005,44 @@ function optionsframework_options() {
'type_4' => __('23k Views (chinese)', 'sakura'),/*23k 次访问(中式)*/
));
$options[] = array(
'name' => __('Comment image upload API', 'sakura'),/*评论图片上传接口*/
'id' => 'img_upload_api',
'std' => "imgur",
'type' => "radio",
'options' => array(
'imgur' => __('Imgur (https://imgur.com)', 'sakura'),
'smms' => __('SM.MS (https://sm.ms)', 'sakura')
));
$options[] = array(
'name' => __('Imgur Client ID', 'sakura'),
'desc' => __('Register your application <a href="https://api.imgur.com/oauth2/addclient">here</a>, note we only need the Client ID here.', 'sakura'),
'id' => 'imgur_client_id',
'std' => '',
'type' => 'text');
$options[] = array(
'name' => __('SM.MS Secret Token', 'sakura'),
'desc' => __('Register your application <a href="https://sm.ms/home/apitoken">here</a>.', 'sakura'),
'id' => 'smms_client_id',
'std' => '',
'type' => 'text');
$options[] = array(
'name' => __('Comment images proxy', 'sakura'),
'desc' => __('A front-ed proxy for the uploaded images. Leave it blank if you do not need.', 'sakura'),
'id' => 'cmt_image_proxy',
'std' => 'https://images.weserv.nl/?url=',
'type' => 'text');
$options[] = array(
'name' => __('Imgur upload proxy', 'sakura'),
'desc' => __('A back-ed proxy to upload images. You may set a self hosted proxy with Nginx, following my <a href="https://2heng.xin/2018/06/06/javascript-upload-images-with-imgur-api/">turtal</a>. This feature is mainly for Chinese who cannot access to Imgur due to the GFW. The default and official setting is 【<a href="https://api.imgur.com/3/image/">https://api.imgur.com/3/image/</a>】', 'sakura'),
'id' => 'imgur_upload_image_proxy',
'std' => 'https://api.imgur.com/3/image/',
'type' => 'text');
$options[] = array(
'name' => __('Enable live search', 'sakura'),/*启用实时搜索*/
'desc' => __('Real-time search in the foreground, call the Rest API to update the cache every hour, you can manually set the cache time in functions.php'),/*前台实现实时搜索,调用 Rest API 每小时更新一次缓存,可在 functions.php 里手动设置缓存时间*/