PluginProbe
Auto Alt Text / 1.3.1
Auto Alt Text v1.3.1
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 / Setup.php

Setup.php in Auto Alt Text 1.3.1, at src/App/Setup.php

235 lines 8.6 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;
4
5 use AATXT\App\Logging\DBLogger;
6 use AATXT\App\Admin\PluginOptions;
7 use AATXT\App\AIProviders\Azure\AzureComputerVisionCaptionsResponse;
8 use AATXT\App\AIProviders\OpenAI\OpenAIChatCompletionResponse;
9 use AATXT\App\AIProviders\OpenAI\OpenAIVision;
10 use AATXT\App\Exceptions\Azure\AzureException;
11 use AATXT\App\Exceptions\OpenAI\OpenAIException;
12 use AATXT\Config\Constants;
13 use WpOrg\Requests\Exception;
14
15
16 class Setup
17 {
18 private static ?self $instance = null;
19
20 private function __construct()
21 {
22 //
23 }
24
25 /**
26 * Register plugin functionalities
27 * @return void
28 */
29 public static function register(): void
30 {
31 if (is_null(self::$instance)) {
32 self::$instance = new self();
33 }
34
35 //Register plugin options pages
36 PluginOptions::register();
37
38 register_activation_hook(AATXT_FILE_ABSPATH, [self::$instance, 'activatePlugin']);
39 register_deactivation_hook(AATXT_FILE_ABSPATH, [self::$instance, 'deactivatePlugin']);
40
41 // When attachment is uploaded, create alt text
42 add_action('add_attachment', [self::$instance, 'addAltText']);
43 // When plugin is loaded, load text domain
44 add_action('plugins_loaded', [self::$instance, 'loadTextDomain']);
45 // Add settings link to the plugin in the plugins listing
46 add_filter('plugin_action_links_auto-alt-text/auto-alt-text.php', [self::$instance, 'settingsLink']);
47 // Register bulk action for media library
48 add_filter('bulk_actions-upload', [self::$instance, 'registerBulkAction']);
49 // Handle alt text generation bulk action for media library
50 add_action('load-upload.php', [self::$instance, 'handleAltTextBulkAction']);
51 // Display a notice after alt text generation bulk action
52 add_action('admin_notices', [self::$instance, 'altTextBulkActionAdminNotice']);
53 }
54
55 /**
56 * Register bulk action for media library
57 */
58 public static function registerBulkAction(array $actions): array
59 {
60 $actions['auto_alt_text'] = esc_attr__('Generate Alt Text', 'auto-alt-text');
61 return $actions;
62 }
63
64 /**
65 * Handle alt text generation bulk action for media library
66 */
67 public static function handleAltTextBulkAction()
68 {
69 $mediaUpdated = 0;
70 $wpListTable = _get_list_table('WP_Media_List_Table');
71 $action = $wpListTable->current_action();
72
73 if ($action === 'auto_alt_text') {
74 // Recupera l'elenco degli ID dei media selezionati
75 $mediaIds = isset($_REQUEST['media']) ? $_REQUEST['media'] : array();
76
77 // Imposta l'alt text per ogni media selezionato
78 foreach ($mediaIds as $mediaId) {
79 $altText = self::altText($mediaId);
80 if (!empty($altText)) {
81 update_post_meta($mediaId, '_wp_attachment_image_alt', $altText);
82 $mediaUpdated++;
83 }
84 }
85
86 $callBackData = [
87 'mediaSelected' => count($mediaIds),
88 'mediaUpdated' => $mediaUpdated,
89 'auto_alt_text' => '1',
90 ];
91
92 // Redirect alla pagina della media library con un messaggio di successo
93 $sendback = add_query_arg(
94 $callBackData,
95 admin_url('upload.php')
96 );
97 wp_redirect($sendback);
98 exit();
99 }
100 }
101
102 /**
103 * Display a notice after alt text generation bulk action
104 */
105 public static function altTextBulkActionAdminNotice()
106 {
107 if (isset($_REQUEST['auto_alt_text'])) {
108 $mediaSelected = intval($_REQUEST['mediaSelected']);
109 $mediaUpdated = intval($_REQUEST['mediaUpdated']);
110
111 $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>.';
112
113 if ($mediaUpdated === 0) {
114 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);
115 } elseif ($mediaSelected === $mediaUpdated) {
116 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);
117 } else {
118 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);
119 }
120 }
121 }
122
123 /**
124 * Create a Logs table on plugin activation
125 */
126 public static function activatePlugin(): void
127 {
128 DBLogger::make()->createLogTable();
129 }
130
131 /**
132 * Drop Logs table on plugin deactivation
133 */
134 public static function deactivatePlugin(): void
135 {
136 DBLogger::make()->dropLogTable();
137 }
138
139 /**
140 * Add link to the options page of the plugin in the plugins listing
141 */
142 public static function settingsLink(array $links): array
143 {
144 $url = esc_url(add_query_arg(
145 'page',
146 'auto-alt-text-options',
147 get_admin_url() . 'admin.php'
148 ));
149 $settingsLink = "<a href='$url'>" . esc_html__('Settings', 'auto-alt-text') . '</a>';
150 $links[] = $settingsLink;
151
152 return $links;
153 }
154
155 /**
156 * Load text domain
157 * @return void
158 */
159 public static function loadTextDomain(): void
160 {
161 load_plugin_textdomain('auto-alt-text', false, AATXT_LANGUAGES_RELATIVE_PATH);
162 }
163
164 /**
165 * @param int $postId
166 * @return string
167 */
168 public static function altText(int $postId): string
169 {
170 if (!wp_attachment_is_image($postId)) {
171 return '';
172 }
173
174 $altText = '';
175 switch (PluginOptions::typology()) {
176 case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_AZURE:
177 // If Azure is selected as alt text generating typology
178 try {
179 $altText = (AltTextGeneratorAi::make(AzureComputerVisionCaptionsResponse::make()))->altText($postId);
180 } catch (AzureException $e) {
181 (DBLogger::make())->writeImageLog($postId, "Azure - " . $e->getMessage());
182 }
183 break;
184 case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_OPENAI:
185 // If OpenAI is selected as alt text generating typology
186 try {
187 $altText = (AltTextGeneratorAi::make(OpenAIVision::make()))->altText($postId);
188 } catch (OpenAIException $e) {
189 //If vision model fails, try with a fallback model
190 $errorMessage = "OpenAI - " . Constants::AATXT_OPENAI_VISION_MODEL . ' - ' . $e->getMessage();
191 (DBLogger::make())->writeImageLog($postId, $errorMessage);
192 try {
193 $altText = (AltTextGeneratorAi::make(OpenAIChatCompletionResponse::make()))->altText($postId);
194 } catch (OpenAIException $e) {
195 $errorMessage = "OpenAI - " . $e->getMessage();
196 (DBLogger::make())->writeImageLog($postId, $errorMessage);
197 }
198 }
199 break;
200 case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_ARTICLE_TITLE:
201 // If Article title is selected as alt text generating typology
202 $parentId = wp_get_post_parent_id($postId);
203 if ($parentId) {
204 $altText = (AltTextGeneratorParentPostTitle::make())->altText($postId);
205 } else {
206 //If media has not a parent use the Attachment Title method as fallback
207 $altText = (AltTextGeneratorAttachmentTitle::make())->altText($postId);
208 }
209 break;
210 case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_ATTACHMENT_TITLE:
211 // If Attachment title is selected as alt text generating typology
212 $altText = (AltTextGeneratorAttachmentTitle::make())->altText($postId);
213 break;
214 default:
215 return '';
216 }
217
218 return $altText;
219 }
220
221 /**
222 * @param int $postId
223 * @return void
224 */
225 public static function addAltText(int $postId): void
226 {
227 $altText = self::altText($postId);
228 if (empty($altText)) {
229 return;
230 }
231
232 update_post_meta($postId, '_wp_attachment_image_alt', $altText);
233 }
234 }
235