-
Notifications
You must be signed in to change notification settings - Fork 6
/
RockFrontend.module.php
2556 lines (2270 loc) 路 78.3 KB
/
RockFrontend.module.php
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace ProcessWire;
use Latte\Bridges\Tracy\LattePanel;
use Latte\Engine;
use Latte\Runtime\Html;
use RockFrontend\Asset;
use RockFrontend\LiveReload;
use RockFrontend\Manifest;
use RockFrontend\ScriptsArray;
use RockFrontend\Seo;
use RockFrontend\StylesArray;
use RockPageBuilder\Block;
use Sabberworm\CSS\OutputFormat;
use Sabberworm\CSS\Parser;
use Sabberworm\CSS\Rule\Rule;
use Sabberworm\CSS\RuleSet\AtRuleSet;
use Sabberworm\CSS\RuleSet\RuleSet;
/**
* @author Bernhard Baumrock, 05.01.2022
* @license MIT
* @link https://www.baumrock.com
*
* @method string render($filename, array $vars = array(), array $options = array())
*/
class RockFrontend extends WireData implements Module, ConfigurableModule
{
const tags = "RockFrontend";
const prefix = "rockfrontend_";
const tagsUrl = "/rockfrontend-layout-suggestions/{q}";
const permission_alfred = "rockfrontend-alfred";
const livereloadCacheName = "rockfrontend_livereload"; // also in livereload.php
const getParam = 'rockfrontend-livereload';
const cache = 'rockfrontend-uikit-versions';
const installedprofilekey = 'rockfrontend-installed-profile';
const recompile = 'rockfrontend-recompile-less';
const defaultVspaceScale = 0.66;
const webfont_agents = [
'woff2' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0', // very modern browsers
'woff' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0', // modern browsers
'ttf' => 'Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/538.1 (KHTML, like Gecko) Safari/538.1 Daum/4.1', // safari, android, ios
'svg' => 'Mozilla/4.0 (iPad; CPU OS 4_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/4.1 Mobile/9A405 Safari/7534.48.3', // legacy ios
'eot' => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)', // IE
];
const webfont_comments = [
'woff2' => '/* Super Modern Browsers */',
'woff' => '/* Pretty Modern Browsers */',
'ttf' => '/* Safari, Android, iOS */',
'svg' => '/* Legacy iOS */',
];
const field_layout = self::prefix . "layout";
const field_favicon = self::prefix . "favicon";
const field_ogimage = self::prefix . "ogimage";
const field_footerlinks = self::prefix . "footerlinks";
/** @var WireData */
public $alfredCache;
/** @var WireArray $folders */
public $folders;
public $home;
/** @var bool */
public $hasAlfred = false;
public $isLiveReload = false;
/** @var array */
protected $js = [];
/** @var Engine */
private $latte;
/** @var WireArray $layoutFolders */
public $layoutFolders;
/** @var Manifest */
protected $manifest;
/** @var bool */
public $noAssets = false;
/** @var string */
public $path;
/** @var WireData */
public $postCSS;
/**
* REM base value (16px)
*/
public $remBase;
/** @var Seo */
public $seo;
private $scripts;
private $styles;
private $textdomain;
/** @var array */
private $translations = [];
public function __construct()
{
if (!$this->wire->config->livereload) return;
if ($this->wire->config->ajax) return;
if (!array_key_exists(self::getParam, $_GET)) return;
$this->addHookBefore("Session::init", function (HookEvent $event) {
// disable tracy for the SSE stream
$event->wire->config->tracy = ['enabled' => false];
// get livereload instance
$live = $this->getLiveReload();
// return silently if secret does not match
// somehow this check is called twice and always throws an error
if (!$live->validSecret()) return;
$event->object->sessionAllow = false;
$this->isLiveReload = true;
$live->watch();
});
}
public function init()
{
$this->wire->classLoader->addNamespace("RockFrontend", __DIR__ . "/classes");
$this->path = $this->wire->config->paths($this);
$this->home = $this->wire->pages->get(1);
if (!is_array($this->features)) $this->features = [];
if (!is_array($this->migrations)) $this->migrations = [];
// make $rockfrontend and $home variable available in template files
$this->wire('rockfrontend', $this);
$this->wire('home', $this->home);
$this->alfredCache = $this->wire(new WireData());
// JS defaults
$this->remBase = 16; // default base for px-->rem conversion
$this->initPostCSS();
// watch this file and run "migrate" on change or refresh
if ($rm = $this->rm()) $rm->watch($this, 0.01);
// setup folders that are scanned for files
$this->folders = $this->wire(new WireArray());
$this->folders->add($this->config->paths->templates);
$this->folders->add($this->config->paths->assets);
$this->folders->add($this->config->paths->root);
// layout folders
$this->layoutFolders = $this->wire(new WireArray());
$this->layoutFolders->add($this->config->paths->templates);
$this->layoutFolders->add($this->config->paths->assets);
// Alfred
require_once __DIR__ . "/Functions.php";
$this->createPermission(
self::permission_alfred,
"Is allowed to use ALFRED frontend editing"
);
$this->createCSS();
// hooks
$this->addHookAfter("ProcessPageEdit::buildForm", $this, "hideLayoutField");
$this->addHook(self::tagsUrl, $this, "layoutSuggestions");
$this->addHookAfter("Modules::refresh", $this, "refreshModules");
$this->addHookBefore('TemplateFile::render', $this, "autoPrepend");
$this->addHookAfter("InputfieldForm::processInput", $this, "createWebfontsFile");
$this->addHookBefore("Inputfield::render", $this, "addFooterlinksNote");
// health checks
$this->checkHealth();
}
public function ready()
{
$this->liveReload();
$this->addAssets();
}
/**
* Add assets to the html markup
* @return void
*/
public function addAssets()
{
// hook after page render to add script
// this will also replace alfred tags
$this->addHookAfter(
"Page::render",
function (HookEvent $event) {
$html = $event->return;
$styles = $this->styles();
$scripts = $this->scripts();
// early exit if asset injection is disabled
// Usage: place "$rockfrontend->noAssets = true" somewhere in your
// template file to prevent loading of any rockfrontend assets
if ($this->noAssets) return;
// early exit if html does not contain a head section
if (!strpos($html, "</head>")) return;
// add livereload secret
if ($this->wire->config->livereload) {
$this->js("rootUrl", $this->wire->config->urls->root);
// create secret and send it to js
/** @var WireRandom $rand */
$rand = $this->wire(new WireRandom());
$cache = $this->wire->cache->get(self::livereloadCacheName);
if (!is_array($cache)) $cache = [];
$secret = $rand->alphanumeric(0, ['minLength' => 30, 'maxLength' => 40]);
$merged = array_merge($cache, [$secret]);
$this->wire->cache->save(self::livereloadCacheName, $merged);
$this->js("livereloadSecret", $secret);
}
// load RockFrontend frontend js file
$file = __DIR__ . "/RockFrontend.js";
if ($this->wire->config->debug) {
// load the non-minified script
$this->scripts()->add($file, "defer");
// when logged in as superuser we make sure to create the minified
// file even if the non-minified version is used.
if ($this->wire->user->isSuperuser()) $this->minifyFile($file);
} else $this->scripts()->add($this->minifyFile($file), "defer");
// load alfred?
if ($this->loadAlfred()) {
$this->js("rootUrl", $this->wire->config->urls->root);
$this->js("defaultVspaceScale", number_format(self::defaultVspaceScale, 2, ".", ""));
$this->scripts()->add($this->path . "Alfred.js");
$this->addAlfredStyles();
// replace alfred cache markup
// if alfred was added without |noescape it has quotes around
if (strpos($html, '"#alfredcache-')) {
foreach ($this->alfredCache as $key => $str) {
$html = str_replace("\"$key\"", $str, $html);
}
}
// if alfred was added with |noescape filter we don't have quotes
if (strpos($html, '#alfredcache-')) {
foreach ($this->alfredCache as $key => $str) {
$html = str_replace("$key", $str, $html);
}
}
// add a fake edit tag to the page body
// this ensures that jQuery is loaded via PageFrontEdit
$faketag = "<div edit=title hidden>title</div>";
$html = str_replace("</body", "$faketag</body", $html);
}
$this->addTopBar($html);
// at the very end we inject the js variables
$assets = '';
$json = count($this->js) ? json_encode($this->js) : '{}';
$assets .= "<script>let RockFrontend = $json</script>";
// check if assets have already been added
// if not we inject them at the end of the <head>
if (!strpos($html, StylesArray::comment)) $assets .= $styles->render();
if (!strpos($html, ScriptsArray::comment)) $assets .= $scripts->render();
// return replaced markup
$html = str_replace("</head>", "$assets</head>", $html);
$event->return = $html;
}
);
}
/**
* Render a portion of HTML that needs consent from the user.
*
* This will replace all "src" attributes by "data-src" attributes.
* All scripts will therefore only be loaded when the user clicks on the
* consent button.
*
* Usage:
* $rockfrontend->consent(
* 'youtube',
* '<iframe src=...',
* '<a href=# rfc-allow=youtube>Allow YouTube-Player on this website</a>'
* );
*
* You can also render files instead of markup:
* $rockfrontend->consent(
* 'youtube'
* 'your youtube embed code',
* 'sections/youtube-consent.latte'
* );
*/
public function consent($name, $enabled, $disabled = null)
{
$enabled = str_replace(" src=", " rfconsent='$name' rfconsent-src=", $enabled);
if ($disabled) {
// we only add the wrapper if we have a disabled markup
// if we dont have a disabled markup that means we only have
// a script tag (like plausible analytics) so we don't need the
// wrapping div!
$enabled = "<div data-rfc-show='$name' hidden>$enabled</div>";
$file = $this->getFile($disabled);
if ($file) $disabled = $this->render($file);
$disabled = "<div data-rfc-hide='$name' hidden>$disabled</div>";
}
return $this->html($enabled . $disabled);
}
public function consentOptout($name, $script)
{
$enabled = str_replace(" src=", " rfconsent='$name' rfconsent-type=optout rfconsent-src=", $script);
return $this->html($enabled);
}
public function ___addAlfredStyles()
{
$this->styles()->add($this->path . "Alfred.css", "", ['minify' => false]);
}
/**
* Add note for superusers on footerlinks inputfield
*/
public function addFooterlinksNote(HookEvent $event)
{
if (!$this->wire->user->isSuperuser()) return;
$f = $event->object;
if ($f->name != self::field_footerlinks) return;
if ($f->notes) $f->notes .= "\n";
$f->notes .= "Superuser Note: Use \$rockfrontend->footerlinks() to access links as a PageArray in your template file (ready for foreach).";
}
private function addLiveReloadScript()
{
// we only add live reloading to the frontend
if ($this->wire->page->template == 'admin') return;
$this->scripts()->add($this->path . "livereload.min.js", "defer");
}
/**
* Return link to add a new page under given parent
* @return string
*/
public function addPageLink($parent)
{
$admin = $this->wire->pages->get(2)->url;
return $admin . "page/add/?parent_id=$parent";
}
/**
* Add a custom postCSS callback
*
* Usage:
* $rockfrontend->addPostCSS('foo', function($markup) {
* return str_replace('foo', 'bar', $markup);
* });
*/
public function addPostCSS($key, $callback)
{
$this->postCSS->set($key, $callback);
}
/**
* Show topbar with sitemap and edit and mobile preview
*/
public function addTopBar(&$html)
{
if (!$this->isEnabled('topbar')) return;
$page = $this->wire->page;
if (!$page->editable()) return;
if ($page->template == 'admin') return;
if ($this->wire->input->get('rfpreview')) return;
/** @var RockMigrations $rm */
$less = __DIR__ . "/bar/bar.less";
if ($rm = $this->wire->modules->get('RockMigrations')) {
// recompile less if changed
// check for method saveCSS to prevent errors on old installations
if (method_exists($rm, "saveCSS")) $rm->saveCSS($less);
}
$css = $this->toUrl("$less.css", true);
$style = "<link rel='stylesheet' href='$css'>";
$html = str_replace("</head", "$style</head", $html);
$topbar = $this->wire->files->render(__DIR__ . "/bar/topbar.php", [
'logourl' => $this->toUrl(__DIR__ . "/RockFrontend.svg", true),
'z' => is_int($this->topbarz) ? $this->topbarz : 999,
]);
$html = str_replace("</body", "$topbar</body", $html);
}
/**
* ALFRED - A Lovely FRontend EDitor
*
* Usage:
* alfred($page, "title,images")
*
* Usage with options array (for RockPageBuilder blocks)
* alfred($page, [
* 'trash' => false,
* 'fields' => 'foo,bar',
* ]);
*
* Show alfred without plus-icons for adding a new block before/after
* alfred($block, false);
*
* You can also provide fields as array when using the verbose syntax
* alfred($page, [
* 'trash' => false,
* 'fields' => [
* 'foo',
* 'bar',
* ],
* ]);
*
* @return string
*/
public function alfred($page = null, $options = [])
{
if (!$this->alfredAllowed()) return;
// support short syntax
if ($options === false) {
$options = [
'addTop' => false,
'addBottom' => false,
];
} elseif (is_string($options)) $options = ['fields' => $options];
// set flag to show that at least one alfred tag is on the page
// this flag is used to load the PW frontend editing assets
$this->hasAlfred = true;
// set the page to be edited
$p = false;
if ($page) $p = $this->wire->pages->get((string)$page);
if ($p instanceof Page and !$p->id) $p = false;
$page = $p;
// check if the current page is a RPB block
// that can happen if RPB blocks are used as regular pages (nfkinder)
// without this check we'd end up with RPB hover GUI for every
// alfred($page) call which is not what we want
// you can force showing the edit icon by alfred($page, ['noBlock' => true])
// eg for editing a single images field of the current page without showing other icons
$noBlock = array_key_exists('noBlock', $options);
if (!$noBlock and $page instanceof Block and $page->id === $this->wire->page->id) {
$page = false;
}
// setup options
/** @var WireData $opt */
$opt = $this->wire(new WireData());
$opt->setArray([
'fields' => '', // fields to edit
'path' => $this->getTplPath(), // path to edit file
'edit' => true,
'blockid' => null,
]);
$opt->setArray($options);
// add quick-add-icons for rockpagebuilder
if ($rpb = $this->wire->modules->get("RockPageBuilder")) {
/** @var RockPageBuilder $rpb */
$data = $this->wire(new WireData());
$data->page = $page;
$data->opt = $opt;
$data->options = $options;
$opt = $rpb->addAlfredOptions($data);
}
// bd($opt, 'opt after');
// icons
$icons = $this->getIcons($page, $opt);
if (!count($icons)) return;
$str = json_encode((object)[
'icons' => $icons,
'addTop' => $opt->addTop,
'addBottom' => $opt->addBottom,
'addLeft' => $opt->addLeft,
'addRight' => $opt->addRight,
'widgetStyle' => $opt->widgetStyle,
'type' => $opt->type,
]);
// save markup to cache and generate alfred tag
// the tag will be replaced on page render
// this is to make it possible to use alfred() without |noescape filter)
$id = uniqid();
$str = " {$opt->blockid} alfred='$str'";
$key = "#alfredcache-$id";
$this->alfredCache->set($key, $str);
return $key;
}
/**
* Shortcut to create ALFRED links with horizontal add buttons
* Thx @gebeer for the PR!!
* @return string
*/
public function alfredH($page = null, $options = [])
{
if ($options === false) {
$options = [
'addLeft' => false,
'addRight' => false,
];
}
return $this->alfred(
$page,
array_merge(['addHorizontal' => true], $options)
);
}
/**
* Is ALFRED allowed for current user?
*/
protected function alfredAllowed(): bool
{
if ($this->wire->user->isSuperuser()) return true;
if ($this->wire->user->hasPermission(self::permission_alfred)) return true;
return false;
}
/**
* Return full asset path from given path
*/
public function assetPath($path): string
{
$path = Paths::normalizeSeparators($path);
$dir = $this->wire->config->paths->assets . "RockFrontend/";
if (strpos($path, $dir) === 0) return $path;
return $dir . trim($path, "/");
}
/**
* Auto-prepend file before rendering for exposing variables from _init.php
*/
public function autoPrepend($event)
{
$event->object->setPrependFilename($this->path . "AutoPrepend.php");
}
/**
* Do several health checks
*/
private function checkHealth()
{
if (!$this->wire->user->isSuperuser()) return;
// removed version healthcheck as of v2.0.0
}
/**
* Create CSS from LESS file
* @return void
*/
private function createCSS()
{
if (!$this->wire->user->isSuperuser()) return;
$css = $this->path . "Alfred.css";
$lessFile = $this->path . "Alfred.less";
if (filemtime($css) > filemtime($lessFile)) return;
if (!$less = $this->wire->modules->get("Less")) return;
/** @var Less $less */
$less->addFile($lessFile);
$less->saveCSS($css);
$this->message("Created $css from $lessFile");
}
/**
* Create permission
* @return void
*/
private function createPermission($name, $title)
{
$p = $this->wire->permissions->get($name);
if ($p and $p->id) return;
$p = $this->wire->permissions->add($name);
$p->setAndSave('title', $title);
}
/**
* Download uikit
* @return void
*/
private function downloadUikit()
{
if (!$version = $this->wire->input->post('uikit', 'string')) return;
$url = "https://github.com/uikit/uikit/archive/refs/tags/$version.zip";
$tpl = $this->wire->config->paths->templates;
$tmp = (new WireTempDir());
(new WireHttp())->download($url, $tmp . "uikit.zip");
$this->wire->files->unzip($tmp . "uikit.zip", $tpl);
$this->wire->files->rmdir($tpl . "uikit", true);
foreach (glob($tpl . "uikit-*") as $dir) {
$this->wire->files->rename($dir, $tpl . "uikit");
}
}
public function editLinks($options = null, $list = true, $size = 32)
{
if ($options instanceof Page) {
$options = ['page' => $options];
}
$opt = $this->wire(new WireData());
$opt->setArray([
'page' => $this->wire->page,
'class' => 'tm-editlink',
]);
if (!$opt->page->editable()) return;
$pages = $this->wire->pages;
$li = $list ? '<li>' : '';
$endli = $list ? '</li>' : '';
return $this->html("
$li
<a class='{$opt->class}' href='{$pages->get(2)->url}'>
<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' aria-hidden='true' role='img' class='iconify iconify--tabler' width='$size' height='$size' preserveAspectRatio='xMidYMid meet' viewBox='0 0 24 24'><g fill='none' stroke='currentColor' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'><rect width='6' height='6' x='3' y='15' rx='2'></rect><rect width='6' height='6' x='15' y='15' rx='2'></rect><rect width='6' height='6' x='9' y='3' rx='2'></rect><path d='M6 15v-1a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v1m-6-6v3'></path></g></svg>
</a>
$endli
$li
<a class='{$opt->class}' href='{$opt->page->editUrl()}'>
<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' aria-hidden='true' role='img' class='iconify iconify--tabler' width='$size' height='$size' preserveAspectRatio='xMidYMid meet' viewBox='0 0 24 24'><g fill='none' stroke='currentColor' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'><path d='M7 7H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2v-1'></path><path d='M20.385 6.585a2.1 2.1 0 0 0-2.97-2.97L9 12v3h3l8.385-8.415zM16 5l3 3'></path></g></svg>
</a>
$endli
");
}
/**
* Find files to suggest
* @return array
*/
public function ___findSuggestFiles($q)
{
$suggestions = [];
foreach ($this->layoutFolders as $dir) {
// find all files to add
$files = $this->wire->files->find($dir, [
'extensions' => ['php'],
'excludeDirNames' => [
'cache',
],
]);
// modify file paths
$files = array_map(function ($item) use ($dir) {
// strip path from file
$str = str_replace($dir, "", $item);
// strip php file extension
return substr($str, 0, -4);
}, $files);
// only use files from within subfolders of the specified directory
$files = array_filter($files, function ($str) use ($q) {
if (!strpos($str, "/")) return false;
return !(strpos($str, $q) < 0);
});
// merge files into final array
$suggestions = array_merge(
$suggestions,
$files
);
}
// bd($suggestions);
return $suggestions;
}
/**
* Get all footerlinks
*/
public function footerlinks(): PageArray
{
return $this->wire->pages->get(1)->get(self::field_footerlinks . "[]");
}
/**
* Force recreation of CSS files
*/
public function forceRecompile()
{
$this->wire->session->set(self::recompile, true);
}
/**
* Get file path of file
*
* You can look for files in folders like this:
* $rf->getFile("mockups/demo.png");
*
* If path is relative we look in $this->folders for matching files
*
* @return string
*/
public function getFile($file, $forcePath = false)
{
if (strpos($file, "//") === 0) return $file;
if (strpos($file, "http://") === 0) return $file;
if (strpos($file, "https://") === 0) return $file;
$file = Paths::normalizeSeparators($file);
// we always add a slash to the file
// this is to ensure that relative paths are not found by is_file() below
// $file = "/".ltrim($file, "/");
// if no extension was provided try php or latte extension
if (!pathinfo($file, PATHINFO_EXTENSION)) {
if ($f = $this->getFile("$file.php", $forcePath)) return $this->realpath($f);
if ($f = $this->getFile("$file.latte", $forcePath)) return $this->realpath($f);
}
// if file exists return it
// this will also find files relative to /site/templates!
// TODO maybe prevent loading of relative paths outside assets?
$inRoot = $this->wire->files->fileInPath($file, $this->wire->config->paths->root);
if ($inRoot and is_file($file)) return $this->realpath($file);
// look for the file in specified folders
foreach ($this->folders as $folder) {
$folder = Paths::normalizeSeparators($folder);
$folder = rtrim($folder, "/") . "/";
$path = $folder . ltrim($file, "/");
if (is_file($path)) return $this->realpath($path);
}
// no file found
// if force path is set true we return the path nonetheless
// this should help on frontend development to get a 404 when using wrong paths
if ($forcePath) return $file;
// no file, return false
return false;
}
/**
* Get ALFRED icons
* @return array
*/
public function ___getIcons($page, $opt)
{
$icons = [];
// prepare fields suffix
$fields = '';
if ($page and $opt->fields) {
if (is_array($opt->fields)) $opt->fields = implode(",", $opt->fields);
// check if the requested fields are available on that page
// if the field does not exist for that page we don't request it
// this is to prevent exception errors breaking page editing
$sep = "&fields=";
foreach (explode(",", $opt->fields) as $field) {
$field = trim($field);
if (!$page->template->hasField($field)) continue;
$fields .= $sep . $field;
$sep = ",";
}
}
// icon to edit page
if ($page and $page->editable() and $opt->edit) {
$icons[] = (object)[
'icon' => 'edit',
'tooltip' => "Edit Block #{$page->id}",
'href' => $page->editUrl() . $fields,
'class' => 'pw-modal alfred-edit',
'suffix' => 'data-buttons="button.ui-button[type=submit]" data-autoclose data-reload',
];
}
// add rockpagebuilder icons
if ($page) {
$rpb = $this->wire->modules->get("RockPageBuilder");
if ($page instanceof Block) $page->addAlfredIcons($icons, $opt);
elseif ($page instanceof RepeaterPage and $rpb) {
$rpb->addAlfredIcons($page, $icons, $opt);
}
}
if ($this->wire->user->isSuperuser()) {
// view file edit link
$icons[] = (object)[
'icon' => 'code',
'label' => $opt->path,
'href' => $this->vscodeLink($opt->path),
'tooltip' => $opt->path,
];
$ext = pathinfo($opt->path, PATHINFO_EXTENSION);
// php file edit link
$php = substr($opt->path, 0, strlen($ext) * -1 - 1) . ".php";
if (is_file($php)) {
$icons[] = (object)[
'icon' => 'php',
'label' => $php,
'href' => $this->vscodeLink($php),
'tooltip' => $php,
];
}
// style edit link
$less = substr($opt->path, 0, strlen($ext) * -1 - 1) . ".less";
if (is_file($less)) {
$icons[] = (object)[
'icon' => 'eye',
'label' => $less,
'href' => $this->vscodeLink($less),
'tooltip' => $less,
];
}
}
return $icons;
}
/**
* Get layout from page field
* @return array|false
*/
public function getLayout($page)
{
$layout = $page->get(self::field_layout);
if (!$layout) return false;
return explode(" ", $layout);
}
/**
* Get a new instance of LiveReload
*/
public function getLiveReload(): LiveReload
{
require_once __DIR__ . "/LiveReload.php";
return new LiveReload();
}
/**
* Find path in rockfrontend folders
* Returns path with trailing slash
* @return string|false
*/
public function getPath($path, $forcePath = false)
{
$path = Paths::normalizeSeparators($path);
// if the path is already absolute and exists we return it
// we dont return relative paths!
// we also make sure that the path is somewhere within the pw root
// to prevent open basedir restriction warnings
$inRoot = strpos($path, $this->wire->config->paths->root) === 0;
if (strpos($path, '/') === 0 and $inRoot and is_dir($path)) {
return rtrim($path, '/') . '/';
}
foreach ($this->folders as $f) {
$dir = $f . ltrim($path, '/');
if (is_readable($dir) and is_dir($dir)) return rtrim($dir, '/') . '/';
}
if ($forcePath) return rtrim($path, '/') . '/';
return false;
}
/**
* Find template file from trace
* @return string
*/
public function getTplPath()
{
$trace = debug_backtrace();
$paths = $this->wire->config->paths;
foreach ($trace as $step) {
$file = $step['file'];
$skip = [
$paths->cache,
$paths($this),
$paths->root . "vendor/"
];
foreach ($skip as $p) {
if (strpos($file, $p) === 0) $skip = true;
}
// special case: rockpagebuilder block
if ($file === $paths->siteModules . "RockPageBuilder/Block.php") {
// return the block view file instead of the block controller
return $step['args'][0];
} elseif (
$file === $paths->siteModules . "RockFrontend/RockFrontend.module.php"
and count($step['args'])
) {
$f = $step['args'][0];
// in case of alfredH args(0) is the block object
// in this case we continue and return the next entry
if (!is_string($f)) continue;
return $f;
}
// try next entry or return file
if ($skip === true) continue;
else return $file;
}
}
/*
* Get translated key by string
* @return string
*/
public function getTranslation($key)
{
if (array_key_exists($key, $this->translations)) return $this->translations[$key];
return '';
}
/**
* Get uikit versions from github
*/
public function getUikitVersions()
{
return $this->wire->cache->get(self::cache, 60 * 5, function () {
$http = new WireHttp();
$json = $http->get('https://api.github.com/repos/uikit/uikit/git/refs/tags');
$refs = json_decode($json);
$versions = [];
foreach ($refs as $ref) {
$version = str_replace("refs/tags/", "", $ref->ref);
$v = $version;
if (strpos($version, "v.") === 0) continue;
if (strpos($version, "v") !== 0) continue;
$versions[$v] = $version;
}
uasort($versions, "version_compare");
return array_reverse($versions);
});
}
/**
* Hide layout field for non-superusers
* @return void
*/
public function hideLayoutField(HookEvent $event)
{
if ($this->wire->user->isSuperuser()) return;
$form = $event->return;
$form->remove(self::field_layout);
}
/**
* Return a latte HTML object that doesn't need to be |noescaped
* @return Html
*/
public static function html($str)
{
// we try to return a latte html object
// If we are not calling that from within a latte file
// the html object will not be available. This can be the case in Seo tags.
// To make sure it returns something we catch erros and return the plain
// string instead. That means if called from outside a latte file it will
// still return the HTML.
try {
require_once __DIR__ . "/vendor/autoload.php";
return new Html($str);
} catch (\Throwable $th) {
return $str;
}
}
/**
* Render icon link
* @return string
*/
public function iconLink($icon, $href, $options = [])
{
$opt = $this->wire(new WireData());
/** @var WireData $opt */
$opt->setArray([
'class' => 'alfred-icon pw-modal',
'wrapClass' => '',
'attrs' => 'data-autoclose data-reload data-barba-prevent
data-buttons="button.ui-button[type=submit]"',
'title' => false,