-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimageapi_optimize_shortpixel.module
More file actions
245 lines (205 loc) · 6.6 KB
/
Copy pathimageapi_optimize_shortpixel.module
File metadata and controls
245 lines (205 loc) · 6.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
<?php
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Site\Settings;
use Drupal\image\Entity\ImageStyle;
/**
* Implements hook_file_url_alter().
*/
function imageapi_optimize_shortpixel_file_url_alter(&$uri) {
$settings = \Drupal::config('imageapi_optimize_shortpixel.settings');
if (!$settings->get('use_cdn')) {
return;
}
$public_uri = imageapi_optimize_shortpixel_normalize_supported_public_image_uri($uri);
if ($public_uri === NULL) {
return;
}
imageapi_optimize_shortpixel_prepare_derivative_if_needed($public_uri);
$original_url = imageapi_optimize_shortpixel_get_absolute_public_url($public_uri);
if ($original_url === NULL) {
return;
}
$cdn_url = imageapi_optimize_shortpixel_build_cdn_url($settings, $original_url);
if ($cdn_url !== NULL) {
$uri = $cdn_url;
}
}
/**
* Normalizes a supported public image reference to a public:// URI.
*/
function imageapi_optimize_shortpixel_normalize_supported_public_image_uri(string $uri): ?string {
if (str_starts_with($uri, 'public://')) {
return imageapi_optimize_shortpixel_is_supported_public_image_uri($uri) ? $uri : NULL;
}
$public_uri = imageapi_optimize_shortpixel_convert_public_url_to_uri($uri);
if ($public_uri === NULL) {
return NULL;
}
return imageapi_optimize_shortpixel_is_supported_public_image_uri($public_uri) ? $public_uri : NULL;
}
/**
* Determines whether the URI can be rewritten to the CDN.
*/
function imageapi_optimize_shortpixel_is_supported_public_image_uri(string $uri): bool {
if (!str_starts_with($uri, 'public://')) {
return FALSE;
}
$target = preg_replace('@^[a-z0-9_]+://@i', '', $uri);
$path = strtok($target, '?') ?: $target;
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
return in_array($extension, [
'avif',
'bmp',
'heic',
'heif',
'gif',
'ico',
'jpeg',
'jpg',
'png',
'svg',
'tif',
'tiff',
'webp',
], TRUE);
}
/**
* Converts a public files URL or path back into a public:// URI.
*/
function imageapi_optimize_shortpixel_convert_public_url_to_uri(string $uri): ?string {
$parts = parse_url($uri);
if ($parts === FALSE) {
return NULL;
}
if (!empty($parts['scheme']) && !in_array(strtolower($parts['scheme']), ['http', 'https'], TRUE)) {
return NULL;
}
$path = $parts['path'] ?? '';
if ($path === '') {
return NULL;
}
$request = \Drupal::requestStack()->getCurrentRequest();
if (!empty($parts['host']) && $request && strcasecmp($parts['host'], $request->getHost()) !== 0) {
return NULL;
}
$public_path = trim((string) Settings::get('file_public_path', 'sites/default/files'), '/');
if ($public_path === '') {
return NULL;
}
$prefixes = ['/' . $public_path];
if ($request) {
$base_path = trim($request->getBasePath(), '/');
if ($base_path !== '') {
$prefixes[] = '/' . $base_path . '/' . $public_path;
}
}
foreach (array_unique($prefixes) as $prefix) {
if ($path === $prefix) {
return 'public://';
}
if (str_starts_with($path, $prefix . '/')) {
return 'public://' . ltrim(substr($path, strlen($prefix)), '/');
}
}
return NULL;
}
/**
* Ensures a style derivative exists before the URL is rewritten to the CDN.
*/
function imageapi_optimize_shortpixel_prepare_derivative_if_needed(string $uri): void {
$derivative = imageapi_optimize_shortpixel_parse_derivative_uri($uri);
if ($derivative === NULL) {
return;
}
$file_system = \Drupal::service('file_system');
$derivative_path = $file_system->realpath($uri);
if ($derivative_path && is_file($derivative_path)) {
return;
}
$original_uri = $derivative['source_scheme'] . '://' . $derivative['source_target'];
$original_path = $file_system->realpath($original_uri);
if (!$original_path || !is_file($original_path)) {
return;
}
$style = ImageStyle::load($derivative['style_name']);
if (!$style) {
return;
}
try {
$style->createDerivative($original_uri, $uri);
}
catch (\Throwable $e) {
\Drupal::logger('imageapi_optimize_shortpixel')->warning('Failed to prepare derivative @uri before CDN rewrite: @message', [
'@uri' => $uri,
'@message' => $e->getMessage(),
]);
}
}
/**
* Parses a Drupal image style derivative URI.
*/
function imageapi_optimize_shortpixel_parse_derivative_uri(string $uri): ?array {
$matches = [];
if (!preg_match('@^(?P<scheme>[a-z0-9_]+)://styles/(?P<style_name>[^/]+)/(?P<source_scheme>[^/]+)/(?P<source_target>.+)$@i', $uri, $matches)) {
return NULL;
}
return [
'scheme' => $matches['scheme'],
'style_name' => $matches['style_name'],
'source_scheme' => $matches['source_scheme'],
'source_target' => $matches['source_target'],
];
}
/**
* Converts a public stream wrapper URI into an absolute URL without recursion.
*/
function imageapi_optimize_shortpixel_get_absolute_public_url(string $uri): ?string {
$wrapper = \Drupal::service('stream_wrapper_manager')->getViaUri($uri);
if (!$wrapper) {
return NULL;
}
$external_url = $wrapper->getExternalUrl();
if ($external_url === '' || $external_url === FALSE) {
return NULL;
}
if (preg_match('@^https?://@i', $external_url)) {
return $external_url;
}
$request = \Drupal::requestStack()->getCurrentRequest();
if (!$request) {
return NULL;
}
if (str_starts_with($external_url, '//')) {
return $request->getScheme() . ':' . $external_url;
}
$path = str_starts_with($external_url, '/') ? $external_url : '/' . ltrim($external_url, '/');
return $request->getSchemeAndHttpHost() . $path;
}
/**
* Builds the Adaptive Images CDN URL for the given original asset.
*/
function imageapi_optimize_shortpixel_build_cdn_url(ImmutableConfig $settings, string $original_url): ?string {
$cdn_base_url = rtrim(trim((string) $settings->get('cdn_base_url')), '/');
if ($cdn_base_url === '') {
return NULL;
}
$compression_type = (string) $settings->get('compression_type');
if (!in_array($compression_type, ['lossy', 'glossy', 'lossless'], TRUE)) {
$compression_type = 'glossy';
}
$client_key = imageapi_optimize_shortpixel_get_client_key();
$parameters = implode(',', [
'to_auto',
'q_' . $compression_type,
'ret_wait',
]);
return $cdn_base_url . '/' . $client_key . '/' . $parameters . '/' . $original_url;
}
/**
* Returns an alphanumeric CDN client key derived from the Drupal site UUID.
*/
function imageapi_optimize_shortpixel_get_client_key(): string {
$uuid = (string) \Drupal::config('system.site')->get('uuid');
$client_key = strtolower(preg_replace('/[^a-z0-9]/i', '', $uuid) ?? '');
return $client_key !== '' ? substr($client_key, 0, 24) : 'drupalshortpixel';
}