PluginProbe
Image Hub – Free Images from Unsplash, Pixabay, Pexels, Openverse & Giphy / trunk
Image Hub – Free Images from Unsplash, Pixabay, Pexels, Openverse & Giphy vtrunk
1.2.0 trunk 1.0.11 1.0.8 1.0.9 1.1.0
image-hub / inc / src / Utils.php

Utils.php in Image Hub – Free Images from Unsplash, Pixabay, Pexels, Openverse & Giphy trunk, at inc/src/Utils.php

250 lines 7.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace ImageHub;
4
5
6
7 class Utils
8 {
9 static function localize_props($name)
10 {
11 wp_localize_script($name, 'image_hub_data', array(
12 'ajaxurl' => admin_url('admin-ajax.php'),
13 'nonce' => wp_create_nonce('image_hub_nonce'),
14 'adminUrl' => admin_url(),
15 'assetBaseUrl' => IMAGE_HUB_ROOT_URL . '/assets',
16 'imageUrl' => IMAGE_HUB_ROOT_URL . '/assets/images/logo-color.svg',
17 'openverseLogoUrl' => IMAGE_HUB_ROOT_URL . '/assets/images/openverse.png',
18 'giphyLogoUrl' => IMAGE_HUB_ROOT_URL . '/assets/images/giphy.png',
19 'giphyAttrUrl' => IMAGE_HUB_ROOT_URL . '/assets/images/giphy-attr.png',
20 'unsplashLogoUrl' => IMAGE_HUB_ROOT_URL . '/assets/images/unsplash.png',
21 'pixabayLogoUrl' => IMAGE_HUB_ROOT_URL . '/assets/images/pixabay.png',
22 'transparentBG' => IMAGE_HUB_ROOT_URL . '/assets/images/transparent-bg.jpg',
23 'pexelsLogoUrl' => IMAGE_HUB_ROOT_URL . '/assets/images/pexels.png',
24 'server_url' => Utils::get_service_url(),
25 'version' => Utils::get_version(),
26 ));
27 }
28
29 static function get_asset_prop($name, $prop)
30 {
31
32 $filepath = IMAGE_HUB_ROOT_DIR . 'build/' . $name . '.asset.php';
33 $filepath = str_replace('\\', '/', $filepath);
34 if (!file_exists($filepath)) {
35 return null;
36 }
37
38 $assets = include $filepath;
39 $assets['script'] = IMAGE_HUB_ROOT_URL . '//build/' . $name . '.js';
40
41 if (!is_array($assets) || !array_key_exists($prop, $assets)) {
42 return null;
43 }
44
45 return $assets[$prop];
46 }
47
48
49 static function enque_image_hub_script($name, $args = false)
50 {
51
52 $dependencies = Utils::get_asset_prop($name, 'dependencies');
53
54 // Check if the asset name is 'media-modal'
55 if ($name == 'media-modal') {
56 // Add 'media-views' to the dependencies array if it's not already there
57 if (!in_array('media-views', $dependencies)) {
58 $dependencies[] = 'media-views';
59 }
60 }
61
62 wp_enqueue_script(
63 'image-hub-' . $name,
64 Utils::get_asset_prop($name, 'script'),
65 $dependencies,
66 Utils::get_asset_prop($name, 'version'),
67 $args
68 );
69 }
70
71
72 /**
73 * Returns the service URL using development or production values.
74 */
75 static function get_service_url()
76 {
77 $svc_temp_url = defined("IMAGE_HUB_DEV_SERVICE_URL") ? IMAGE_HUB_DEV_SERVICE_URL : IMAGE_HUB_SERVICE_URL;
78 return $svc_temp_url;
79 }
80
81 /**
82 * Returns the version for the plugin.
83 */
84 static function get_version()
85 {
86 $temp_version = defined("IMAGE_HUB_DEV_VERSION") ? IMAGE_HUB_DEV_VERSION : IMAGE_HUB_VERSION;
87 return $temp_version == "@@buildnumber@@" ? time() : $temp_version;
88 }
89
90 /**
91 * Creates an attribution string.
92 */
93 static function create_attribution($provider, $link, $username)
94 {
95 if (empty($provider) || empty($link) || empty($username)) {
96 return '';
97 }
98
99 $providerFormatted = ucfirst(strtolower($provider));
100
101 return sprintf(
102 'Photo by <a href="%s?utm_source=image-hub&amp;utm_medium=referral" target="_blank" rel="noopener noreferrer">%s</a> on <a href="https://%s.com" target="_blank" rel="noopener noreferrer">%s</a>',
103 esc_url($link),
104 esc_html($username),
105 esc_attr($provider),
106 esc_html($providerFormatted)
107 );
108 }
109
110 /**
111 * Downloads an image, performs sanity checks, and sideloads it into the media library.
112 */
113 static function download_image($image_url, $description)
114 {
115 add_filter('http_headers_useragent', static function () {
116 return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.2 Safari/537.36';
117 });
118
119 $tmp = download_url($image_url);
120 if (is_wp_error($tmp)) {
121 return $tmp;
122 }
123
124 $path_info = pathinfo(wp_parse_url($image_url, PHP_URL_PATH));
125 $filename = isset($path_info['filename']) ? sanitize_file_name($path_info['filename']) : 'image';
126 $mime_type = mime_content_type($tmp);
127
128 $mime_extension_map = [
129 'image/jpeg' => 'jpg',
130 'image/png' => 'png',
131 'image/gif' => 'gif',
132 'image/webp' => 'webp',
133 'image/svg+xml' => 'svg',
134 ];
135
136 $extension = isset($path_info['extension']) ? strtolower($path_info['extension']) : '';
137 if (!$extension || !isset($mime_extension_map[$mime_type])) {
138 $extension = $mime_extension_map[$mime_type] ?? 'jpg';
139 }
140
141 if (empty($extension)) {
142 @wp_delete_file($tmp);
143 return new \WP_Error('invalid_file_type', "Could not determine file type.");
144 }
145
146 $desired_filename = "{$filename}.{$extension}";
147
148 $file = [
149 'name' => $desired_filename,
150 'type' => $mime_type,
151 'tmp_name' => $tmp,
152 'error' => 0,
153 'size' => filesize($tmp),
154 ];
155
156 $image_id = media_handle_sideload($file, 0, $description);
157 if (is_wp_error($image_id)) {
158 @wp_delete_file($tmp);
159 return $image_id;
160 }
161
162 return $image_id;
163 }
164
165 /**
166 * Renames a downloaded image file.
167 */
168 static function rename_image($file_path, $new_name, $image_id)
169 {
170 $file_info = pathinfo($file_path);
171 $new_filename = sanitize_file_name($new_name . '.' . $file_info['extension']);
172 $new_file_path = $file_info['dirname'] . '/' . $new_filename;
173
174 global $wp_filesystem;
175
176 if (! function_exists('WP_Filesystem')) {
177 require_once ABSPATH . 'wp-admin/includes/file.php';
178 }
179
180 WP_Filesystem();
181
182
183 if ($wp_filesystem->move($file_path, $new_file_path)) {
184 update_attached_file($image_id, $new_file_path);
185 wp_update_post([
186 'ID' => $image_id,
187 'post_title' => $new_filename,
188 'post_name' => sanitize_title($new_filename),
189 ]);
190 }
191
192 return $new_file_path;
193 }
194
195 /**
196 * Resizes an image if maximum dimensions are set.
197 */
198 static function resize_image($file_path)
199 {
200
201 if (
202 !isset($_POST['nonce']) ||
203 !wp_verify_nonce(sanitize_key(wp_unslash($_POST['nonce'])), 'image_hub_nonce')
204 ) {
205 wp_send_json_error('Nonce verification failed.');
206 }
207 if (isset($_POST['provider']) && $_POST['provider'] === 'unsplash') {
208 // error_log( 'Unsplash image detected, skipping resize.' );
209 return;
210 }
211
212 $editor = wp_get_image_editor($file_path);
213 if (is_wp_error($editor)) {
214 return;
215 }
216
217 $max_width = get_option('image_hub_max_image_width');
218 $max_height = get_option('image_hub_max_image_height');
219 if ($max_width || $max_height) {
220 $editor->resize($max_width, $max_height, false);
221 $editor->save($file_path);
222 }
223 }
224
225 /**
226 * Updates attachment metadata.
227 */
228 static function update_attachment_data($image_id, $data, $file_path)
229 {
230 $attachment_data = [
231 'ID' => $image_id,
232 'post_title' => $data['title'],
233 'post_content' => $data['description'],
234 ];
235
236 if (get_option('image_hub_enable_image_attribution', false)) {
237 $attachment_data['post_excerpt'] = $data['caption'];
238 }
239
240 wp_update_post($attachment_data);
241
242 if (!empty($data['alt'])) {
243 update_post_meta($image_id, '_wp_attachment_image_alt', $data['alt']);
244 }
245
246 $attach_data = wp_generate_attachment_metadata($image_id, $file_path);
247 wp_update_attachment_metadata($image_id, $attach_data);
248 }
249 }
250