-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathRockFrontend.module.php
3980 lines (3506 loc) · 123 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 ExposeFunctionsExtension;
use HumanDates;
use Latte\Engine;
use Latte\Runtime\Html;
use LogicException;
use MatthiasMullie\Minify\Exceptions\IOException;
use ProcessWire\Paths as ProcessWirePaths;
use RockFrontend\Asset;
use RockFrontend\LiveReload;
use RockFrontend\Manifest;
use RockFrontend\Paths;
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;
use Tracy\Debugger;
use Tracy\Dumper;
use Wa72\HtmlPageDom\HtmlPageCrawler;
function rockfrontend(): RockFrontend
{
return wire()->modules->get('RockFrontend');
}
// load the fieldmethod trait here,
// otherwise it throws an error when used in DefaultPage
require_once __DIR__ . '/classes/FieldMethod.php';
/**
* @author Bernhard Baumrock, 05.01.2022
* @license MIT
* @link https://www.baumrock.com
*
* @method string render($filename, array $vars = array(), array $options = array())
* @method string view(string $file, array|Page $vars = [], Page $page = null)
*/
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 layoutFile = '_main.latte';
const ajax_noaccess = "ajax-noaccess";
const ajax_rendererror = "ajax-render-error";
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";
const field_images = self::prefix . "images";
const field_less = self::prefix . "less";
private $addMarkup;
/**
* Property that is true for ajax requests.
* Compared to $config->ajax this will also account for HTMX etc.
* @var false
*/
public $ajax = false;
private $ajaxFolders = [];
/** @var WireData */
public $alfredCache;
public $autoloadScripts;
public $autoloadStyles;
private $contenttype = "text/html";
public $createManifest = false;
/** @var WireArray $folders */
public $folders;
public $home;
/** @var bool */
public $hasAlfred = false;
public $isLiveReload = false;
/** @var array */
protected $js = [];
public $langMaps;
/** @var Engine */
private $latte;
/** @var Engine */
private $latteWithLayout;
public $layoutFile = self::layoutFile;
/** @var WireArray $layoutFolders */
public $layoutFolders;
private $liveReload;
/** @var Manifest */
protected $manifest;
/** @var bool */
public $noAssets = false;
public $noLayoutFile;
private $onceKeys = [];
/** @var string */
public $path;
private $paths;
/** @var WireData */
public $postCSS;
/**
* REM base value (16px)
*/
public $remBase;
private $scripts;
/** @var Seo */
public $seo;
private $sitemapCallback;
private $sitemapOptions;
private $styles;
/** @var array */
private $translations = [];
/** @var array */
private $viewfolders = [];
public function __construct()
{
$this->folders = $this->wire(new WireArray());
$this->addLiveReloadWatch();
}
public function init()
{
$config = wire()->config;
$this->path = wire()->config->paths($this);
$this->home = wire()->pages->get(1);
// load composer autoloader as early as possible
// this is so that anyone can create custom latte extensions
// without having to require the autoloader in their extension
require_once $this->path . "vendor/autoload.php";
wire()->classLoader->addNamespace("RockFrontend", __DIR__ . "/classes");
// if settings are set in config.php we make sure to use these settings
if ($config->livereloadBackend !== null) {
$this->livereloadBackend = $config->livereloadBackend;
}
if (!is_array($this->features)) $this->features = [];
// make $rockfrontend and $home variable available in template files
$this->wire('rockfrontend', $this);
$this->wire('home', $this->home);
$this->autoloadScripts = new WireArray();
$this->autoloadStyles = new WireArray();
$this->alfredCache = $this->wire(new WireData());
// set ajax flag
$htmx = isset($_SERVER['HTTP_HX_REQUEST']) && $_SERVER['HTTP_HX_REQUEST'];
$this->ajax = $this->wire->config->ajax || $htmx;
// JS defaults
// set the remBase either from config setting or use 16 as fallback
$this->remBase = $this->remBase ?: 16;
$this->initPostCSS();
// if in DDEV we set a js property accordingly
// if not we set nothing, so no markup will be on the frontend
// see https://processwire.com/talk/topic/27417-rockfrontend-%F0%9F%9A%80%F0%9F%9A%80-the-powerful-toolbox-for-processwire-frontend-development/?do=findComment&comment=240837
if ($this->isDDEV()) $this->js('isDDEV', true);
// watch this file and run "migrate" on change or refresh
if ($rm = $this->rm()) {
$rm->watch($this, 0.01);
$rm->minify(__DIR__ . '/RockFrontend.js');
}
// setup folders that are scanned for files
$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);
// add ajax folders
// you can add custom endpoints in 3rd party modules in the same way
// see RockCommerce for an example
$this->addAjaxFolder(
'ajax',
$this->wire->config->paths->templates . 'ajax'
);
// Alfred
require_once __DIR__ . "/Functions.php";
$this->createPermission(
self::permission_alfred,
"Is allowed to use ALFRED frontend editing"
);
$this->lessToCss($this->path . "Alfred.less");
// hooks
wire()->addHookAfter("ProcessPageEdit::buildForm", $this, "hideLayoutField");
wire()->addHook(self::tagsUrl, $this, "layoutSuggestions");
wire()->addHookAfter("Modules::refresh", $this, "refreshModules");
wire()->addHookBefore("TemplateFile::render", $this, "autoPrepend");
wire()->addHookAfter("InputfieldForm::processInput", $this, "createWebfontsFile");
wire()->addHookBefore("Inputfield::render", $this, "addFooterlinksNote");
wire()->addHookAfter("Page::changed", $this, "resetCustomLess");
wire()->addHookBefore("Page::render", $this, "createCustomLess");
wire()->addHookMethod("Page::otherLangUrl", $this, "otherLangUrl");
wire()->addHookAfter("Modules::refresh", $this, "livereloadResetCache");
wire()->addHookAfter("Page::render", $this, "livereloadAddMarkup");
wire()->addHookAfter("Page::render", $this, "hookAddMarkup");
// LiveReload on Tracy Error Page
// See https://processwire.com/talk/topic/29910-how-to-inject-custom-markup-into-tracys-error-pages/#comment-240601
if ($this->wire->modules->isInstalled('TracyDebugger')) {
if ($this->addLiveReload()) {
$blueScreen = \Tracy\Debugger::getBlueScreen();
$blueScreen->addPanel(function () {
return ['tab' => 'RFE Panel', 'panel' => $this->liveReloadMarkup()];
});
}
}
// others
$this->checkHealth();
// development helpers by rockmigrations
if ($this->wire->modules->isInstalled('RockMigrations')) {
try {
$rm = rockmigrations();
$rm->minify(__DIR__ . "/Alfred.js");
} catch (\Throwable $th) {
$this->warning("rockmigrations() not available - please update RockMigrations!");
}
}
}
public function ready()
{
$this->ajaxAddEndpoints();
$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;
// early exits
if (!strpos($html, "</body>")) return;
if (!strpos($html, "</head>")) return;
$this->addRockFrontendJS();
$html = $this->addAlfredMarkup($html);
try {
$this->addTopBar($html);
} catch (\Throwable $th) {
$this->log($th->getMessage());
}
$this->injectJavascriptSettings($html);
$this->injectAssets($html);
$event->return = $html;
},
// other modules also hooking to page::render can define load order
// via hook priority, for example RockCommerce uses 200 to make sure
// all RockCommerce releated stuff is loaded after default RF assets
['priority' => 100]
);
}
private function addAlfredMarkup(string $html, $skipAssets = false): string
{
if (!$this->loadAlfred()) return $html;
if (!$skipAssets) {
$this->js("rootUrl", $this->wire->config->urls->root);
$this->js("defaultVspaceScale", number_format(self::defaultVspaceScale, 2, ".", ""));
$this->scripts('rockfrontend')->add(__DIR__ . "/Alfred.min.js", "defer");
$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);
return $html;
}
/**
* Add a folder as ajax endpoint (without trailing slash!)
*
* Usage:
* rockfrontend()->addAjaxFolder(
* '/rockcommerce/',
* __DIR__ . '/ajax/',
* );
*
* This will add all .php files as ajax-endpoints. It also supports nested
* folders, for example:
*
* /cart/add.php
* /cart/reset.php
*
* rockfrontend()->addAjaxFolder(
* '/rockcommerce/',
* __DIR__ . '/ajax/',
* );
* --> /rockcommerce/cart/add
* --> /rockcommerce/cart/reset
*
* @param string $url
* @param string $folder
* @return void
*/
public function addAjaxFolder(
string $url,
string $folder,
): void {
$url = '/' . trim($url, '/') . '/';
$folder = $this->paths()->toPath($folder);
$this->ajaxFolders[$url] = $folder;
}
/**
* This method makes it possible to add a custom InputfieldWrapper to a
* page edit form in the backend. You can for example easily place two fields
* side-by-side using flexbox.
*
* Usage:
* rockfrontend()->addPageEditWrapper(
* templateName: 'your-template',
* renderFile: '/path/to/markup.latte',
* );
*/
public function addPageEditWrapper(
string $templateName,
string $renderFile,
): void {
// do everything only on buildForm
wire()->addHookAfter(
'ProcessPageEdit::buildForm',
function ($e) use ($templateName, $renderFile) {
if ($e->process->getPage()->template != $templateName) return;
$markup = $this->render($renderFile);
if (!$markup) return;
// get array of field:myfield tags
$fields = [];
preg_match_all('/field:([a-zA-Z0-9_]+)/', $markup, $matches);
if (!count($matches) === 2) return;
$fields = $matches[1];
if (!count($fields)) return;
/** @var InputfieldForm $form */
$form = $e->return;
// add wrapper that holds the new markup
$f = new InputfieldWrapper();
$f->addHookBefore(
'render',
function ($e) use ($markup) {
$e->return = $markup;
$e->replace = true;
}
);
$lastField = $fields[count($fields) - 1];
$existing = $form->get($lastField);
if (!$existing) return;
$form->insertAfter($f, $existing);
// manipulate the form html via dom tools
$form->addHookAfter(
'render',
function ($e) use ($fields) {
$html = $e->return;
$dom = $this->dom($html);
$replace = [];
foreach ($fields as $i => $f) {
$li = $dom->filter("#wrap_Inputfield_$f")->outerHtml();
$replace["field:$f"] = "
<style>
.rf-pageeditwrapper { padding: 0; margin: 0; height: 100%; }
.rf-pageeditwrapper > li { height: 100%; }
</style>
<ul class='rf-pageeditwrapper'>$li</ul>
";
$dom->filter("#wrap_Inputfield_$f")->remove();
}
$html = str_replace(
array_keys($replace),
array_values($replace),
$dom->outerHtml()
);
$e->return = $html;
}
);
}
);
}
private function addRockFrontendJS(): void
{
if (!$this->isEnabled('RockFrontend.js')) return;
$this->scripts('rockfrontend')->add(__DIR__ . '/RockFrontend.min.js', 'defer');
}
public function ___addAlfredStyles()
{
$this->styles('rockfrontend')->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).";
}
public function ___addLiveReload(): bool
{
$config = $this->wire->config;
if (!$config->livereload) return false;
if ($config->rockformsPreserveSuccess) return false;
if ($config->ajax) return false;
if ($config->external) return false;
return true;
}
private function addLiveReloadWatch(): void
{
if (!$this->wire->config->livereload) 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();
$this->liveReload = $live;
$event->object->sessionAllow = false;
$this->isLiveReload = true;
$live->watch($_GET[self::getParam]);
});
}
/**
* 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 ($page->template == 'form-builder') return;
if ($this->wire->input->get('rfpreview')) return;
if ($this->wire->config->hideTopBar) return;
/** @var RockMigrations $rm */
$less = __DIR__ . "/topbar/topbar.less";
if ($this->wire->modules->isInstalled("RockMigrations")) {
/** @var RockMigrations $rm */
$rm = $this->wire->modules->get('RockMigrations');
$rm->saveCSS($less, minify: true);
}
$css = $this->toUrl(__DIR__ . "/topbar/topbar.min.css", true);
$style = "<link rel='stylesheet' href='$css'>";
$html = str_replace("</head", "$style</head", $html);
$topbar = $this->wire->files->render(__DIR__ . "/topbar/topbar.php", [
'rf' => $this,
'logourl' => $this->toUrl(__DIR__ . "/RockFrontend.svg", true),
'z' => is_int($this->topbarz) ? $this->topbarz : 999,
]);
$html = str_replace("</body", "$topbar</body", $html);
}
/**
* Adjust brightness of a hex value
* See https://stackoverflow.com/a/54393956 for details.
* It might not be 100% accurate but good enough for my usecases :)
*
* @param mixed $hexCode
* @param mixed $adjustPercent
* @return string
*/
private function adjustBrightness($hexCode, $adjustPercent)
{
$hexCode = ltrim($hexCode, '#');
if (strlen($hexCode) == 3) {
$hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
}
$hexCode = array_map('hexdec', str_split($hexCode, 2));
foreach ($hexCode as &$color) {
$adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
$adjustAmount = ceil($adjustableLimit * $adjustPercent);
$color = str_pad(dechex($color + $adjustAmount), 2, '0', STR_PAD_LEFT);
}
return '#' . implode($hexCode);
}
/**
* Add hooks for all ajax endpoints
*/
protected function ajaxAddEndpoints(): void
{
foreach ($this->ajaxEndpoints() as $url => $file) {
wire()->addHook(
$url,
function (HookEvent $event) use ($file, $url) {
$isGET = $this->wire->input->requestMethod() === 'GET';
// ajax requests always return the public endpoint
if ($this->ajax || !$isGET) {
return $this->ajaxPublic($file);
}
// non-ajax request show the debug screen for superusers
if (wire()->user->isSuperuser()) {
return $this->ajaxDebug($file, $url);
}
// guest and no ajax: no access!
if (wire()->modules->isInstalled('TracyDebugger')) {
Debugger::$showBar = false;
}
http_response_code(403);
return "Access Denied";
}
);
}
}
/**
* Given a base url like /ajax/foo returns the subfolder-safe url like
* /subfolder/ajax/foo ready to be used for get/post requests
*
* @param mixed $base
* @return string
*/
public function ajaxBaseToUrl(string $base): string
{
return $this->wire->pages->get(1)->url . ltrim($base, '/');
}
private function ajaxDebug($file, $url): string
{
// dont catch errors when debugging
$raw = $this->ajaxResponse($file);
$response = Dumper::toHtml($raw);
// generate textarea content
$textarea = '';
foreach ($this->ajaxVars()->getArray() as $key => $value) {
$textarea .= "$key: $value\n";
}
// render html
$markup = $this->render(__DIR__ . "/stubs/ajax-debug.latte", [
'endpoint' => $file,
'ajaxUrl' => $this->ajaxBaseToUrl($url),
'response' => $response,
'formatted' => $this->ajaxFormatted($raw, $file),
'contenttype' => $this->contenttype, // must be after formatted!
'input' => Dumper::toHtml($this->ajaxVars()->getArray()),
'textarea' => $textarea,
]);
return $markup;
}
/**
* Get array of all added ajax endpoints
* Array is in format [base-url => filepath]
*
* ATTENTION: The base-url is the endpoint url without the subfolder prefix!
*
* Example: /ajax/foo will be the base-url, but /subfolder/ajax/foo will be
* the endpoint used for GET/POST requests.
*
* You can get the subfolder-safe endpoint via ->ajaxBaseToUrl($baseurl)
*
* @return array
*/
private function ajaxEndpoints(): array
{
// scan for these extensions
// later listed extensions have priority
$extensions = [
'php',
'latte',
];
// attach hook for every found endpoint
$arr = [];
foreach ($extensions as $ext) {
$opt = ['extensions' => [$ext]];
foreach ($this->ajaxFolders as $baseurl => $folder) {
// add all endpoints from this folder to RockFrontend
$endpoints = $this->wire->files->find($folder, $opt);
foreach ($endpoints as $file) {
// get url after folder
// we can't use basename because we support nested folders/endpoints
$suffix = substr($file, strlen($folder), - (strlen($ext) + 1));
$url = $baseurl . ltrim($suffix, '/');
if (array_key_exists($url, $arr)) continue;
$arr[$url] = $file;
}
}
}
return $arr;
}
private function ajaxFormatted($raw, $endpoint): string
{
$extension = pathinfo($endpoint, PATHINFO_EXTENSION);
if ($extension === "latte") {
$response = $this->render($endpoint);
} else $response = $raw;
// is response already a string?
if (is_string($response)) {
$exceptions = [
self::ajax_noaccess => "No access",
self::ajax_rendererror => "Error rendering endpoint - see logs for details.",
];
if (array_key_exists($response, $exceptions)) {
throw new WireException($exceptions[$response]);
}
// no exception - return string
return $response;
}
// array --> json
if (is_array($response)) {
$this->contenttype = "application/json";
return json_encode($response, JSON_PRETTY_PRINT);
}
// still no string, try to cast it to string
try {
$response = (string)$response;
} catch (\Throwable $th) {
throw new WireException("Invalid return type");
}
return $response;
}
private function ajaxPublic($endpoint): string
{
// return function to keep code DRY
$return = function ($endpoint) {
$raw = $this->ajaxResponse($endpoint);
$response = $this->ajaxFormatted($raw, $endpoint);
header('Content-Type: ' . $this->contenttype);
return $response;
};
// for debugging we don't catch errors
if (wire()->config->debug) return $return($endpoint);
// public endpoints return a generic error message
// to avoid leaking information
try {
return $return($endpoint);
} catch (\Throwable $th) {
$this->log($th->getMessage());
return "Error in AJAX endpoint - error has been logged";
}
}
private function ajaxResponse($endpoint)
{
// for superusers we don't catch errors
if ($this->wire->user->isSuperuser()) {
return $this->ajaxResult($endpoint);
}
// non superusers - use try catch
try {
return $this->ajaxResult($endpoint);
} catch (\Throwable $th) {
$this->log($th->getMessage());
return self::ajax_rendererror;
}
}
private function ajaxResult($endpoint)
{
$input = $this->ajaxVars();
$result = $this->wire->files->render($endpoint, ['input' => $input]);
if (is_string($result)) {
return $this->addAlfredMarkup(
$result,
true
);
} else return $result;
}
public function ajaxUrl($base): string
{
return $this->wire->pages->get(1)->url . "ajax/$base";
}
/**
* Get all input variables from GET and POST
* POST has precedence over GET
*/
private function ajaxVars(): WireInputData
{
$vars = new WireInputData();
// grab GET data
$vars->setArray(wire()->input->get->getArray());
// grab POST data
$vars->setArray(wire()->input->post->getArray());
// grab raw input (for JSON or other content types)
$raw_input = file_get_contents('php://input');
if (!empty($raw_input)) {
$json_data = json_decode($raw_input, true);
if (is_array($json_data)) {
// It's valid JSON
$vars->setArray($json_data);
} else {
// It's not JSON, try parsing as form data
parse_str($raw_input, $parsed_input);
if (is_array($parsed_input)) {
$vars->setArray($parsed_input);
}
}
}
// return result
return $vars;
}
/**
* 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;
// check if frontend editing is installed
if (!$this->wire->modules->isInstalled("PageFrontEdit")) {
$this->addMarkup .= "<script>alert('Please install PageFrontEdit to use ALFRED')</script>";
}
// 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 ($this->wire->modules->isInstalled('RockPageBuilder')) {
/** @var RockPageBuilder $rpb */
$rpb = $this->wire->modules->get("RockPageBuilder");
$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,
]);
// entity encode alfred string
// this is to avoid "invalid json" errors when using labels with apostrophes
// like "Don't miss any updates"
$str = $this->wire->sanitizer->entities1($str);
// 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;
}