2048) { throw new InvalidArgumentException('Invalid media link.'); } $parts = wp_parse_url($value); if (!is_array($parts) || !in_array($parts['scheme'] ?? '', array('http', 'https'), true) || empty($parts['host']) || isset($parts['user']) || isset($parts['pass']) || isset($parts['fragment'])) { throw new InvalidArgumentException('Use a complete HTTP or HTTPS media link.'); } return $value; } function fiftyw_media_source($input, $file, $kind) { $attachment = absint($input['attachmentId'] ?? 0); if ($attachment) { if (!current_user_can('upload_files') || !current_user_can('edit_post', $attachment) || get_post_type($attachment) !== 'attachment') { throw new InvalidArgumentException('You cannot use this Media Library attachment.'); } $path = realpath(get_attached_file($attachment, true) ?: ''); $uploads = wp_get_upload_dir(); $root = realpath($uploads['basedir']); if (!$path || !$root || !str_starts_with($path, $root . DIRECTORY_SEPARATOR) || !is_file($path)) { throw new InvalidArgumentException('The selected attachment is not a local media file.'); } } else { if (!is_array($file) || ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK || !is_uploaded_file($file['tmp_name'] ?? '')) { throw new InvalidArgumentException('Select a complete media upload or a Media Library file.'); } $path = $file['tmp_name']; } $name = $attachment ? basename($path) : sanitize_file_name($file['name']); $allowed = $kind === 'image' ? array('jpg|jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp') : array('mp4' => 'video/mp4', 'mov' => 'video/quicktime'); $checked = wp_check_filetype_and_ext($path, $name, $allowed); $size = filesize($path); if (!$checked['ext'] || !$checked['type'] || !$size || $size > ($kind === 'image' ? 52428800 : 1073741824)) { throw new InvalidArgumentException('Unsupported media format or file size.'); } if ($kind === 'image' && !in_array(wp_get_image_mime($path), array_values($allowed), true)) { throw new InvalidArgumentException('The selected file is not a supported image.'); } return array('path' => $path, 'mime' => $checked['type'], 'name' => 'media.' . $checked['ext']); } function fiftyw_media_response($body, $status, $content_type) { if ($status === 401) { throw new RuntimeException('550W authentication failed. Reconnect the same account or check the configured credentials, then query the original operation before submitting again.', 401); } if ($status === 403) { throw new RuntimeException('Authorize the required permissions on the same 550W account, then query the original operation before submitting again.', 403); } if ($status !== 200 || !str_starts_with(strtolower((string) $content_type), 'application/json') || strlen($body) > 2097152) { throw new RuntimeException('Outcome not confirmed. Query existing tasks before repeating a charged action.'); } $value = json_decode($body, true, 32); if (!is_array($value) || !is_int($value['code'] ?? null)) { throw new RuntimeException('Outcome not confirmed. Query existing tasks before resubmitting.'); } return $value; } function fiftyw_media_send($url, $fields, $source = null, $bearer = null, $method = 'POST') { if ($source === null) { $headers = $bearer ? array('Authorization' => 'Bearer ' . $bearer) : array(); $headers['X-550W-Product'] = 'plugin-wordpress'; $headers['X-550W-Product-Version'] = FIFTYW_MEDIA_VERSION; if ($bearer && $method === 'POST') { $headers['Content-Type'] = 'application/json'; } $args = array('method' => $method, 'timeout' => 60, 'redirection' => 0, 'limit_response_size' => 2097152, 'headers' => $headers); if ($method === 'POST') { $args['body'] = $bearer ? wp_json_encode($fields) : $fields; } $response = wp_remote_request($url, $args); if (is_wp_error($response)) { throw new RuntimeException('Outcome not confirmed. Query the task before resubmitting.'); } return fiftyw_media_response(wp_remote_retrieve_body($response), wp_remote_retrieve_response_code($response), wp_remote_retrieve_header($response, 'content-type')); } // Native HTTP API requires an in-memory multipart body. Bound size before reading, // leaving room for transport copies and the running WordPress request. $limit = wp_convert_hr_to_bytes(ini_get('memory_limit')); $available = $limit > 0 ? max(0, $limit - memory_get_usage(true) - 33554432) : 268435456; $maximum = min(wp_max_upload_size(), 67108864, (int) floor($available / 4)); if (filesize($source['path']) > $maximum) { throw new InvalidArgumentException('File exceeds this host’s safe transfer limit. Use a smaller file or the web processing tool.'); } $boundary = '550w-' . bin2hex(random_bytes(24)); $body = ''; foreach ($fields as $key => $value) { if (!preg_match('/^[A-Za-z0-9_]+$/D', $key) || !is_scalar($value)) { throw new InvalidArgumentException('Invalid media parameters.'); } $body .= '--' . $boundary . "\r\nContent-Disposition: form-data; name=\"" . $key . "\"\r\n\r\n" . (string) $value . "\r\n"; } $bytes = file_get_contents($source['path']); if ($bytes === false) { throw new InvalidArgumentException('Cannot read the selected media.'); } $body .= '--' . $boundary . "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" . $source['name'] . "\"\r\nContent-Type: " . $source['mime'] . "\r\n\r\n" . $bytes . "\r\n--" . $boundary . "--\r\n"; unset($bytes); $headers = array('Content-Type' => 'multipart/form-data; boundary=' . $boundary, 'X-550W-Product' => 'plugin-wordpress', 'X-550W-Product-Version' => FIFTYW_MEDIA_VERSION); if ($bearer) { $headers['Authorization'] = 'Bearer ' . $bearer; } $response = wp_remote_post($url, array('timeout' => 180, 'redirection' => 0, 'limit_response_size' => 2097152, 'headers' => $headers, 'body' => $body, 'data_format' => 'body')); if (is_wp_error($response)) { throw new RuntimeException('Outcome not confirmed. Query the task before resubmitting.'); } return fiftyw_media_response(wp_remote_retrieve_body($response), wp_remote_retrieve_response_code($response), wp_remote_retrieve_header($response, 'content-type')); } function fiftyw_media_rectangle($value) { if ($value === '' || $value === null) { return null; } if (!is_string($value) || strlen($value) > 128) { throw new InvalidArgumentException('Invalid erase region.'); } $coords = json_decode($value, true); if (!is_array($coords) || array_keys($coords) !== array(0,1,2,3) || count(array_filter($coords, 'is_int')) !== 4 || min($coords) < 0 || $coords[0] >= $coords[2] || $coords[1] >= $coords[3]) { throw new InvalidArgumentException('Use [left,top,right,bottom] pixel coordinates, or leave the region empty.'); } return $coords; } function fiftyw_media_execute($input, $file) { $action = $input['action'] ?? ''; $mode = $input['authMode'] ?? 'api_key'; if (!in_array($mode, array('api_key', 'oauth'), true)) { throw new InvalidArgumentException('Select an account connection.'); } if (!in_array($action, array('image', 'video', 'share', 'image_query', 'video_query'), true)) { throw new InvalidArgumentException('Select a media tool.'); } $query = str_ends_with($action, '_query'); if (!$query && ($input['confirmCharge'] ?? '') !== 'yes') { throw new InvalidArgumentException('Confirm permission to process this media and approve credit usage.'); } $id = $query ? fiftyw_media_token($input['taskId'] ?? '') : fiftyw_media_token($input['operationId'] ?? '', 64); $source = in_array($action, array('image', 'video'), true) ? fiftyw_media_source($input, $file, $action) : null; $coords = $action === 'video' ? fiftyw_media_rectangle($input['rectangle'] ?? '') : null; $share = null; if ($action === 'share') { $text = $input['shareText'] ?? ''; if (!is_string($text) || strlen($text) > 4096) { throw new InvalidArgumentException('Paste one platform share link.'); } preg_match_all('~https?://[^\s]+~i', $text, $matches); if (count($matches[0]) !== 1) { throw new InvalidArgumentException('Paste exactly one platform share link.'); } $share = fiftyw_media_url(rtrim($matches[0][0], ');!')); } if ($mode === 'oauth') { $bearer = Fiftyw_Media_OAuth::access_token(); $base = 'https://www.550wai.cn/media-api/' . FIFTYW_MEDIA_REGION . '/v1'; if ($query) { return fiftyw_media_send($base . '/tasks/' . ($action === 'image_query' ? 'image' : 'video') . '/' . rawurlencode($id), array(), null, $bearer, 'GET'); } $fields = array('mediaType' => $action, 'operationId' => $id); if ($share) { $fields['sourceUrl'] = $share; } if ($coords) { $fields['area'] = implode(',', $coords); } return fiftyw_media_send($base . '/media', $fields, $source, $bearer); } $credentials = array(); foreach (array('apiKey', 'userNo') as $key) { $value = $input[$key] ?? ''; if (!is_string($value) || !trim($value) || strlen($value) > 128 || preg_match('/[\r\n]/', $value)) { throw new InvalidArgumentException('Enter your User No and API Key.'); } $credentials[$key] = trim($value); } $base = 'https://www.550wai.cn/open/'; if ($query) { return fiftyw_media_send($base . ($action === 'image_query' ? 'imageWatermarkTaskDetail' : 'taskDetail'), array_merge($credentials, array('taskId' => $id))); } if ($action === 'image') { return fiftyw_media_send($base . 'removeImageWatermark', array_merge($credentials, array('operationId' => $id, 'sync' => 'false')), $source); } if ($action === 'share') { return fiftyw_media_send($base . 'removeVideoWatermark', array_merge($credentials, array('operationId' => $id, 'videoUrl' => $share))); } $uploaded = fiftyw_media_send($base . 'uploadVideo', $credentials, $source); if ($uploaded['code'] !== 200) { return $uploaded; } $width = $uploaded['width'] ?? 0; $height = $uploaded['height'] ?? 0; $duration = $uploaded['duration'] ?? 0; if (!is_numeric($width) || !is_numeric($height) || min($width,$height) < 1 || max($width,$height) > 1920 || min($width,$height) > 1080 || !is_numeric($duration) || $duration < 1 || $duration > 600) { throw new InvalidArgumentException('This video exceeds the supported duration or resolution. No processing task was submitted.'); } $fields = array_merge($credentials, array('videoUrl' => fiftyw_media_url($uploaded['videoUrl'] ?? ''), 'width' => $width, 'height' => $height, 'duration' => $duration, 'idempotencyKey' => $id)); if ($coords) { if ($coords[2] > $width || $coords[3] > $height) { throw new InvalidArgumentException('Erase region exceeds the video dimensions.'); } $fields = array_merge($fields, array_combine(array('x1','y1','x2','y2'), $coords)); } return fiftyw_media_send($base . 'submitTask', $fields); }