| 1 |
<?php |
| 2 |
if(did_action('init')){ |
| 3 |
if(empty(CDN_NAME)){ |
| 4 |
wp_die('你没开启云存储', '你没开启云存储', ['response'=>404]); |
| 5 |
} |
| 6 |
|
| 7 |
$post = get_post(get_query_var('p')); |
| 8 |
$remote = get_query_var(CDN_NAME); |
| 9 |
|
| 10 |
if(empty($remote)){ |
| 11 |
wp_die('文件名不能为空', '文件名不能为空', ['response'=>404]); |
| 12 |
} |
| 13 |
|
| 14 |
if(empty($post)){ |
| 15 |
wp_die('文章不存在', '文章不存在', ['response'=>404]); |
| 16 |
} |
| 17 |
|
| 18 |
$filename = pathinfo($remote, PATHINFO_FILENAME); |
| 19 |
$url = ''; |
| 20 |
|
| 21 |
if(preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', do_shortcode($post->post_content), $matches)){ |
| 22 |
foreach($matches[1] as $image_url){ |
| 23 |
if($filename == md5($image_url)){ |
| 24 |
$url = $image_url; |
| 25 |
break; |
| 26 |
} |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
if(!$url){ |
| 31 |
wp_die('文章没有该图片', '文章没有该图片', ['response'=>404]); |
| 32 |
} |
| 33 |
|
| 34 |
if(wpjam_doing_debug()){ |
| 35 |
echo $url; |
| 36 |
exit; |
| 37 |
} |
| 38 |
|
| 39 |
$response = wpjam_if_error(wp_safe_remote_get($url), 'die'); |
| 40 |
$content_type = wp_remote_retrieve_header($response, 'content-type'); |
| 41 |
|
| 42 |
if(!preg_match('|^image/|', $content_type)){ |
| 43 |
wp_die('不是图片', '', ['response'=>403]); |
| 44 |
} |
| 45 |
|
| 46 |
header('Content-Type: '.$content_type); |
| 47 |
|
| 48 |
echo $response['body']; |
| 49 |
|
| 50 |
exit; |
| 51 |
} |
| 52 |
|
| 53 |
add_action('init', function(){ |
| 54 |
$GLOBALS['wp']->add_query_var(CDN_NAME); |
| 55 |
|
| 56 |
add_rewrite_rule(CDN_NAME.'/([0-9]+)/image/([^/]+)?$', 'index.php?p=$matches[1]&'.CDN_NAME.'=$matches[2]', 'top'); |
| 57 |
|
| 58 |
add_action('template_redirect', function(){ |
| 59 |
if(get_query_var(CDN_NAME)){ |
| 60 |
include __FILE__; |
| 61 |
} |
| 62 |
}, 5); |
| 63 |
|
| 64 |
add_filter('the_content', function($content){ |
| 65 |
if(!is_singular() || get_post_status() !== 'publish'){ |
| 66 |
return $content; |
| 67 |
} |
| 68 |
|
| 69 |
if(!preg_match_all('/<img.*?src=[\'"](.*?)[\'"].*?>/i', $content, $matches)){ |
| 70 |
return $content; |
| 71 |
} |
| 72 |
|
| 73 |
$search = $replace = []; |
| 74 |
|
| 75 |
foreach($matches[0] as $i => $img_tag){ |
| 76 |
$img_url = $matches[1][$i]; |
| 77 |
|
| 78 |
if($img_url && wpjam_is_external_url($img_url, false)){ |
| 79 |
$img_type = $img_type == 'png' ? 'png' : 'jpg'; |
| 80 |
$img_replace = CDN_HOST.'/'.CDN_NAME.'/'.get_the_ID().'/image/'.md5($img_url).'.'.$img_type; |
| 81 |
$search[] = $img_tag; |
| 82 |
$replace[] = str_replace($img_url, $img_replace, $img_tag); |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
return $search ? str_replace($search, $replace, $content) : $content; |
| 87 |
}, 4); |
| 88 |
}); |
| 89 |
|