$value) {
$input[$key] = sanitize_text_field(wp_unslash($value));
}
} else {
$input = sanitize_text_field(wp_unslash($input));
}
return $input;
}
// 引入CSS文件
function yunpan_settings_enqueue_styles($hook_suffix) {
if ($hook_suffix !== 'toplevel_page_yunpan-settings') {
return;
}
wp_enqueue_style('yunpan-settings-style', plugin_dir_url(__FILE__) . 'assets/css/main.css',array(),'1.0.0');
}
//全局设置
function yunpan_settings_render_folder_id() {
$stored_token = get_option('yunpan_access_token');
$stored_expiry = get_option('yunpan_token_expiry');
$current_time = current_time('timestamp');
$total_left_space_str = '0TB';
$total_left_traffic_str= '0TB';
if ($stored_token && $stored_expiry && $stored_expiry > $current_time ) {
$user_info = yunpan_open_request('api/v1/user/info',[],$stored_token,'GET');
if (is_wp_error($user_info)) {
// Handle error
add_settings_error('yunpan_settings_group_storage', 'userinfo_error', $user_info->get_error_message(), 'error');
set_transient('settings_errors', get_settings_errors(), 30);
} else {
if(isset($user_info['data']['spacePermanent'])){
$total_left_space =round(($user_info['data']['spacePermanent']+$user_info['data']['spaceTemp']-$user_info['data']['spaceUsed'])/(1024*1024*1024*1024),2);
$total_left_space_str = $total_left_space>1?$total_left_space.' TB':round(($user_info['data']['spacePermanent']+$user_info['data']['spaceTemp']-$user_info['data']['spaceUsed'])/(1024*1024),2).' GB';
$total_left_traffic = round($user_info['data']['directTraffic']/(1024*1024*1024*1024),2);
$unit = 'TB';
if($total_left_traffic<1){
$unit = 'GB';
$total_left_traffic = round($user_info['data']['directTraffic']/(1024*1024*1024),2);
if($total_left_traffic<1){
$unit = 'MB';
$total_left_traffic = round($user_info['data']['directTraffic']/(1024*1024),2);
}
}
$total_left_traffic_str = $total_left_traffic.$unit;
}
}
}
$options = get_option('yunpan_settings_storage');
if(!$options){
$options['folder_id'] = '';
}
echo " 剩余容量:".esc_html($total_left_space_str)." 剩余直链流量:".esc_html($total_left_traffic_str)."";
echo "
在123云盘中,选择用于同步的开启了直链空间的文件夹,右键-复制文件夹ID,获取文件夹ID。
";
}
function yunpan_settings_render_access_key() {
$options = get_option('yunpan_settings_storage');
if(!$options){
$options['access_key'] = '';
}
echo "";
echo "在123云盘开放平台中注册开发者账号后,即可获取accessKey。
";
}
function yunpan_settings_render_secret_key() {
$options = get_option('yunpan_settings_storage');
if(!$options){
$options['secret_key'] = '';
}
echo "";
echo "在123云盘开放平台中注册开发者账号后,即可获取secretKey。
";
}
function yunpan_settings_render_local_folder() {
$options = get_option('yunpan_settings_storage');
if(!$options){
$options['local_folder'] = '';
}
echo "";
echo "附件在服务器上的存储位置,默认为wp-content/uploads (注意不要以“/”开头和结尾),根目录请输入.。
";
}
function yunpan_settings_render_no_thumbnail() {
$options = get_option('yunpan_settings_storage');
$checked = (isset($options['no_thumbnail']) && $options['no_thumbnail']==1) ? 'checked' : '';
echo "";
echo "建议不勾选。
";
}
//自定义域名
function yunpan_settings_render_pan_domain(){
$options = get_option('yunpan_settings_storage');
if(!$options || !isset($options['pan_domain'])){
$options['pan_domain'] = '';
}
echo "";
echo "默认为https://vip.123pan.com/,若需启用个性域名,请在直链流量包-域名管理区域进行设置,并填写到此文本框中。
";
}
function yunpan_settings_render_no_backup() {
$options = get_option('yunpan_settings_storage');
$checked = (isset($options['no_backup']) && $options['no_backup']==1) ? 'checked' : '';
echo "";
echo "建议不勾选。
";
}
function yunpan_settings_render_referer_protection() {
echo "前往直链流量包设置Referer鉴权以实现保护。
";
}
function yunpan_settings_render_save_button(){
echo " |
";
}
function yunpan_settings_render_start_sync() {
echo "如果是首次同步,执行时间将会非常长(根据你的历史附件数量和单附件大小),有可能会因为执行时间过长,导致页面显示超时或者报错。所以,建议附件数量过多的用户,使用官方的openapi实现。 ";
echo " |
";
}
function yunpan_settings_render_relace_domain(){
echo '此功能会替换文章以及设置的特色图片(题图)等使用的资源链接,并将新域名设置为同步域名,请填写完整域名,替换立即生效且无法撤销,如果是首次替换,请注意备份!
';
}
function yunpan_settings_render_old_domain() {
$options = get_option('yunpan_settings_db');
if(!$options){
$options['old_domain'] = '';
}
echo "";
echo "123云盘默认域名为:https://vip.123pan.cn
";
}
function yunpan_settings_render_new_domain() {
$options = get_option('yunpan_settings_db');
if(!$options){
$options['new_domain'] = '';
}
echo "";
}
function yunpan_settings_render_save_domain(){
echo " |
";
}
// 云盘配置选项表单
function yuanpan_settings_page() {
if ($settings_errors = get_transient('settings_errors')) {
foreach ($settings_errors as $error) {
add_settings_error($error['setting'], $error['code'], $error['message'], $error['type']);
}
delete_transient('settings_errors');
}
?>
get_error_message(), 'error');
set_transient('settings_errors', get_settings_errors(), 30);
wp_redirect(admin_url('admin.php?page=yunpan-settings'));
exit;
}
if($token){
$user_info = yunpan_open_request('api/v1/user/info',[],$token,'GET');
if (is_wp_error($user_info)) {
add_settings_error('yunpan_settings_group_storage', 'userinfo_error', $user_info->get_error_message(), 'error');
set_transient('settings_errors', get_settings_errors(), 30);
wp_redirect(admin_url('admin.php?page=yunpan-settings'));
exit;
} else {
if($user_info['data']['directTraffic']==0){
add_settings_error('yunpan_settings_group_storage', 'settings_updated', '请先开通会员并确保直链可用流量余额充足', 'error');
set_transient('settings_errors', get_settings_errors(), 30);
wp_redirect(admin_url('admin.php?page=yunpan-settings'));
exit;
}
}
//开始设置目录id
$folderSetRes = yunpan_open_request('api/v1/direct-link/enable',['fileID'=>sanitize_text_field(wp_unslash(isset($_POST['yunpan_settings_storage']['folder_id'])?$_POST['yunpan_settings_storage']['folder_id']:''))],$token);
if (is_wp_error($folderSetRes)) {
// Handle error
add_settings_error('yunpan_settings_group_storage', 'folderset_error', $folderSetRes->get_error_message(), 'error');
set_transient('settings_errors', get_settings_errors(), 30);
wp_redirect(admin_url('admin.php?page=yunpan-settings'));
exit;
}
else if($folderSetRes['code']!=0){
add_settings_error('yunpan_settings_group_storage', 'settings_updated', $folderSetRes['message'], 'error');
set_transient('settings_errors', get_settings_errors(), 30);
wp_redirect(admin_url('admin.php?page=yunpan-settings'));
exit;
}
}
update_option('yunpan_settings_storage', $options);
$db_options = get_option('yunpan_settings_db');
$pan_domain = (isset($db_options['new_domain']) && $db_options['new_domain']) ?$db_options['new_domain']:'https://vip.123pan.cn/';
if($user_info['data']['isHideUID']&&$pan_domain!='https://vip.123pan.cn/'){
$uid_path = '';
}
else{
$uid_path = $user_info['data']['uid'].'/';
}
// Check if the last character is not a "/"
if (substr($pan_domain, -1) !== '/') {
// If not, add the "/"
$pan_domain .= '/';
}
$default_server_url = $pan_domain.$uid_path.urlencode($folderSetRes['data']['filename']);
update_option('yunpan_upload_url_path', $default_server_url);
update_option('yunpan_upload_folder_name', $folderSetRes['data']['filename'].'/');
update_option('yunpan_upload_folder_path', $pan_domain.$uid_path);
add_settings_error('yunpan_settings_group_storage', 'settings_updated', '设置成功', 'updated');
set_transient('settings_errors', get_settings_errors(), 30);
$new_url = admin_url('admin.php?page=yunpan-settings');
wp_redirect($new_url, 301); // 301 indicates a permanent redirect
exit;
}
add_settings_error('yunpan_settings_group_storage', 'settings_updated', '保存失败.', 'updated');
set_transient('settings_errors', get_settings_errors(), 30);
wp_redirect(admin_url('admin.php?page=yunpan-settings'));
exit;
}
add_action('admin_post_save_yunpan_settings', 'yunpan_handle_form_submission');
//本地所有文件上传提交
function yunpan_handle_form_sync_submission() {
if (
! isset($_POST['save_sync_settings_nonce']) ||
! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['save_sync_settings_nonce'])), 'save_sync_settings_action')
) {
wp_die('Security check failed');
}
$options = get_option('yunpan_settings_storage');
if(!$options){
add_settings_error('yunpan_settings_group_storage','settings_updated', '请先完成保存配置', 'updated');
set_transient('settings_errors', get_settings_errors(), 30);
wp_redirect(admin_url('admin.php?page=yunpan-settings'));
exit;
}
$token = yunpan_get_yp_token();
$finish_num = 0;
if(isset($_POST['action']) && sanitize_text_field(wp_unslash($_POST['action']))=='save_sync_settings'){
$finish_num = yunpan_send_files_to_server($token);
}
add_settings_error('yunpan_settings_group_storage', 'settings_updated', '已完成 '.$finish_num.' 项历史文件同步', 'updated');
if(!$finish_num || $finish_num==0){
// add_settings_error('yunpan_settings_group_storage', 'settings_updated', '已完成 '.$finish_num.' 同步失败:404', 'updated');
}
set_transient('settings_errors', get_settings_errors(), 30);
wp_redirect(admin_url('admin.php?page=yunpan-settings'));
exit;
}
add_action('admin_post_save_sync_settings', 'yunpan_handle_form_sync_submission');
//域名批量替换提交
function yunpan_handle_form_db_submission() {
if (
! isset($_POST['save_db_settings_nonce']) ||
! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['save_db_settings_nonce'])), 'save_db_settings_action')
) {
wp_die('Security check failed');
}
$options = get_option('yunpan_settings_storage');
if(!$options){
add_settings_error('yunpan_settings_group_storage','settings_updated', '请先完成保存配置', 'updated');
set_transient('settings_errors', get_settings_errors(), 30);
wp_redirect(admin_url('admin.php?page=yunpan-settings'));
exit;
}
$options = get_option('yunpan_settings_db');
if(isset($_POST['action']) && sanitize_text_field(wp_unslash($_POST['action']))=='save_db_settings'){
$old_domain = isset($_POST['yunpan_settings_db']['old_domain'])?sanitize_text_field(wp_unslash($_POST['yunpan_settings_db']['old_domain'])):'';
$new_domain = isset($_POST['yunpan_settings_db']['new_domain'])?sanitize_text_field(wp_unslash($_POST['yunpan_settings_db']['new_domain'])):'';
global $wpdb;
if($old_domain && $new_domain){
// Replace in wp_posts
$wpdb->query($wpdb->prepare(
"UPDATE {$wpdb->posts} SET guid = REPLACE(guid, %s, %s) WHERE post_type = 'attachment'",
$old_domain, $new_domain
));
$wpdb->query($wpdb->prepare(
"UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)",
$old_domain, $new_domain
));
// Replace in wp_postmeta
$wpdb->query($wpdb->prepare(
"UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s)",
$old_domain, $new_domain
));
$yunpan_upload_folder_name = substr(get_option('yunpan_upload_folder_name'),0,-1);
$parsed_url = wp_parse_url(get_option('yunpan_upload_folder_path'));
$yunpan_upload_uid_path = $parsed_url['path'];
if (substr($new_domain, -1) == '/') {
// If not, add '/'
$new_domain = substr($new_domain,0,-1);
}
$default_server_url = $new_domain.$yunpan_upload_uid_path.urlencode($yunpan_upload_folder_name);
update_option('yunpan_upload_url_path', $default_server_url);
update_option('yunpan_upload_folder_path', $new_domain.$yunpan_upload_uid_path);
}
}
$options['old_domain'] = $old_domain;
$options['new_domain'] = $new_domain;
update_option('yunpan_settings_db', $options);
add_settings_error('yunpan_settings_group_db', 'settings_updated', '域名替换已完成', 'updated');
set_transient('settings_errors', get_settings_errors(), 30);
wp_redirect(admin_url('admin.php?page=yunpan-settings'));
exit;
}
add_action('admin_post_save_db_settings', 'yunpan_handle_form_db_submission');
function yunpan_get_all_media_files() {
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => -1, // Get all attachments
);
$media_files = get_posts($args);
$result = array();
foreach ($media_files as $media_file) {
// Get the main attachment URL
$main_attachment_url = wp_get_attachment_url($media_file->ID);
// Get attachment metadata
$attachment_metadata = wp_get_attachment_metadata($media_file->ID);
// Prepare the result entry
$entry = array(
'id' => $media_file->ID,
'title' => $media_file->post_title,
'main_attachment' => $main_attachment_url,
'thumbnails' => array(),
);
// Add all thumbnail sizes
if (isset($attachment_metadata['sizes'])) {
foreach ($attachment_metadata['sizes'] as $size => $size_info) {
$thumbnail_url = wp_get_attachment_image_url($media_file->ID, $size);
if ($thumbnail_url) {
$entry['thumbnails'][$size] = $thumbnail_url;
}
}
}
$result[] = $entry;
}
return $result;
}
//批量上传本地文件到云盘
function yunpan_send_files_to_server($token) {
$finish_num =0;
$media_files = yunpan_get_all_media_files();
foreach ($media_files as $file) {
// Process main attachment
$file_path = get_attached_file($file['id']);
//exit(print_r($file_path));
$numer = yunpan_process_file($file_path, $token);
$finish_num +=$numer;
if($numer==0)
continue;
// Process thumbnails
foreach ($file['thumbnails'] as $size => $thumbnail_url) {
$thumbnail_path = yunpan_convert_url_to_local_path($thumbnail_url);
$child_number = yunpan_process_file($thumbnail_path, $token);
$finish_num +=$child_number;
}}
return $finish_num;
}
function yunpan_process_file($file_path, $token) {
$finish_num = 0;
// Get the site's domain
$site_url = get_site_url();
$parsed_url = wp_parse_url($site_url);
$domain = isset($parsed_url['host']) ? $parsed_url['host'] : '';
//判断是否有当前站点域名 如果没有 说明已经是外部链接
if (strpos($file_path, $domain) === false && strpos($file_path,'http')!==false) {
return;
}
$file_type = yunpan_get_mime_type($file_path);
$options = get_option('yunpan_settings_storage');
$folder_id = $options['folder_id'];
$file_true_path = yunpan_get_relative_upload_path($file_path);
$pre_response = yunpan_open_request('upload/v1/file/create',['parentFileID' => $folder_id,'etag'=>md5_file($file_path),
'size'=>yunpan_get_file_size($file_path),'containDir'=>true,'fileName'=>$file_true_path],$token,'POST',true);
if (is_wp_error($pre_response)) {
// Handle error
exit;
}
if($pre_response['code'] ==0){
if($pre_response['data']['reuse']){//秒传
$file_id = $pre_response['data']['fileID'];
$file_url = yunpan_open_request('api/v1/direct-link/url',['fileID'=>$file_id],$token,'GET');
yunpan_update_attachment_metadata_with_attachment_id($file->ID,$file_url['data']['url'],$file_id);
$finish_num++;
return $finish_num;
}
else{
//需要分片
if($pre_response['data']['sliceSize']$pre_response['data']['preuploadID']],$token);
if($complate_response['code']==0){//异步轮询接口
if($complate_response['data']['fileID'] && $complate_response['data']['async']==0){
$finish_num++;
$file_id = $complate_response['data']['fileID'];
$file_url = yunpan_open_request('api/v1/direct-link/url',['fileID'=>$file_id],$token);
yunpan_update_attachment_metadata_with_attachment_id($file->ID,$file_url['data']['url'],$file_id);
}
}
}
return;
}
//获取上传地址
$uploadDataRes = yunpan_open_request('/upload/v1/file/get_upload_url',['preuploadID'=>$pre_response['data']['preuploadID'],'sliceNo'=>1],$token);
if($uploadDataRes['code'] ==0 && $uploadDataRes['data']['presignedURL']){
$url = $uploadDataRes['data']['presignedURL']; // Change to your target URL
$file_handle = yunpan_read_file_content($file_path);
$file_size = yunpan_get_file_size($file_path);
$args = array(
'method' => 'PUT',
'headers' => array(
'Content-Type' => $file_type,
'Content-Length' => $file_size,
),
'body' => $file_handle,
);
$response = wp_remote_request($url, $args);
if (is_wp_error($response)) {
} else {
if($response['response']['message']=='OK' && $response['response']['code']==200){
$complate_response = yunpan_open_request('upload/v1/file/upload_complete',['preuploadID'=>$pre_response['data']['preuploadID']],$token);
if($complate_response['code']==0){//异步轮询接口
$finish_num++;
if($complate_response['data']['fileID'] && $complate_response['data']['async']==0){
$file_id = $complate_response['data']['fileID'];
$file_url = yunpan_open_request('api/v1/direct-link/url',['fileID'=>$file_id],$token,'GET');
yunpan_update_attachment_metadata_with_attachment_id($file->ID,$file_url['data']['url'],$file_id);
}
}
}
}
}
}
}
return $finish_num;
}
function yunpan_get_attachment_id_by_url($url) {
global $wpdb;
return $wpdb->get_var( $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE guid = %s", $url
));
}
function yunpan_convert_url_to_local_path($url) {
$upload_dir = wp_upload_dir();
$upload_base_url = $upload_dir['baseurl'];
$upload_base_dir = $upload_dir['basedir'];
if (strpos($url, $upload_base_url) === 0) {
$relative_path = str_replace($upload_base_url, '', $url);
$local_path = $upload_base_dir . $relative_path;
return $local_path;
}
return false;
}
//避免上传插件/主题时出现同步到kodo的情况
if (isset($_SERVER['REQUEST_URI']) && substr_count(sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])), '/update.php') <= 0) {
add_filter('wp_handle_upload', 'yunpan_auto_upload_to_api', 50);
add_filter('wp_generate_attachment_metadata', 'yunpan_upload_thumbnails_to_api', 100);
add_filter('wp_save_image_editor_file', 'yunpan_save_image_editor_file', 101);
}
function yunpan_save_image_editor_file($override){
add_filter('wp_update_attachment_metadata', 'yunpan_image_editor_file_do');
return $override;
}
function yunpan_image_editor_file_do($metadata){
return yunpan_upload_thumbnails_to_api($metadata);
}
//触发云盘上传操作
function yunpan_auto_upload_to_api($upload) {
//获取token
$token = yunpan_get_yp_token();
$options = get_option('yunpan_settings_storage');
$no_backup = isset($options['no_backup']) ? $options['no_backup'] : false;
$mime_types = get_allowed_mime_types();
$image_mime_types = [
$mime_types['jpg|jpeg|jpe'],
$mime_types['gif'],
$mime_types['png'],
$mime_types['bmp'],
$mime_types['tiff|tif'],
$mime_types['webp'],
$mime_types['ico'],
$mime_types['heic'],
];
// 例如mp4等格式 上传后根据配置选择是否删除 删除后媒体库会显示默认图片 点开内容是正常的
// 图片在缩略图处理
if (!in_array($upload['type'], $image_mime_types)) {
if (isset($upload['file']) && $upload['type']) {
$file_path = $upload['file'];
$file_type = $upload['type'];
// Store the original file path in post meta
$file_id = yunpan_upload_file_to_external_server($file_path, $file_type, $token);
if($file_id && is_numeric($file_id)){
add_action('add_attachment', function($post_ID) use ($file_path,$file_id) {
update_post_meta($post_ID, '_yunpan_original_file_path', $file_path);
update_post_meta($post_ID, '_yunpan_file_id', $file_id);
});
}
if (file_exists($file_path) && $no_backup) {
yunpan_delete_local_file($file_path);
}
}
}
return $upload;
}
//删除远端文件,删除文件时触发
function yunpan_delete_remote_attachment($post_id)
{
$meta = wp_get_attachment_metadata($post_id);
$token = yunpan_get_yp_token();
$yunpan_upload_folder_name = get_option('yunpan_upload_folder_name');
$yunpan_upload_folder_path = get_option('yunpan_upload_folder_path');
if (!empty($meta['file'])) {
$deleteObjects = [];
// meta['file']的格式为 "2020/01/wp-bg.png"
$file_path = $meta['file'];
$dirname = $yunpan_upload_folder_name;
$base_dir = dirname($file_path) . '/';
$deleteObjects[] = $dirname.$file_path;
// 超大图原图
if (!empty($meta['original_image'])) {
$deleteObjects[] = $dirname.$base_dir. $meta['original_image'];
}
// 删除缩略图
if (!empty($meta['sizes'])) {
foreach ($meta['sizes'] as $val) {
$deleteObjects[] = $dirname.$base_dir . $val['file'];
}
}
$backup_sizes = get_post_meta($post_id, '_wp_attachment_backup_sizes', true);
if (is_array($backup_sizes)) {
foreach ($backup_sizes as $size) {
$deleteObjects[] = $dirname.$base_dir . $size['file'];
}
}
yunpan_open_request('api/v1/file/base-path/trash',['filePathList'=>$deleteObjects],$token);
} else {
$link = wp_get_attachment_url($post_id);
if ($link) {
// 获取链接删除
$file_info = explode($yunpan_upload_folder_path, $link);
if (isset($file_info[1])) {
yunpan_open_request('api/v1/file/base-path/trash',['filePathList'=>[$file_info[1]]],$token);
}
}
}
}
add_action('delete_attachment', 'yunpan_delete_remote_attachment');
// 上传 缩略图
function yunpan_upload_thumbnails_to_api($metadata) {
$upload_dir = wp_upload_dir();
if (empty($metadata['file'])) {
return $metadata;
}
$options = get_option('yunpan_settings_storage');
$no_thumbnail = isset($options['no_thumbnail']) ? $options['no_thumbnail'] : false;
$no_backup = isset($options['no_backup']) ? $options['no_backup'] : false;
//获取上传路径
$wp_uploads = wp_upload_dir();
$basedir = $wp_uploads['basedir'];
// Get token
$token = yunpan_get_yp_token();
// Get the path to the original file
$file_path = $basedir . '/' . $metadata['file'];
$file_path = str_replace('./', '', $file_path);
if ($file_path) {
$file_type = wp_check_filetype($file_path);
yunpan_upload_file_to_external_server($file_path, $file_type['type'], $token);
if ($no_backup) {
yunpan_delete_local_file($file_path);
}
}
// Upload all generated sizes
if ($metadata && !$no_thumbnail) {
foreach ($metadata['sizes'] as $size => $size_info) {
$size_path = $upload_dir['basedir'] . '/' . dirname($metadata['file']) . '/' . $size_info['file'];
$size_type = wp_check_filetype($size_path);
if (file_exists($size_path)) {
yunpan_upload_file_to_external_server($size_path, $size_type['type'], $token);
}
if ($no_backup) {
yunpan_delete_local_file($size_path);
}
}
}
return $metadata;
}
function yunpan_upload_file_to_external_server($file_path,$file_type,$token){
$options = get_option('yunpan_settings_storage');
$folder_id = $options['folder_id'];
$file_true_path = yunpan_get_relative_upload_path($file_path);
$pre_response =yunpan_open_request('upload/v1/file/create',['parentFileID' => $folder_id,'etag'=>md5_file($file_path),
'size'=>yunpan_get_file_size($file_path),'containDir'=>true,'fileName'=>$file_true_path],$token,'POST',true);//
if (is_wp_error($pre_response)) {
// Handle error
exit;
}
if($pre_response['code'] ==0){
if($pre_response['data']['reuse']){//秒传
$file_id = $pre_response['data']['fileID'];
$file_url = yunpan_open_request('api/v1/direct-link/url',['fileID'=>$file_id],$token,'GET');
set_transient('yunpan_file_id', $file_id, 60);
return $file_id;
}
else{
//需要分片
if($pre_response['data']['sliceSize']$pre_response['data']['preuploadID']],$token);
$md5_verify_result = 1;
if($md5_verify_result){
$complate_response = yunpan_open_request('upload/v1/file/upload_complete',['preuploadID'=>$pre_response['data']['preuploadID']],$token);
if($complate_response['code']==0){//异步轮询接口
if($complate_response['data']['fileID'] && $complate_response['data']['async']==0){
$file_id = $complate_response['data']['fileID'];
$file_url = yunpan_open_request('api/v1/direct-link/url',['fileID'=>$file_id],$token,'GET');
set_transient('yunpan_file_id', $file_id, 60);
return $file_id;
}
elseif($complate_response['data']['async']==1){
sleep(3);
$async_data = yunpan_open_request('upload/v1/file/upload_async_result',['preuploadID'=>$pre_response['data']['preuploadID']],$token);
if(isset($async_data['data']['fileID']) && $async_data['data']['fileID']){
$file_id = $async_data['data']['fileID'];
$file_url = yunpan_open_request('api/v1/direct-link/url2',['fileID'=>$file_id],$token,'GET');
set_transient('yunpan_file_id', $file_id, 60);
return $file_id;
}
}
}
}
return ;
}
//小文件获取上传地址
$uploadDataRes = yunpan_open_request('/upload/v1/file/get_upload_url',['preuploadID'=>$pre_response['data']['preuploadID'],'sliceNo'=>1],$token);
if($uploadDataRes['code'] ==0 && $uploadDataRes['data']['presignedURL']){
$url = $uploadDataRes['data']['presignedURL']; // Change to your target URL
$file_handle = yunpan_read_file_content($file_path);
$file_size = yunpan_get_file_size($file_path);
$args = array(
'method' => 'PUT',
'headers' => array(
'Content-Type' => $file_type,
'Content-Length' => $file_size,
),
'body' => $file_handle,
);
$response = wp_remote_request($url, $args);
if (is_wp_error($response)) {
} else {
if($response['response']['message']=='OK' && $response['response']['code']==200){
//文件md5 校验
//$md5_verify = yunpan_open_request('upload/v1/file/list_upload_parts',['preuploadID'=>$pre_response['data']['preuploadID']],$token);
$complate_response = yunpan_open_request('upload/v1/file/upload_complete',['preuploadID'=>$pre_response['data']['preuploadID']],$token);
if($complate_response['code']==0){//异步轮询接口
if($complate_response['data']['fileID'] && $complate_response['data']['async']==0){
$file_id = $complate_response['data']['fileID'];
$file_url = yunpan_open_request('api/v1/direct-link/url',['fileID'=>$file_id],$token);
set_transient('yunpan_external_upload_url', $file_url, 60);
return $file_id;
}
elseif($complate_response['data']['async']==1){
sleep(3);
$async_data = yunpan_open_request('upload/v1/file/upload_async_result',['preuploadID'=>$pre_response['data']['preuploadID']],$token);
if(isset($async_data['data']['fileID']) && $async_data['data']['fileID']){
$file_id = $async_data['data']['fileID'];
$file_url = yunpan_open_request('api/v1/direct-link/url',['fileID'=>$file_id],$token,'GET');
set_transient('yunpan_external_upload_url', $file_url['data']['url'], 60);
return $file_id;
}
}
}
}
}
}
}
}
}
//切片上传
function yunpan_put_part($url, $part_stream, $part_size) {
// 读取文件内容
$part_data = stream_get_contents($part_stream);
// 准备请求参数
$args = array(
'method' => 'PUT',
'headers' => array(
'Content-Type' => 'application/octet-stream', // 设置为二进制流
'Content-Length' => $part_size, // 指定文件块大小
),
'body' => $part_data, // 传递二进制文件内容
'timeout' => 600, // 600秒超时
'sslverify' => false, // 允许 SSL 验证(如果服务器证书有效的话可以设为 true)
);
// 发送请求
$response = wp_remote_request($url, $args);
// 检查请求是否有错误
if (is_wp_error($response)) {
throw new ErrorException('分片传输失败,错误信息:' . esc_html($response->get_error_message()));
}
// 获取 HTTP 状态码
$status_code = wp_remote_retrieve_response_code($response);
// 如果返回状态码不是 200,则抛出异常
if ($status_code !== 200) {
throw new ErrorException('分片传输错误,错误码:' . esc_html($status_code) . ',错误信息:' . esc_html(wp_remote_retrieve_body($response)));
}
}
add_action('admin_notices', 'yunpan_upload_error_notice');
function yunpan_upload_error_notice() {
if ($error = get_transient('yunpan_upload_error')) {
// Display the error message
echo '';
delete_transient('yunpan_upload_error');
}
}
function yunpan_init_filesystem() {
global $wp_filesystem;
if ( ! function_exists( 'request_filesystem_credentials' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
if ( ! WP_Filesystem() ) {
return false;
}
return true;
}
// Get file content using WP_Filesystem
function yunpan_read_file_content($file_path) {
global $wp_filesystem;
if (!yunpan_init_filesystem()) {
return new WP_Error('filesystem_error', 'Could not initialize WP_Filesystem');
}
return $wp_filesystem->get_contents($file_path);
}
// Get file size using WP_Filesystem
function yunpan_get_file_size($file_path) {
global $wp_filesystem;
return $wp_filesystem->size($file_path);
}
// Upload file to 123pan using WP_Filesystem-based content
function yunpan_upload_file_to_123pan($file_path, $file_type, $url) {
$file_contents = yunpan_read_file_content($file_path);
if (is_wp_error($file_contents)) {
return $file_contents;
}
$file_size = yunpan_get_file_size($file_path);
$args = array(
'method' => 'PUT',
'headers' => array(
'Content-Type' => $file_type,
'Content-Length' => $file_size,
),
'body' => $file_contents,
);
return wp_remote_request($url, $args);
}
// Slice and upload file in chunks using WP_Filesystem
function yunpan_slice_and_upload_file($file_path, $chunk_size, $token, $pre_response) {
if (!yunpan_init_filesystem()) {
return new WP_Error('filesystem_error', 'Could not initialize WP_Filesystem');
}
$res = [];
$file_contents = yunpan_read_file_content($file_path);
if (is_wp_error($file_contents)) {
return $file_contents;
}
$total_size = strlen($file_contents);
$num_chunks = ceil($total_size / $chunk_size);
for ($i = 0; $i < $num_chunks; $i++) {
$part_num = $i + 1;
$start = $i * $chunk_size;
$part_data = substr($file_contents, $start, $chunk_size);
$res_data = yunpan_open_request('/upload/v1/file/get_upload_url', [
'preuploadID' => $pre_response['data']['preuploadID'],
'sliceNo' => $part_num
], $token);
$args = array(
'method' => 'PUT',
'headers' => array(
'Content-Type' => 'application/octet-stream',
'Content-Length' => strlen($part_data),
),
'body' => $part_data,
'timeout' => 600,
'sslverify' => false,
);
$response = wp_remote_request($res_data['data']['presignedURL'], $args);
if (is_wp_error($response)) {
throw new ErrorException('分片传输失败,错误信息:' . esc_html($response->get_error_message()));
}
$status_code = wp_remote_retrieve_response_code($response);
if ($status_code !== 200) {
throw new ErrorException('分片传输错误,错误码:' . esc_html($status_code) . ',错误信息:' . esc_html(wp_remote_retrieve_body($response)));
}
}
}
//切片
//发送请求
function yunpan_open_request($api_path, $data, $token,$method="POST",$add_header=false){
// Prepare the request body as JSON
$api_url = 'https://open-api.123pan.com/'.$api_path;//https://open-api.123pan.com/
if($add_header){
$args = array(
'headers' => array(
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
'Platform' =>'open_platform',
'Wp-Request'=>'1',
),
);
}
else{
$args = array(
'headers' => array(
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
'Platform' =>'open_platform',
// 'App-Version'=>3
),
);
}
if($method=='GET'){
$api_url = add_query_arg($data, $api_url);
$response = wp_remote_get($api_url, $args);
}
else{
if($data){
$args['body']=wp_json_encode($data);
}
$response = wp_remote_post($api_url, $args);
}
if (is_wp_error($response)) {
return $response;
}
$response_code = wp_remote_retrieve_response_code($response);
if ($response_code != 200) {
return new WP_Error('upload_failed', 'Failed to upload file to external server: ' . $response_code);
}
$response_body = wp_remote_retrieve_body($response);
$response_data = json_decode($response_body, true);
return $response_data;
}
//获取token
function yunpan_get_yp_token($client_id='',$client_secret='',$save=0){
$stored_token = get_option('yunpan_access_token');
$stored_expiry = get_option('yunpan_token_expiry');
$current_time = current_time('timestamp');
if ($stored_token && $stored_expiry && $stored_expiry > $current_time && !$save) {
return $stored_token;
}
$options = get_option('yunpan_settings_storage');
$client_id = $client_id?$client_id:$options['access_key']; // Your client ID
$client_secret = $client_secret?$client_secret:$options['secret_key']; // Your client secret
$api_url = 'https://open-api.123pan.com/api/v1/access_token'; // API URL for access token
// Prepare the request body as JSON
$body = wp_json_encode(array(
'clientID' => $client_id,
'clientSecret' => $client_secret,
));
$args = array(
'headers' => array(
'Authorization' => 'Bearer ' . base64_encode($client_id . ':' . $client_secret),
'Content-Type' => 'application/json',
'Platform' =>'open_platform'
),
'body' => $body
);
$response = wp_remote_post($api_url, $args);
if (is_wp_error($response)) {
return $response;
}
$response_code = wp_remote_retrieve_response_code($response);
if ($response_code != 200) {
return new WP_Error('upload_failed', 'Failed to upload file to external server: ' . $response_code);
}
$response_body = wp_remote_retrieve_body($response);
$response_data = json_decode($response_body, true);
if (!isset($response_data['data']['accessToken']) || !isset($response_data['data']['expiredAt'])) {
return new WP_Error('invalid_response', 'accesskey、secretkey验证失败,请查正后再试');
}
// Store the access token and expiration time in the database
update_option('yunpan_access_token', $response_data['data']['accessToken']);
update_option('yunpan_token_expiry', strtotime($response_data['data']['expiredAt']));
return $response_data['data']['accessToken'];
}
//获取上传文件的 实际目录地址
function yunpan_get_relative_upload_path($full_path) {
// Get the WordPress uploads directory
$upload_dir = wp_upload_dir();
$base_dir = $upload_dir['basedir']; // This is the base directory path
// Ensure the full path starts with the base directory
if (strpos($full_path, $base_dir) !== false) {
// Get the relative path by removing the base directory from the full path
$relative_path = str_replace($base_dir . '/', '', $full_path);
return $relative_path;
} else {
return false; // The path is not within the uploads directory
}
}
function yunpan_update_attachment_metadata_with_attachment_id($attachment_id,$new_url,$file_id) {
// Get the new URL from the transient
$file_path = get_attached_file($attachment_id);
update_post_meta($attachment_id, '_yunpan_file_id', $file_id);
}
add_filter('wp_get_attachment_url', 'yunpan_use_external_attachment_url', 10, 2);
//格式化输出图片
function yunpan_use_external_attachment_url($url, $post_id) {
// Retrieve the stored external URL
$external_url = get_post_meta($post_id, '_external_url', true);
if ($external_url) {
return $external_url;
}
return $url;
}
function yunpan_get_mime_type($file) {
// Check if mime_content_type() is available
if (function_exists('mime_content_type')) {
return mime_content_type($file);
}
$mime_types = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
$ext = strtolower(array_pop(explode('.', $file)));
if (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext];
}
return 'application/octet-stream';
}
//删除本地文件
function yunpan_delete_local_file($file)
{
try {
//文件不存在
if (!@file_exists($file)) {
return true;
}
//删除文件
if (!@wp_delete_file($file)) {
return false;
}
return true;
} catch (Exception $ex) {
return false;
}
}