| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Image Controller |
| 5 |
*/ |
| 6 |
|
| 7 |
namespace Extendify\Draft\Controllers; |
| 8 |
|
| 9 |
defined('ABSPATH') || die('No direct access.'); |
| 10 |
|
| 11 |
// Try to execute set the limit to something that will work for 60s duration. |
| 12 |
// phpcs:ignore WordPress.PHP.NoSilencedErrors, Generic.PHP.NoSilencedErrors.Discouraged |
| 13 |
if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
| 14 |
// phpcs:ignore WordPress.PHP.NoSilencedErrors, Generic.PHP.NoSilencedErrors.Discouraged |
| 15 |
@set_time_limit(60); |
| 16 |
} |
| 17 |
|
| 18 |
use Extendify\Shared\Services\Sanitizer; |
| 19 |
|
| 20 |
/** |
| 21 |
* The controller for uploading images to the Media Library. |
| 22 |
*/ |
| 23 |
|
| 24 |
class ImageController |
| 25 |
{ |
| 26 |
/** |
| 27 |
* Upload the provided image |
| 28 |
* |
| 29 |
* @param \WP_REST_Request $request - The request. |
| 30 |
* @return \WP_REST_Response |
| 31 |
*/ |
| 32 |
public static function uploadMedia(\WP_REST_Request $request) |
| 33 |
{ |
| 34 |
if (! function_exists('\media_sideload_image')) { |
| 35 |
require_once ABSPATH . 'wp-admin/includes/media.php'; |
| 36 |
require_once ABSPATH . 'wp-admin/includes/file.php'; |
| 37 |
require_once ABSPATH . 'wp-admin/includes/image.php'; |
| 38 |
} |
| 39 |
|
| 40 |
$imageId = \media_sideload_image($request->get_param('source'), 0, null, 'id'); |
| 41 |
|
| 42 |
if ($request->get_param('alt_text')) { |
| 43 |
update_post_meta( |
| 44 |
$imageId, |
| 45 |
'_wp_attachment_image_alt', |
| 46 |
Sanitizer::sanitizeText($request->get_param('alt_text')) |
| 47 |
); |
| 48 |
} |
| 49 |
|
| 50 |
if ($request->get_param('caption')) { |
| 51 |
wp_update_post( |
| 52 |
Sanitizer::sanitizeArray([ |
| 53 |
'ID' => $imageId, |
| 54 |
'post_excerpt' => $request->get_param('caption'), |
| 55 |
]) |
| 56 |
); |
| 57 |
} |
| 58 |
|
| 59 |
$imageObject = \get_post($imageId); |
| 60 |
$altText = (get_post_meta($imageId, '_wp_attachment_image_alt', true)) |
| 61 |
? get_post_meta($imageId, '_wp_attachment_image_alt', true) |
| 62 |
: ''; |
| 63 |
|
| 64 |
return new \WP_REST_Response( |
| 65 |
[ |
| 66 |
'id' => $imageId, |
| 67 |
'caption' => ['raw' => $imageObject->post_excerpt], |
| 68 |
'source_url' => wp_get_attachment_url($imageId), |
| 69 |
'alt_text' => $altText, |
| 70 |
] |
| 71 |
); |
| 72 |
} |
| 73 |
} |
| 74 |
|