-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.php
More file actions
468 lines (413 loc) · 15.3 KB
/
Copy pathhelpers.php
File metadata and controls
468 lines (413 loc) · 15.3 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
<?php
// ==========================================================
//
// Config
global $karappo_common_config;
$karappo_common_config = [
'breakpoint' => 1000,
];
/**
* karappo-common のデフォルト設定を上書きする
* テーマの functions.php 等で呼び出す:
* karappo_common_config(['breakpoint' => 700]);
*
* @param array $overrides 上書きする設定の連想配列
*/
function karappo_common_config($overrides) {
global $karappo_common_config;
$karappo_common_config = array_merge($karappo_common_config, $overrides);
}
// ==========================================================
//
// Helpers
function assets_image_path($path) {
// $srcが絶対パス(http://や/からはじまる場合)ならそのまま使うが、それ以外はassets/image/から読み込む
if (
preg_match('/^https?:\/\//', $path) ||
preg_match('/^\//', $path)
) {
return $path;
}
return get_template_directory_uri() . "/assets/image/$path";
}
/**
* 単純なimgタグ
* @param string $src Path to image
* @param string $attrs Attributes e.g. 'alt="description of image" data-value="hoge"'
* @param bool $return Set true if you just want result without echo
* @return string
*/
function image_tag($src, $attrs = '', $return = false) {
$src = assets_image_path($src);
// altが未設定の場合は attrs="" を追加
if(!preg_match('/alt=".*"/', $attrs)) {
$attrs .= ' alt=""';
}
$res = "<img $attrs src=\"$src\">";
if($return){
return $res;
}
echo $res;
}
/**
* PC/SP用の2つのimgタグ(それぞれpc,spクラスを付与)
* @param string $src Path to image
* @param string $attrs Attributes e.g. 'alt="description of image" data-value="hoge"'
* @param bool $return Set true if you just want result without echo
* @return string or null
*/
function image_tag_sp($src, $attrs = '', $return = false) {
// attrの中からclassを抜き出す
$class_val = '';
if(preg_match('/class="(.*)"/', $attrs, $match)){
$class_val = " $match[1]";
$attrs = preg_replace('/(class="\w+")/', '', $attrs);
}
// altが未設定の場合は attrs="" を追加
if(!preg_match('/alt=".*"/', $attrs)) {
$attrs .= ' alt=""';
}
$src_sp = preg_replace('/\.(\w+)$/', '-sp.$1', $src);
$asset_src = assets_image_path($src);
$asset_src_sp = assets_image_path($src_sp);
$res =
"<img class=\"pc$class_val\" $attrs src=\"$asset_src\">
<img class=\"sp$class_val\" $attrs src=\"$asset_src_sp\">";
if($return){
return $res;
}
echo $res;
}
/**
* $srcで指定したパスに自動で@2xをつけてsrcsetを設定する
* @param string $src Path to image
* @param string $attrs Attributes e.g. 'alt="description of image" data-value="hoge"'
* @param bool $return Set true if you just want result without echo
* @return string or null
*/
function img_tag($src, $attrs = '', $return = false) {
$src_2x = preg_replace('/(\.\w+)$/', '@2x$1', $src);
// 画像毎にhash値が違うので注意
$asset_src = assets_image_path($src);
$asset_src_2x = assets_image_path($src_2x);
// altが未設定の場合は attrs="" を追加
if(!preg_match('/alt=".*"/', $attrs)) {
$attrs .= ' alt=""';
}
$res = "<img $attrs src=\"$asset_src\" srcset=\"$asset_src_2x 2x\">";
if($return){
return $res;
}
echo $res;
}
/**
* $srcで指定したパスに自動で@2xをつけてsrcsetを設定する
* PC/SP用の2つのimgタグ(それぞれpc,spクラスを付与)
* @param string $src Path to image
* @param string $attrs Attributes e.g. 'alt="description of image" data-value="hoge"'
* @param bool $return Set true if you just want result without echo
* @return string or null
*/
function img_tag_sp($src, $attrs = '', $return = false) {
$src_2x = preg_replace('/(\.\w+)$/', '@2x$1', $src);
// attrの中からclassを抜き出す
$class_val = '';
if(preg_match('/class="(.+)"/', $attrs, $match)){
$class_val = " $match[1]";
$attrs = preg_replace('/(class="\w+")/', '', $attrs);
}
// altが未設定の場合は attrs="" を追加
if(!preg_match('/alt=".*"/', $attrs)) {
$attrs .= ' alt=""';
}
$src_sp = preg_replace('/\.(\w+)$/', '-sp.$1', $src);
$src_sp_2x = preg_replace('/(\.\w+)$/', '@2x$1', $src_sp);
$asset_src = assets_image_path($src);
$asset_src_2x = assets_image_path($src_2x);
$asset_src_sp = assets_image_path($src_sp);
$asset_src_sp_2x = assets_image_path($src_sp_2x);
$res = "<img class=\"pc$class_val\" $attrs src=\"$asset_src\" srcset=\"$asset_src_2x 2x\"><img class=\"sp$class_val\" $attrs src=\"$asset_src_sp\" srcset=\"$asset_src_sp_2x 2x\">";
if($return){
return $res;
}
echo $res;
}
/**
* 画像のローカルファイルパスを取得
* @param string $src 相対パス(assets/image/以下)
* @return string ローカルファイルパス
*/
function get_image_filepath($src) {
return get_template_directory() . "/assets/image/$src";
}
/**
* <picture>タグによるレスポンシブ画像(@2x対応あり)
* 使用例: pict_tag('top/hero.png', 'alt=""');
* 出力:
* <picture>
* <source media="(max-width: 1000px)" srcset="top/hero-sp.png, top/hero-sp@2x.png 2x">
* <img src="top/hero.png" srcset="top/hero@2x.png 2x" alt="">
* </picture>
*
* @param string $src 画像パス
* @param string $attrs 属性文字列
* @param int|null $bp ブレークポイント(省略時はグローバル設定値)
* @param bool $return trueなら文字列を返す
* @return string|null
*/
function pict_tag($src, $attrs = '', $bp = null, $return = false) {
global $karappo_common_config;
if ($bp === null) $bp = $karappo_common_config['breakpoint'];
$sp_src = preg_replace('/(\.\w+)$/', '-sp$1', $src);
$sp_retina_src = preg_replace('/(\.\w+)$/', '@2x$1', $sp_src);
$source_srcset = assets_image_path($sp_src) . ', ' . assets_image_path($sp_retina_src) . ' 2x';
$sp_attrs = '';
$sp_filepath = get_image_filepath($sp_src);
if (file_exists($sp_filepath)) {
$sp_size = getimagesize($sp_filepath);
if ($sp_size) {
$sp_attrs = ' width="' . $sp_size[0] . '" height="' . $sp_size[1] . '"';
}
}
$fallback = img_tag($src, $attrs, true);
$res = '<picture><source media="(max-width: ' . $bp . 'px)" srcset="' . $source_srcset . '"' . $sp_attrs . '>' . $fallback . '</picture>';
if ($return) {
return $res;
}
echo $res;
}
/**
* <picture>タグによるレスポンシブ画像(@2xなし)
* .webp指定時はフォールバック用のPNG/JPGパスも自動導出
* 使用例: picture_tag('top/hero.png', 'alt=""');
* 出力:
* <picture>
* <source media="(max-width: 1000px)" srcset="top/hero-sp.png">
* <img src="top/hero.png" alt="">
* </picture>
*
* @param string $src 画像パス
* @param string $attrs 属性文字列
* @param int|null $bp ブレークポイント(省略時はグローバル設定値)
* @param bool $return trueなら文字列を返す
* @return string|null
*/
function picture_tag($src, $attrs = '', $bp = null, $return = false) {
global $karappo_common_config;
if ($bp === null) $bp = $karappo_common_config['breakpoint'];
$is_webp = preg_match('/\.webp$/', $src);
// .webp指定時はフォールバック用のPNG/JPGパスを導出
$fallback_src = null;
if ($is_webp) {
foreach (['.png', '.jpg'] as $ext) {
$candidate = preg_replace('/\.webp$/', $ext, $src);
if (file_exists(get_image_filepath($candidate))) {
$fallback_src = $candidate;
break;
}
}
}
$sp_src = preg_replace('/(\.\w+)$/', '-sp$1', $src);
$sp_attrs = '';
$sp_filepath = get_image_filepath($sp_src);
if (file_exists($sp_filepath)) {
$sp_size = getimagesize($sp_filepath);
if ($sp_size) {
$sp_attrs = ' width="' . $sp_size[0] . '" height="' . $sp_size[1] . '"';
}
}
if ($is_webp && $fallback_src) {
$fallback_sp_src = preg_replace('/(\.\w+)$/', '-sp$1', $fallback_src);
$fallback = image_tag($fallback_src, $attrs, true);
$sources = '';
// WebP SP
if (file_exists($sp_filepath)) {
$sources .= '<source media="(max-width: ' . $bp . 'px)" srcset="' . assets_image_path($sp_src) . '" type="image/webp"' . $sp_attrs . '>';
}
// WebP PC
$sources .= '<source srcset="' . assets_image_path($src) . '" type="image/webp">';
// Fallback SP
if (file_exists(get_image_filepath($fallback_sp_src))) {
$sources .= '<source media="(max-width: ' . $bp . 'px)" srcset="' . assets_image_path($fallback_sp_src) . '"' . $sp_attrs . '>';
}
$res = '<picture>' . $sources . $fallback . '</picture>';
} else {
$source_srcset = assets_image_path($sp_src);
$fallback = image_tag($src, $attrs, true);
$res = '<picture><source media="(max-width: ' . $bp . 'px)" srcset="' . $source_srcset . '"' . $sp_attrs . '>' . $fallback . '</picture>';
}
if ($return) {
return $res;
}
echo $res;
}
/**
* SVGファイルをinline出力
* @param string $src Path to image
* @param string $attrs Attributes e.g. 'alt="description of image" data-value="hoge"'
* @param bool $return Set true if you just want result without echo
* @return string
*/
function inline_svg($src, $attrs = '', $return = false) {
$src = assets_image_path($src);
// デバッグ情報を出力
// echo 'SVG Source URL: ' . $src;
// まずローカルファイルパスとして試行
$local_path = str_replace(get_template_directory_uri(), get_template_directory(), $src);
// echo 'Local Path: ' . $local_path;
// echo 'File exists: ' . (file_exists($local_path) ? 'Yes' : 'No');
if (file_exists($local_path)) {
$res = file_get_contents($local_path);
} else {
// ホスト名が.testで終わる場合にSSL検証を無効にする
$options = [];
if (preg_match('/\.test$/', $_SERVER['HTTP_HOST'])) {
echo '.test';
$options = [
"ssl" => [
"verify_peer" => false,
"verify_peer_name" => false,
],
];
}
$context = stream_context_create($options);
$res = file_get_contents($src, false, $context);
}
if ($attrs != '') {
// attrをもともとのattributesとマージして置換
preg_match('/<svg ([^\>]*)>/', $res, $_matches);
$attr_array = array_merge_recursive(parseAttributes($_matches[1]), parseAttributes($attrs));
$attrs = '';
foreach ($attr_array as $key => $value) {
if (is_array($value)) {
$value = implode(' ', $value);
}
$attrs .= " $key=\"$value\"";
}
$res = str_replace($_matches[1], $attrs, $res);
}
if($return){
return $res;
}
echo $res;
}
/**
* $srcで指定したパスに自動で@2xをつけて2つのSVGファイルをinline出力(それぞれpc,spクラスを付与)
* @param string $src Path to image
* @param string $attrs Attributes e.g. 'alt="description of image" data-value="hoge"'
* @param bool $return Set true if you just want result without echo
* @return string
*/
function inline_svg_sp($src, $attrs = '', $return = false) {
// attrの中からclassを抜き出す
$class_val = '';
if(preg_match('/class="(.*)"/', $attrs, $match)){
$class_val = " $match[1]";
$attrs = preg_replace('/(class="\w+")/', '', $attrs);
}
$src_sp = preg_replace('/\.(\w+)$/', '-sp.$1', $src);
inline_svg($src, "class=\"pc$class_val\" $attrs", $return);
inline_svg($src_sp, "class=\"sp$class_val\" $attrs", $return);
}
/**
* HTMLのattributesを配列化
* @param string $str : 'attr1="hoge" attr2="moge"'
* @return array : ["attr1"=> "hoge", "attr2"=>"moge"]
*/
function parseAttributes($str){
preg_match_all('/(\w+)=[\'"]([^\'"]*)/', $str, $matches, PREG_SET_ORDER);
$res = [];
foreach($matches as $match){
$attrName = $match[1];
//parse the string value into an integer if it's numeric,
// leave it as a string if it's not numeric,
$attrValue = is_numeric($match[2])? (int)$match[2]: trim($match[2]);
$res[$attrName] = $attrValue; //add match to results
}
return $res;
}
/**
* $linkに応じてhrefやtargetなどのattrを設定して返す
* @param string | array $link arrayはACFproのリンクオブジェクトの連想配列
* @return string
*/
/**
* テキスト中のURLを自動的に <a> 化する。
* 外部ホスト(home_url のホスト名と異なるもの)には target="_blank" rel="noopener" を付与する。
*
* 戻り値はサニタイズしていないHTMLなので、ユーザー入力を扱う場合は wp_kses_post() 等でラップして出力すること。
* 例: echo wp_kses_post(auto_link($profile));
*
* @param string $text 元テキスト(プレーンテキスト or HTML)
* @return string URLがリンク化されたHTML
*/
function auto_link($text) {
if (!is_string($text) || $text === '') return $text;
// make_clickable は `<br />\r\n` のようなCRLFが入ると URL を検出できないので正規化
$html = make_clickable(str_replace(["\r\n", "\r"], "\n", $text));
$site_host = wp_parse_url(home_url(), PHP_URL_HOST);
return preg_replace_callback(
'/<a\s+([^>]*?)href=(["\'])([^"\']+)\2([^>]*?)>/i',
function ($m) use ($site_host) {
$host = wp_parse_url($m[3], PHP_URL_HOST);
if (!$host || strcasecmp($host, $site_host) === 0) {
return $m[0];
}
$attrs = $m[1] . $m[4];
$extra = '';
if (stripos($attrs, 'target=') === false) {
$extra .= ' target="_blank"';
}
if (stripos($attrs, 'rel=') === false) {
$extra .= ' rel="noopener"';
}
return '<a ' . $m[1] . 'href=' . $m[2] . $m[3] . $m[2] . $m[4] . $extra . '>';
},
$html
);
}
function get_attr_for_link($link) {
$attr = '';
// $linkが文字列だったら
if (is_string($link) && $link) {
$link_url = $link;
$attr = 'href="'.esc_url( $link_url ).'"';
}
// $linkが連想配列だったら
else if (is_array($link)) {
$link_url = $link['url'];
if ($link_url) {
$link_target = $link['target'] ? $link['target'] : '_self';
$attr = 'href="'.esc_url( $link_url ).'" target="'.esc_attr( $link_target ).'"';
}
}
return $attr;
}
// ==========================================================
//
// Asset cache busting
//
// テーマ内アセットのファイル更新時刻(mtime)を `?ver=` に渡し、
// 編集の都度ブラウザ・実機キャッシュが自動で切れるようにする。
/**
* テーマディレクトリ起点の相対パスからファイルの mtime を返す
* @param string $relative_path 例: 'assets/css/common.css'
* @return string|false 10進文字列。ファイルが無ければ false(WP デフォルトの ver にフォールバック)
*/
function asset_version($relative_path) {
$abs = get_template_directory() . '/' . ltrim($relative_path, '/');
return file_exists($abs) ? (string) filemtime($abs) : false;
}
/**
* wp_enqueue_style のラッパー。version に asset_version() を渡す。
*/
function enqueue_style_with_version($handle, $relative_path, $deps = []) {
wp_enqueue_style($handle, get_template_directory_uri() . '/' . ltrim($relative_path, '/'), $deps, asset_version($relative_path));
}
/**
* wp_enqueue_script のラッパー。version に asset_version() を渡す。
* デフォルトで footer 出力($in_footer = true)。
*/
function enqueue_script_with_version($handle, $relative_path, $deps = [], $in_footer = true) {
wp_enqueue_script($handle, get_template_directory_uri() . '/' . ltrim($relative_path, '/'), $deps, asset_version($relative_path), $in_footer);
}