PluginProbe
Auto Alt Text / 2.1.1
Auto Alt Text v2.1.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 2.1.1, at src/App/Setup.php

238 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\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;
15
16
17 class Setup
18 {
19 private static ?self $instance = null;
20
21 private function __construct()
22 {
23 //
24 }
25
26 /**
27 * Register plugin functionalities
28 * @return void
29 */
30 public static function register(): void
31 {
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']);
56 }
57
58 /**
59 * Register bulk action for media library
60 */
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 int $postId
169 * @return string
170 */
171 public static function altText(int $postId): string
172 {
173 if (!wp_attachment_is_image($postId)) {
174 return '';
175 }
176
177 $altText = '';
178 switch (PluginOptions::typology()) {
179 case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_AZURE:
180 // If Azure is selected as alt text generating typology
181 try {
182 $altText = (AltTextGeneratorAi::make(AzureComputerVisionCaptionsResponse::make()))->altText($postId);
183 } catch (AzureException $e) {
184 (DBLogger::make())->writeImageLog($postId, "Azure - " . $e->getMessage());
185 }
186 break;
187 case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_OPENAI:
188 // If OpenAI is selected as alt text generating typology
189 try {
190 $altText = (AltTextGeneratorAi::make(OpenAIVision::make()))->altText($postId);
191 } catch (OpenAIException $e) {
192 //If vision model fails, try with a fallback model
193 $errorMessage = "OpenAI - " . Constants::AATXT_OPENAI_VISION_MODEL . ' - ' . $e->getMessage();
194 (DBLogger::make())->writeImageLog($postId, $errorMessage);
195 try {
196 $altText = (AltTextGeneratorAi::make(Fallback::make()))->altText($postId);
197 } catch (OpenAIException $e) {
198 $errorMessage = "OpenAI - " . $e->getMessage();
199 (DBLogger::make())->writeImageLog($postId, $errorMessage);
200 }
201 }
202 break;
203 case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_ARTICLE_TITLE:
204 // If Article title is selected as alt text generating typology
205 $parentId = wp_get_post_parent_id($postId);
206 if ($parentId) {
207 $altText = (AltTextGeneratorParentPostTitle::make())->altText($postId);
208 } else {
209 //If media has not a parent use the Attachment Title method as fallback
210 $altText = (AltTextGeneratorAttachmentTitle::make())->altText($postId);
211 }
212 break;
213 case Constants::AATXT_OPTION_TYPOLOGY_CHOICE_ATTACHMENT_TITLE:
214 // If Attachment title is selected as alt text generating typology
215 $altText = (AltTextGeneratorAttachmentTitle::make())->altText($postId);
216 break;
217 default:
218 return '';
219 }
220
221 return $altText;
222 }
223
224 /**
225 * @param int $postId
226 * @return void
227 */
228 public static function addAltText(int $postId): void
229 {
230 $altText = self::altText($postId);
231 if (empty($altText)) {
232 return;
233 }
234
235 update_post_meta($postId, '_wp_attachment_image_alt', $altText);
236 }
237 }
238