PluginProbe
Auto Alt Text / trunk
Auto Alt Text vtrunk
3.0.3 2.8.2 1.3.1 1.3.2 2.0.0 2.1.0 2.1.1 2.2.0 2.3.0 2.3.1 2.3.2 2.3.3 2.3.4 2.4.0 2.4.1 2.4.2 2.5.0 2.5.1 2.5.2 2.5.3 2.6.0 2.6.1 2.7.0 2.8.0 2.8.1 All 28 releases
auto-alt-text / src / App / Admin / MediaLibrary.php

MediaLibrary.php in Auto Alt Text trunk, at src/App/Admin/MediaLibrary.php

200 lines 6.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace AATXT\App\Admin;
4
5 use AATXT\App\Services\AltTextService;
6 use AATXT\App\Utilities\AssetsManager;
7 use AATXT\Config\Constants;
8
9 class MediaLibrary
10 {
11 /**
12 * Alt text generation service
13 *
14 * @var AltTextService
15 */
16 private $altTextService;
17
18 /**
19 * Assets manager for handling Vite manifests
20 *
21 * @var AssetsManager
22 */
23 private $assetsManager;
24
25 /**
26 * Constructor
27 *
28 * @param AltTextService $altTextService Service for generating alt text
29 * @param AssetsManager $assetsManager Manager for asset URLs
30 */
31 public function __construct(AltTextService $altTextService, AssetsManager $assetsManager)
32 {
33 $this->altTextService = $altTextService;
34 $this->assetsManager = $assetsManager;
35 }
36
37 public function register(): void
38 {
39 add_action('admin_enqueue_scripts', [$this, 'enqueue'], 1);
40
41 // Render custom template in media modal
42 add_action('print_media_templates', [$this, 'renderGenerateButtonTemplate']);
43
44 // Add button to generate alt text in media library
45 add_filter('attachment_fields_to_edit', [$this, 'addGenerateAltTextButton'], 10, 2);
46
47 // Register REST route to generate alt text
48 add_action('rest_api_init', [$this, 'registerRestRoutes']);
49 }
50
51 public function enqueue(): void
52 {
53 $screen = get_current_screen();
54
55 // Load script in Media Library and in any post editing/modal (all CPTs)
56 if (! $screen || in_array($screen->base, ['upload', 'post'], true)) {
57 $mediaLibraryJs = $this->assetsManager->getAssetUrl('resources/js/media-library.js', false);
58 wp_enqueue_script(
59 Constants::AATXT_PLUGIN_MEDIA_LIBRARY_HANDLE,
60 $mediaLibraryJs,
61 ['jquery'],
62 false,
63 true
64 );
65
66 wp_localize_script(
67 Constants::AATXT_PLUGIN_MEDIA_LIBRARY_HANDLE,
68 'AATXT',
69 [
70 'restNonce' => wp_create_nonce('wp_rest'),
71 'restUrl' => esc_url_raw(
72 rest_url(Constants::AATXT_REST_NAMESPACE . Constants::AATXT_REST_ROUTE_GENERATE_ALT_TEXT)
73 ),
74 ]
75 );
76 }
77 }
78
79 public function renderGenerateButtonTemplate(): void
80 {
81 ?>
82 <script type="text/html" id="tmpl-aatxt-generate-alt-text">
83 <# if ( data.type === 'image' ) { #>
84 <button class="button aatxt-generate-alt-text" data-post-id="{{ data.id }}">
85 <?php esc_html_e('Generate Alt Text', 'auto-alt-text'); ?>
86 </button>
87 <span class="spinner"></span>
88 <# } #>
89 </script>
90
91 <?php
92 }
93
94 public function addGenerateAltTextButton(array $form_fields, \WP_Post $post): array
95 {
96 if (! wp_attachment_is_image($post->ID)) {
97 return $form_fields;
98 }
99
100 $mimeType = get_post_mime_type($post->ID);
101 $altTextGenerationTypology = PluginOptions::typology();
102
103 if ($altTextGenerationTypology === Constants::AATXT_OPTION_TYPOLOGY_CHOICE_OPENAI
104 && ! in_array($mimeType, Constants::AATXT_OPENAI_ALLOWED_MIME_TYPES, true)
105 ) {
106 return $form_fields;
107 }
108
109 if ($altTextGenerationTypology === Constants::AATXT_OPTION_TYPOLOGY_CHOICE_AZURE
110 && ! in_array($mimeType, Constants::AATXT_AZURE_ALLOWED_MIME_TYPES, true)
111 ) {
112 return $form_fields;
113 }
114
115 $form_fields['generate_alt_text'] = [
116 'label' => get_post_mime_type($post->ID),
117 'input' => 'html',
118 'html' => '<button type="button" class="button" id="generate-alt-text-button" data-post-id="' . $post->ID . '">'
119 . esc_html__('Generate Alt Text', 'auto-alt-text') .
120 '</button><span id="loading-spinner" class="spinner" style="float:none; margin-left:5px; display:none;"></span>',
121 'helps' => '',
122 ];
123
124 return $form_fields;
125 }
126
127 /**
128 * Register the REST API routes handled by this class.
129 *
130 * @return void
131 */
132 public function registerRestRoutes(): void
133 {
134 register_rest_route(
135 Constants::AATXT_REST_NAMESPACE,
136 Constants::AATXT_REST_ROUTE_GENERATE_ALT_TEXT,
137 [
138 'methods' => 'POST',
139 'callback' => [$this, 'generateAltText'],
140 'permission_callback' => [$this, 'canGenerateAltText'],
141 'args' => [
142 'post_id' => [
143 'required' => true,
144 'type' => 'integer',
145 'sanitize_callback' => 'absint',
146 'validate_callback' => static function ($value): bool {
147 return absint($value) > 0;
148 },
149 ],
150 ],
151 ]
152 );
153 }
154
155 /**
156 * Permission check for the alt text generation endpoint.
157 *
158 * @param \WP_REST_Request<array<string, mixed>> $request The REST request.
159 * @return bool True if the current user may generate alt text.
160 */
161 public function canGenerateAltText(\WP_REST_Request $request): bool
162 {
163 $postId = absint($request->get_param('post_id'));
164
165 return $postId > 0 && current_user_can('edit_post', $postId);
166 }
167
168 /**
169 * Generate alt text for an attachment.
170 *
171 * @param \WP_REST_Request<array<string, mixed>> $request The REST request.
172 * @return \WP_REST_Response|\WP_Error The generated alt text or an error.
173 */
174 public function generateAltText(\WP_REST_Request $request)
175 {
176 $postId = absint($request->get_param('post_id'));
177
178 if (! wp_attachment_is_image($postId)) {
179 return new \WP_Error(
180 'aatxt_invalid_attachment',
181 __('The provided ID is not an image attachment.', 'auto-alt-text'),
182 ['status' => 404]
183 );
184 }
185
186 $mediaUrl = wp_get_attachment_url($postId);
187 if (! $mediaUrl) {
188 return new \WP_Error(
189 'aatxt_media_not_found',
190 __('Media not found.', 'auto-alt-text'),
191 ['status' => 404]
192 );
193 }
194
195 $generatedAltText = $this->altTextService->generateForAttachment($postId);
196
197 return new \WP_REST_Response(['alt_text' => $generatedAltText], 200);
198 }
199 }
200