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
← All changes | src/App/Setup.php +27 -240 2.3.4trunk View file →
@@ -1,262 +1,49 @@
1 1 <?php
2 2
3 3 namespace AATXT\App;
4 4
5 -use AATXT\App\Admin\MediaLibrary;
6 -use AATXT\App\Logging\DBLogger;
7 -use AATXT\App\Admin\PluginOptions;
8 -use AATXT\App\AIProviders\Azure\AzureComputerVisionCaptionsResponse;
9 -use AATXT\App\AIProviders\OpenAI\Fallback;
10 -use AATXT\App\AIProviders\OpenAI\OpenAIVision;
11 -use AATXT\App\Exceptions\Azure\AzureException;
12 -use AATXT\App\Exceptions\OpenAI\OpenAIException;
13 -use AATXT\Config\Constants;
14 -use WpOrg\Requests\Exception;
5 +use AATXT\App\Core\Container;
6 +use AATXT\App\Core\PluginBootstrap;
7 +use AATXT\App\Services\AltTextService;
15 8
16 -
9 +/**
10 + * Legacy Setup class maintained for backward compatibility.
11 + *
12 + * @deprecated 2.6.0 Use PluginBootstrap::init() and dependency injection for new code.
13 + * All methods in this class are deprecated and will be removed in v3.0.0.
14 + * Use AltTextService via dependency injection instead of Setup::altText().
15 + */
17 16 class Setup
18 17 {
19 - private static ?self $instance = null;
20 -
21 - private function __construct()
22 - {
23 - //
24 - }
25 -
26 18 /**
27 - * Register plugin functionalities
19 + * Register plugin functionalities.
20 + *
21 + * @deprecated 2.6.0 Use PluginBootstrap::init() instead.
28 22 * @return void
29 23 */
30 24 public static function register(): void
31 25 {
32 - if (is_null(self::$instance)) {
33 - self::$instance = new self();
34 - }
35 -
36 - //Register plugin options pages
37 - PluginOptions::register();
38 - //Register medial library hooks
39 - MediaLibrary::register();
40 -
41 - register_activation_hook(AATXT_FILE_ABSPATH, [self::$instance, 'activatePlugin']);
42 - register_deactivation_hook(AATXT_FILE_ABSPATH, [self::$instance, 'deactivatePlugin']);
43 -
44 - // When attachment is uploaded, create alt text
45 - add_action('add_attachment', [self::$instance, 'addAltText']);
46 - // When plugin is loaded, load text domain
47 - add_action('plugins_loaded', [self::$instance, 'loadTextDomain']);
48 - // Add settings link to the plugin in the plugins listing
49 - add_filter('plugin_action_links_auto-alt-text/auto-alt-text.php', [self::$instance, 'settingsLink']);
50 - // Register bulk action for media library
51 - add_filter('bulk_actions-upload', [self::$instance, 'registerBulkAction']);
52 - // Handle alt text generation bulk action for media library
53 - add_action('load-upload.php', [self::$instance, 'handleAltTextBulkAction']);
54 - // Display a notice after alt text generation bulk action
55 - add_action('admin_notices', [self::$instance, 'altTextBulkActionAdminNotice']);
26 + _deprecated_function(__METHOD__, '2.6.0', 'PluginBootstrap::init()');
27 + PluginBootstrap::init(AATXT_FILE_ABSPATH);
56 28 }
57 29
58 30 /**
59 - * Register bulk action for media library
31 + * Generate alt text for an attachment.
32 + *
33 + * This method is kept for backward compatibility with external code
34 + * that may call Setup::altText() directly.
35 + *
36 + * @deprecated 2.6.0 Use AltTextService::generateForAttachment() via dependency injection instead.
37 + * @param int $postId The attachment post ID
38 + * @return string Generated alt text, or empty string if generation fails
60 39 */
61 - public static function registerBulkAction(array $actions): array
62 - {
63 - $actions['auto_alt_text'] = esc_attr__('Generate Alt Text', 'auto-alt-text');
64 - return $actions;
65 - }
66 -
67 - /**
68 - * Handle alt text generation bulk action for media library
69 - */
70 - public static function handleAltTextBulkAction()
71 - {
72 - $mediaUpdated = 0;
73 - $wpListTable = _get_list_table('WP_Media_List_Table');
74 - $action = $wpListTable->current_action();
75 -
76 - if ($action === 'auto_alt_text') {
77 - // Recupera l'elenco degli ID dei media selezionati
78 - $mediaIds = isset($_REQUEST['media']) ? $_REQUEST['media'] : array();
79 -
80 - // Imposta l'alt text per ogni media selezionato
81 - foreach ($mediaIds as $mediaId) {
82 - $altText = self::altText($mediaId);
83 - if (!empty($altText)) {
84 - update_post_meta($mediaId, '_wp_attachment_image_alt', $altText);
85 - $mediaUpdated++;
86 - }
87 - }
88 -
89 - $callBackData = [
90 - 'mediaSelected' => count($mediaIds),
91 - 'mediaUpdated' => $mediaUpdated,
92 - 'auto_alt_text' => '1',
93 - ];
94 -
95 - // Redirect alla pagina della media library con un messaggio di successo
96 - $sendback = add_query_arg(
97 - $callBackData,
98 - admin_url('upload.php')
99 - );
100 - wp_redirect($sendback);
101 - exit();
102 - }
103 - }
104 -
105 - /**
106 - * Display a notice after alt text generation bulk action
107 - */
108 - public static function altTextBulkActionAdminNotice()
109 - {
110 - if (isset($_REQUEST['auto_alt_text'])) {
111 - $mediaSelected = intval($_REQUEST['mediaSelected']);
112 - $mediaUpdated = intval($_REQUEST['mediaUpdated']);
113 -
114 - $errorLogDisclaimer = __('Take a look at the', 'auto-alt-text') . ' <a href="' . esc_url(menu_page_url(Constants::AATXT_PLUGIN_OPTION_LOG_PAGE_SLUG, false)) . '">' . __('error log', 'auto-alt-text') . '</a>.';
115 -
116 - if ($mediaUpdated === 0) {
117 - printf('<div id="message" class="notice notice-error is-dismissible"><p>' . esc_attr__('No Alt Text has been set.', 'auto-alt-text') . ' %s</p></div>', $errorLogDisclaimer);
118 - } elseif ($mediaSelected === $mediaUpdated) {
119 - printf('<div id="message" class="updated notice is-dismissible"><p>' . esc_attr__('The Alt Text has been set for %s media.', 'auto-alt-text') . '</p></div>', $mediaUpdated);
120 - } else {
121 - printf('<div id="message" class="notice notice-warning is-dismissible"><p>' . esc_attr__('The Alt Text has been set for %s of %s media.', 'auto-alt-text') . ' %s</p></div>', $mediaUpdated, $mediaSelected, $errorLogDisclaimer);
122 - }
123 - }
124 - }
125 -
126 - /**
127 - * Create a Logs table on plugin activation
128 - */
129 - public static function activatePlugin(): void
130 - {
131 - DBLogger::make()->createLogTable();
132 - }
133 -
134 - /**
135 - * Drop Logs table on plugin deactivation
136 - */
137 - public static function deactivatePlugin(): void
138 - {
139 - DBLogger::make()->dropLogTable();
140 - }
141 -
142 - /**
143 - * Add link to the options page of the plugin in the plugins listing
144 - */
145 - public static function settingsLink(array $links): array
146 - {
147 - $url = esc_url(add_query_arg(
148 - 'page',
149 - 'auto-alt-text-options',
150 - get_admin_url() . 'admin.php'
151 - ));
152 - $settingsLink = "<a href='$url'>" . esc_html__('Settings', 'auto-alt-text') . '</a>';
153 - $links[] = $settingsLink;
154 -
155 - return $links;
156 - }
157 -
158 - /**
159 - * Load text domain
160 - * @return void
161 - */
162 - public static function loadTextDomain(): void
163 - {
164 - load_plugin_textdomain('auto-alt-text', false, AATXT_LANGUAGES_RELATIVE_PATH);
165 - }
166 -
167 - /**
168 - * @param array<string> $allowedMimeTypes
169 - */
170 - private static function allowedMimeTypesList(array $allowedMimeTypes): string
171 - {
172 - return str_replace('image/', '' , implode(', ', $allowedMimeTypes));
173 - }
174 -
175 - /**
176 - * @param int $postId
177 - * @return string
178 - */
179 40 public static function altText(int $postId): string
180 41 {
181 - if (!wp_attachment_is_image($postId)) {
182 - return '';
183 - }
42 + _deprecated_function(__METHOD__, '2.6.0', 'AltTextService::generateForAttachment()');
184 43
185 - if (PluginOptions::preserveExistingAltText()) {
186 - $altText = get_post_meta($postId, '_wp_attachment_image_alt', TRUE);
44 + $container = Container::make();
45 + $altTextService = $container->get(AltTextService::class);
187 46
188 - if (!empty($altText)) {
189 - return $altText;
190 - }
191 - }
192 -
193 - $mimeType = get_post_mime_type($postId);
194 -
195 - switch (PluginOptions::typology()) {
196 - case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_AZURE:
197 - if (!in_array($mimeType, Constants::AATXT_AZURE_ALLOWED_MIME_TYPES, true)) {
198 - $formats = self::allowedMimeTypesList(Constants::AATXT_AZURE_ALLOWED_MIME_TYPES);
199 - (DBLogger::make())->writeImageLog($postId, "You uploaded an unsupported image. Please make sure your image has of one the following formats: $formats");
200 - return '';
201 - }
202 - try {
203 - $altText = (AltTextGeneratorAi::make(AzureComputerVisionCaptionsResponse::make()))->altText($postId);
204 - } catch (AzureException $e) {
205 - (DBLogger::make())->writeImageLog($postId, "Azure - " . $e->getMessage());
206 - }
207 - break;
208 - case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_OPENAI:
209 - if (!in_array($mimeType, Constants::AATXT_OPENAI_ALLOWED_MIME_TYPES, true)) {
210 - $formats = self::allowedMimeTypesList(Constants::AATXT_OPENAI_ALLOWED_MIME_TYPES);
211 - (DBLogger::make())->writeImageLog($postId, "You uploaded an unsupported image. Please make sure your image has of one the following formats: $formats");
212 - return '';
213 - }
214 - try {
215 - $altText = (AltTextGeneratorAi::make(OpenAIVision::make()))->altText($postId);
216 - } catch (OpenAIException $e) {
217 - //If vision model fails, try with a fallback model
218 - $errorMessage = "OpenAI - " . Constants::AATXT_OPENAI_VISION_MODEL . ' - ' . $e->getMessage();
219 - (DBLogger::make())->writeImageLog($postId, $errorMessage);
220 - try {
221 - $altText = (AltTextGeneratorAi::make(Fallback::make()))->altText($postId);
222 - } catch (OpenAIException $e) {
223 - $errorMessage = "OpenAI - " . $e->getMessage();
224 - (DBLogger::make())->writeImageLog($postId, $errorMessage);
225 - }
226 - }
227 - break;
228 - case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_ARTICLE_TITLE:
229 - // If Article title is selected as alt text generating typology
230 - $parentId = wp_get_post_parent_id($postId);
231 - if ($parentId) {
232 - $altText = (AltTextGeneratorParentPostTitle::make())->altText($postId);
233 - } else {
234 - //If media has not a parent use the Attachment Title method as fallback
235 - $altText = (AltTextGeneratorAttachmentTitle::make())->altText($postId);
236 - }
237 - break;
238 - case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_ATTACHMENT_TITLE:
239 - // If Attachment title is selected as alt text generating typology
240 - $altText = (AltTextGeneratorAttachmentTitle::make())->altText($postId);
241 - break;
242 - default:
243 - return '';
244 - }
245 -
246 - return $altText ?? '';
247 - }
248 -
249 - /**
250 - * @param int $postId
251 - * @return void
252 - */
253 - public static function addAltText(int $postId): void
254 - {
255 - $altText = self::altText($postId);
256 - if (empty($altText)) {
257 - return;
258 - }
259 -
260 - update_post_meta($postId, '_wp_attachment_image_alt', $altText);
47 + return $altTextService->generateForAttachment($postId);
261 48 }
262 49 }