Repository navigation
Expand file tree
/
Copy pathconfig.php
More file actions
974 lines (969 loc) · 43.9 KB
/
Copy pathconfig.php
File metadata and controls
974 lines (969 loc) · 43.9 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
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
<?php
/**
* This includes a fallback mechanism for deciphering where the root of the site
* is located. If placed in a HAXcms deployment (assumed multi-site) then
* it first looks for this location 2 levels below the site.
*
* HAXiam (SaaS HAXcms) also has this structure and will discover where it is
* and bootstrap appropriately. To pull in all local (HAXcms) and global (HAXiam)
* configuration so that the user is appropriately delivered the site AND potential
* authoring experience via wiring required to do so in AppStore specification.
*
* In the event we are on a PHP based host that DOES NOT have HAXcms we are
* running as a "single site" context. In this mode the HAXsite needs to be able to
* bootstrap appropriately but with a dramatically trimmed down version of the
* platform as they cannot log into just a single site for authoring. This
* dection file accounts for HAXiam, HAXcms, Docker methods as well as the
* provided single file fall back to operate stand alone.
*
* When not in "single site" context, HAXcms/HAXiam will supply the HAXSiteConfig
* global variables and classed object. When in Single Site, this classed
* object can be found below. Modification of this is not recommended however,
* everything required to get a HAXsite to bootstrap is included in this file
* and can be modified in "single site" context to do whatever you desire to
* customize the site's output along with modification of index.php for where
* things are rendered.
*/
$bootstrapPath = "/../..";
// see if we are in docker, tweak path
if (file_exists("/.dockerenv") && __DIR__ == "/var/www/html") {
$GLOBALS["HAXcmsInDocker"] = true;
$bootstrapPath = "";
}
// look for a local / larger copy of HAXcms in multi-site mode
if (file_exists(__DIR__ . $bootstrapPath . '/system/backend/php/bootstrapHAX.php')) {
include_once __DIR__ . $bootstrapPath . '/system/backend/php/bootstrapHAX.php';
include_once __DIR__ . $bootstrapPath . '/system/backend/php/lib/HAXSiteConfig.php';
include_once $GLOBALS['HAXCMS']->configDirectory . '/config.php';
$site = $HAXCMS->loadSite(basename(__DIR__));
$page = $site->loadNodeByLocation();
$color = 'var(' . $site->manifest->metadata->theme->variables->cssVariable . ', #FF2222)';
$HAXSiteConfig = new HAXSiteConfig($site);
}
// local slim config loader off of site.json
// Without a global HAXcms instance this implies the above did not autoload one
// and that we are operating in HAXsite "single site" context and must supply
// all our configuration below to power the page.
// this only runs if broken off from a larger deploy that hosts a PHP env
if (!isset($GLOBALS['HAXCMS'])) {
/**
* A slim version of HAXcms that is just config driven off site.json
*/
define("HAXCMS_FALLBACK_HEX", "#3f51b5");
class HAXSiteConfig {
public function __construct($basePath = NULL, $location = "./site.json") {
$this->basePath = $basePath;
if ($this->basePath === NULL) {
$this->basePath = $this->request_uri();
}
$this->cdn = './';
$this->developerMode = FALSE;
$this->developerModeAdminOnly = FALSE;
$this->sitesDirectory = 'sites';
$this->color = "blue";
$this->manifest = new stdClass();
$this->manifest->items = array();
// ensure we have site.json to load config from
if (file_exists($location)) {
$this->file = $location;
$fileData = json_decode(file_get_contents($location));
$vars = get_object_vars($fileData);
foreach ($vars as $key => $var) {
if ($key != 'items') {
$this->manifest->{$key} = $var;
}
}
// also ensures data matches only what is supported
if (isset($vars['items'])) {
foreach ($vars['items'] as $key => $item) {
$newItem = new stdClass();
$newItem->id = $item->id;
$newItem->indent = $item->indent;
$newItem->location = $item->location;
$newItem->slug = (isset($item->slug) ? $item->slug : str_replace('pages/', '', str_replace('/index.html','', $item->location)));
$newItem->order = $item->order;
$newItem->parent = $item->parent;
$newItem->title = $item->title;
$newItem->description = $item->description;
// metadata can be anything so whatever
$newItem->metadata = $item->metadata;
$this->manifest->items[$key] = $newItem;
}
}
$this->page = $this->loadNodeByLocation();
if (isset($this->manifest->metadata->theme->variables->cssVariable)) {
$this->color = 'var(' . $this->manifest->metadata->theme->variables->cssVariable . ', #FF2222)';
}
$this->name = $this->manifest->metadata->site->name;
}
}
/**
* Return the base tag accurately which helps with the PWA / SW side of things
* @return string HTML blob for hte <base> tag
*/
public function getBaseTag() {
// Security (SEC-09): escape basePath (derived from REQUEST_URI) so a
// crafted URL cannot break out of the href attribute (reflected XSS).
return '<base href="' . htmlspecialchars($this->basePath, ENT_QUOTES, 'UTF-8') . '" />';
}
public function cacheBusterHash() {
return '?';
}
/**
* Return attributes for the site
* @todo make this mirror the drupal get attributes method
* @return string eventually, array of data keyed by type of information
*/
public function getSitePageAttributes() {
return 'vocab="http://schema.org/" prefix="oer:http://oerschema.org cc:http://creativecommons.org/ns dc:http://purl.org/dc/terms/"';
}
/**
* Language of the site
*/
public function getLanguage() {
if (isset($this->manifest->metadata->site->settings->lang) && $this->manifest->metadata->site->settings->lang != "" && $this->manifest->metadata->site->settings->lang != null) {
return $this->manifest->metadata->site->settings->lang;
}
return "en-US";
}
/**
* Return the active URI if it exists
*/
public function getURI() {
if (isset($_SERVER['SCRIPT_URI'])) {
return $_SERVER['SCRIPT_URI'];
}
}
/**
* Return the active domain if it exists
*/
public function getDomain() {
if (isset($_SERVER['SERVER_NAME'])) {
return 'https://' . $_SERVER['SERVER_NAME'];
}
}
/**
* Return accurate, rendered site metadata
* @return string an html chunk of tags for the head section
* @todo move this to a render function / section / engine
*/
public function getSiteMetadata($page = NULL, $domain = NULL, $cdn = '') {
$preloadTags = array();
$content = $this->getPageContent($page);
preg_match_all("/<(?:\"-[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>/", $content, $matches);
foreach ($matches[0] as $match) {
if (strpos($match, '-')) {
$tag = str_replace('>', '', str_replace('</', '', $match));
$preloadTags[$tag] = $tag;
}
}
// domain's need to inject their own full path for OG metadata (which is edge case)
// most of the time this is the actual usecase so use the active path
if (is_null($domain)) {
$domain = $this->getURI();
}
// support preconnecting CDNs, sets us up for dynamic CDN switching too
$preconnect = '';
$base = './';
if ($cdn == '' && $this->cdn != './') {
$cdn = $this->cdn;
}
if ($cdn != '') {
// preconnect for faster DNS lookup
$preconnect = '<link rel="preconnect" crossorigin href="' . $cdn . '">';
// base is preload for the calls below
$base = $cdn;
}
$contentPreload = '';
$wcMap = $this->getWCRegistryJson($base);
foreach ($preloadTags as $tag) {
// means the tag is known in our registry
if (isset($wcMap->{$tag})) {
$contentPreload .= '
<link rel="preload" href="' . $base . 'build/es6/node_modules/' . $wcMap->{$tag} . '" as="script" crossorigin="anonymous" />
<link rel="modulepreload" href="' . $base . 'build/es6/node_modules/' . $wcMap->{$tag} . '" />';
}
}
$title = htmlspecialchars($page->title, ENT_QUOTES, 'UTF-8');
$siteTitle = htmlspecialchars($this->manifest->title, ENT_QUOTES, 'UTF-8') . ' | ' . htmlspecialchars($page->title, ENT_QUOTES, 'UTF-8');
$description = htmlspecialchars($page->description, ENT_QUOTES, 'UTF-8');;
$hexCode = HAXCMS_FALLBACK_HEX;
$themePreload = '';
// sanity check, then preload the theme
if (isset($this->manifest->metadata->theme->path)) {
$themePreload = ' <link rel="preload" href="' . $base . 'build/es6/node_modules/' . str_replace("@lrnwebcomponents/", "@haxtheweb/", $this->manifest->metadata->theme->path) . '" as="script" crossorigin="anonymous" />
<link rel="modulepreload" href="' . $base . 'build/es6/node_modules/' . str_replace("@lrnwebcomponents/", "@haxtheweb/", $this->manifest->metadata->theme->path) . '" />';
}
if ($description == '') {
$description = htmlspecialchars($this->manifest->description, ENT_QUOTES, 'UTF-8');
}
if ($title == '' || $title == 'New item') {
$title = htmlspecialchars($this->manifest->title, ENT_QUOTES, 'UTF-8');
$siteTitle = $title;
}
if (isset($this->manifest->metadata->theme->variables->hexCode)) {
$hexCode = htmlspecialchars($this->manifest->metadata->theme->variables->hexCode, ENT_QUOTES, 'UTF-8');
}
// if we have a privacy flag, then tell robots not to index this were it to be found
// which in HAXiam this isn't possible
if (isset($this->manifest->metadata->site->settings->private) && $this->manifest->metadata->site->settings->private) {
$robots = '<meta name="robots" content="none" />';
}
else {
$robots = '<meta name="robots" content="index, follow" />';
}
// canonical flag, if set we use the domain field
if (isset($this->manifest->metadata->site->settings->canonical) && $this->manifest->metadata->site->settings->canonical) {
if (isset($this->manifest->metadata->site->domain) && $this->manifest->metadata->site->domain != '') {
$canonical = ' <link name="canonical" href="' . filter_var($this->manifest->metadata->site->domain . '/' . $page->slug, FILTER_SANITIZE_URL) . '" />' . "\n";
}
else {
$canonical = ' <link name="canonical" href="' . filter_var($domain, FILTER_SANITIZE_URL). '" />' . "\n";
}
}
else {
$canonical = '';
}
$prevResource = '';
$nextResource = '';
// if we have a place in the array bc it's a page, then we can get next / prev
if ($page->id && $this->manifest->getItemKeyById($page->id) !== FALSE) {
$currentId = $this->manifest->getItemKeyById($page->id);
if ($currentId > 0 && isset($this->manifest->items[$currentId-1]->slug)) {
$prevResource = ' <link rel="prev" href="' . $this->manifest->items[$currentId-1]->slug . '" />' . "\n";
}
if ($currentId < count($this->manifest->items)-1 && isset($this->manifest->items[$currentId+1]->slug)) {
$nextResource = ' <link rel="next" href="' . $this->manifest->items[$currentId+1]->slug . '" />' . "\n";
}
}
$metadata = '
<meta charset="utf-8">' . $preconnect . '
<link rel="preconnect" crossorigin href="https://fonts.googleapis.com">
<link rel="preconnect" crossorigin href="https://cdnjs.cloudflare.com">
<link rel="preload" href="' . $base . 'build.js" as="script" />
<link rel="preload" href="' . $base . 'build-haxcms.js" as="script" />
<link rel="preload" href="' . $base . 'wc-registry.json" as="fetch" crossorigin="anonymous" fetchpriority="high" />
<link rel="preload" href="' . $base . 'build/es6/node_modules/@haxtheweb/dynamic-import-registry/dynamic-import-registry.js" as="script" crossorigin="anonymous" />
<link rel="modulepreload" href="' . $base . 'build/es6/node_modules/@haxtheweb/dynamic-import-registry/dynamic-import-registry.js" />
<link rel="preload" href="' . $base . 'build/es6/node_modules/@haxtheweb/wc-autoload/wc-autoload.js" as="script" crossorigin="anonymous" />
<link rel="modulepreload" href="' . $base . 'build/es6/node_modules/@haxtheweb/wc-autoload/wc-autoload.js" />
' . $themePreload . $contentPreload . '
<link rel="preload" href="' . $base . 'build/es6/node_modules/@haxtheweb/haxcms-elements/lib/base.css" as="style" />
<meta name="generator" content="HAXcms" />
' . $canonical . $prevResource . $nextResource . ' <link rel="manifest" href="manifest.json" />
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes" />
<title>' . $siteTitle . '</title>
<link rel="icon" href="' . $this->getLogoSize('16', '16') . '" />
<meta name="theme-color" content="' . $hexCode . '" />
' . $robots . '
<meta name="mobile-web-app-capable" content="yes" />
<meta name="application-name" content="' . $title . '" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="' . $title . '" />
<link rel="apple-touch-icon" sizes="48x48" href="' . $this->getLogoSize('48', '48') . '" />
<link rel="apple-touch-icon" sizes="72x72" href="' . $this->getLogoSize('72', '72') . '" />
<link rel="apple-touch-icon" sizes="96x96" href="' . $this->getLogoSize('96', '96') . '" />
<link rel="apple-touch-icon" sizes="144x144" href="' . $this->getLogoSize('144', '144') . '" />
<link rel="apple-touch-icon" sizes="192x192" href="' . $this->getLogoSize('192', '192') . '" />
<meta name="msapplication-TileImage" content="' . $this->getLogoSize('144', '144') . '" />
<meta name="msapplication-TileColor" content="' . $hexCode . '" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="description" content="' . $description . '" />
<meta name="og:sitename" property="og:sitename" content="' . htmlspecialchars($this->manifest->title, ENT_QUOTES, 'UTF-8') . '" />
<meta name="og:title" property="og:title" content="' . $title . '" />
<meta name="og:type" property="og:type" content="article" />
<meta name="og:url" property="og:url" content="' . filter_var($domain, FILTER_SANITIZE_URL) . '" />
<meta name="og:description" property="og:description" content="' . $description . '" />
<meta name="og:image" property="og:image" content="' . $this->getSocialShareImage($page) . '" />
<meta name="twitter:card" property="twitter:card" content="summary_large_image" />
<meta name="twitter:site" property="twitter:site" content="' . filter_var($domain, FILTER_SANITIZE_URL) . '" />
<meta name="twitter:title" property="twitter:title" content="' . $title . '" />
<meta name="twitter:description" property="twitter:description" content="' . $description . '" />
<meta name="twitter:image" property="twitter:image" content="' . $this->getSocialShareImage($page) . '" />';
$inLanguage = $this->getLanguage();
$siteUrlForStructuredData = filter_var($domain, FILTER_SANITIZE_URL);
if (isset($this->manifest->metadata->site->domain) && $this->manifest->metadata->site->domain != '') {
$siteUrlForStructuredData = filter_var($this->manifest->metadata->site->domain, FILTER_SANITIZE_URL);
}
$pageUrlForStructuredData = filter_var($domain, FILTER_SANITIZE_URL);
if (
isset($this->manifest->metadata->site->settings->canonical) &&
$this->manifest->metadata->site->settings->canonical &&
isset($this->manifest->metadata->site->domain) &&
$this->manifest->metadata->site->domain != '' &&
isset($page->slug) &&
$page->slug != ''
) {
$pageUrlForStructuredData = filter_var(
rtrim((string) $this->manifest->metadata->site->domain, '/') . '/' . ltrim((string) $page->slug, '/'),
FILTER_SANITIZE_URL
);
}
if ($siteUrlForStructuredData == '') {
$siteUrlForStructuredData = $pageUrlForStructuredData;
}
if ($pageUrlForStructuredData == '') {
$pageUrlForStructuredData = $siteUrlForStructuredData;
}
$joinStructuredDataUrl = function ($baseValue = '', $segmentValue = '') {
$normalizedBase = (string) $baseValue;
$normalizedSegment = (string) $segmentValue;
if ($normalizedSegment == '') {
return $normalizedBase;
}
if (preg_match('/^https?:\\/\\//i', $normalizedSegment)) {
return $normalizedSegment;
}
if ($normalizedBase == '') {
return $normalizedSegment;
}
return rtrim($normalizedBase, '/') . '/' . ltrim($normalizedSegment, '/');
};
$toAbsoluteStructuredDataUrl = function ($value = '') use ($siteUrlForStructuredData, $joinStructuredDataUrl) {
$sanitizedValue = filter_var((string) $value, FILTER_SANITIZE_URL);
if ($sanitizedValue == '') {
return '';
}
if (preg_match('/^https?:\\/\\//i', $sanitizedValue)) {
return $sanitizedValue;
}
if ($siteUrlForStructuredData != '') {
return filter_var($joinStructuredDataUrl($siteUrlForStructuredData, $sanitizedValue), FILTER_SANITIZE_URL);
}
return $sanitizedValue;
};
$socialImageForStructuredData = $toAbsoluteStructuredDataUrl($this->getSocialShareImage($page));
$siteLogoForStructuredData = $toAbsoluteStructuredDataUrl($this->getLogoSize('512', '512'));
$pageUpdatedISO = '';
if (isset($page->metadata->updated) && is_numeric($page->metadata->updated)) {
$updatedTimestamp = intval($page->metadata->updated);
if ($updatedTimestamp > 0) {
$pageUpdatedISO = gmdate('c', $updatedTimestamp);
}
}
$pageCreatedISO = '';
if (isset($page->metadata->created) && is_numeric($page->metadata->created)) {
$createdTimestamp = intval($page->metadata->created);
if ($createdTimestamp > 0) {
$pageCreatedISO = gmdate('c', $createdTimestamp);
}
}
$authorName = '';
if (isset($this->manifest->metadata->author->name) && trim((string) $this->manifest->metadata->author->name) != '') {
$authorName = trim((string) $this->manifest->metadata->author->name);
}
else if (isset($this->manifest->author) && is_string($this->manifest->author) && trim((string) $this->manifest->author) != '') {
$authorName = trim((string) $this->manifest->author);
}
else if (isset($this->manifest->author) && is_object($this->manifest->author) && isset($this->manifest->author->name) && trim((string) $this->manifest->author->name) != '') {
$authorName = trim((string) $this->manifest->author->name);
}
$authorEmail = '';
if (isset($this->manifest->metadata->author->email) && trim((string) $this->manifest->metadata->author->email) != '') {
$authorEmail = trim((string) $this->manifest->metadata->author->email);
}
else if (isset($this->manifest->author) && is_object($this->manifest->author) && isset($this->manifest->author->email) && trim((string) $this->manifest->author->email) != '') {
$authorEmail = trim((string) $this->manifest->author->email);
}
$authorSocialLink = '';
if (isset($this->manifest->metadata->author->socialLink) && trim((string) $this->manifest->metadata->author->socialLink) != '') {
$authorSocialLink = filter_var(trim((string) $this->manifest->metadata->author->socialLink), FILTER_SANITIZE_URL);
}
else if (isset($this->manifest->author) && is_object($this->manifest->author) && isset($this->manifest->author->socialLink) && trim((string) $this->manifest->author->socialLink) != '') {
$authorSocialLink = filter_var(trim((string) $this->manifest->author->socialLink), FILTER_SANITIZE_URL);
}
$authorImageForStructuredData = '';
if (isset($this->manifest->metadata->author->image) && trim((string) $this->manifest->metadata->author->image) != '') {
$authorImageForStructuredData = $toAbsoluteStructuredDataUrl(trim((string) $this->manifest->metadata->author->image));
}
else if (isset($this->manifest->author) && is_object($this->manifest->author) && isset($this->manifest->author->image) && trim((string) $this->manifest->author->image) != '') {
$authorImageForStructuredData = $toAbsoluteStructuredDataUrl(trim((string) $this->manifest->author->image));
}
$itemById = array();
if (isset($this->manifest->items) && is_array($this->manifest->items)) {
foreach ($this->manifest->items as $manifestItem) {
if (isset($manifestItem->id)) {
$itemById[(string) $manifestItem->id] = $manifestItem;
}
}
}
$breadcrumbTrail = array();
if (isset($page->id) && $page->id && isset($itemById[(string) $page->id])) {
$itemBuilder = $itemById[(string) $page->id];
$safetyCounter = 0;
while ($itemBuilder && $safetyCounter < 200) {
array_unshift($breadcrumbTrail, $itemBuilder);
if (!isset($itemBuilder->parent) || is_null($itemBuilder->parent) || $itemBuilder->parent === '') {
break;
}
$parentKey = (string) $itemBuilder->parent;
if (!isset($itemById[$parentKey])) {
break;
}
$itemBuilder = $itemById[$parentKey];
$safetyCounter++;
}
}
else if (isset($page->title) || isset($page->slug)) {
$breadcrumbTrail[] = $page;
}
$breadcrumbListElements = array();
$breadcrumbPosition = 1;
if ($siteUrlForStructuredData != '') {
$breadcrumbListElements[] = array(
'@type' => 'ListItem',
'position' => $breadcrumbPosition,
'name' => isset($this->manifest->title) ? (string) $this->manifest->title : 'Home',
'item' => $siteUrlForStructuredData,
);
$breadcrumbPosition++;
}
foreach ($breadcrumbTrail as $index => $breadcrumbItem) {
$breadcrumbName = '';
if (isset($breadcrumbItem->title) && trim((string) $breadcrumbItem->title) != '') {
$breadcrumbName = trim((string) $breadcrumbItem->title);
}
else if (isset($breadcrumbItem->slug) && trim((string) $breadcrumbItem->slug) != '') {
$breadcrumbName = trim((string) $breadcrumbItem->slug);
}
else {
$breadcrumbName = $title;
}
$breadcrumbUrl = '';
if (isset($breadcrumbItem->slug) && trim((string) $breadcrumbItem->slug) != '') {
$breadcrumbUrl = $toAbsoluteStructuredDataUrl($breadcrumbItem->slug);
}
if ($breadcrumbUrl == '' && $index === (count($breadcrumbTrail) - 1)) {
$breadcrumbUrl = $pageUrlForStructuredData;
}
if ($breadcrumbUrl == '') {
$breadcrumbUrl = $siteUrlForStructuredData;
}
if ($breadcrumbPosition === 2 && $siteUrlForStructuredData != '' && $breadcrumbUrl == $siteUrlForStructuredData) {
continue;
}
if ($breadcrumbUrl == '') {
continue;
}
$breadcrumbListElements[] = array(
'@type' => 'ListItem',
'position' => $breadcrumbPosition,
'name' => $breadcrumbName,
'item' => $breadcrumbUrl,
);
$breadcrumbPosition++;
}
$structuredDataBaseUrl = $siteUrlForStructuredData != '' ? $siteUrlForStructuredData : $pageUrlForStructuredData;
$siteStructuredDataId = rtrim((string) $siteUrlForStructuredData, '/') . '#website';
$pageStructuredDataId = rtrim((string) $pageUrlForStructuredData, '/') . '#webpage';
$breadcrumbStructuredDataId = rtrim((string) $pageUrlForStructuredData, '/') . '#breadcrumb';
$authorStructuredDataId = rtrim((string) $structuredDataBaseUrl, '/') . '#author';
$publisherStructuredDataId = rtrim((string) $structuredDataBaseUrl, '/') . '#publisher';
$jsonLdGraph = array();
$authorNode = null;
$publisherNode = null;
if ($authorName != '' || $authorEmail != '' || $authorSocialLink != '' || $authorImageForStructuredData != '') {
$authorNode = array(
'@type' => 'Person',
'@id' => $authorStructuredDataId,
);
if ($authorName != '') {
$authorNode['name'] = $authorName;
}
if ($authorEmail != '') {
$authorNode['email'] = $authorEmail;
}
if ($authorSocialLink != '') {
$authorNode['sameAs'] = array($authorSocialLink);
}
if ($authorImageForStructuredData != '') {
$authorNode['image'] = array(
'@type' => 'ImageObject',
'url' => $authorImageForStructuredData,
);
}
$jsonLdGraph[] = $authorNode;
}
if ($siteUrlForStructuredData != '') {
$publisherNode = array(
'@type' => 'Organization',
'@id' => $publisherStructuredDataId,
'url' => $siteUrlForStructuredData,
'name' => isset($this->manifest->title) ? (string) $this->manifest->title : $title,
);
if ($siteLogoForStructuredData != '') {
$publisherNode['logo'] = array(
'@type' => 'ImageObject',
'url' => $siteLogoForStructuredData,
);
}
if ($authorNode !== null && isset($authorNode['@id'])) {
$publisherNode['founder'] = array(
'@id' => $authorNode['@id'],
);
}
$jsonLdGraph[] = $publisherNode;
}
if ($siteUrlForStructuredData != '') {
$webSiteNode = array(
'@type' => 'WebSite',
'@id' => $siteStructuredDataId,
'url' => $siteUrlForStructuredData,
'name' => isset($this->manifest->title) ? (string) $this->manifest->title : $title,
'inLanguage' => $inLanguage,
'potentialAction' => array(
'@type' => 'SearchAction',
'target' => array(
'@type' => 'EntryPoint',
'urlTemplate' => rtrim((string) $siteUrlForStructuredData, '/') . '/x/search?search={search_term_string}',
),
'query-input' => 'required name=search_term_string',
),
);
if ($publisherNode !== null && isset($publisherNode['@id'])) {
$webSiteNode['publisher'] = array(
'@id' => $publisherNode['@id'],
);
}
if ($authorNode !== null && isset($authorNode['@id'])) {
$webSiteNode['author'] = array(
'@id' => $authorNode['@id'],
);
}
if ($siteLogoForStructuredData != '') {
$webSiteNode['image'] = array(
'@type' => 'ImageObject',
'url' => $siteLogoForStructuredData,
);
}
$jsonLdGraph[] = $webSiteNode;
}
if (count($breadcrumbListElements) > 0 && $pageUrlForStructuredData != '') {
$jsonLdGraph[] = array(
'@type' => 'BreadcrumbList',
'@id' => $breadcrumbStructuredDataId,
'itemListElement' => $breadcrumbListElements,
);
}
if ($pageUrlForStructuredData != '') {
$webPageNode = array(
'@type' => 'WebPage',
'@id' => $pageStructuredDataId,
'url' => $pageUrlForStructuredData,
'name' => $title,
'description' => $description,
'inLanguage' => $inLanguage,
);
if ($siteUrlForStructuredData != '') {
$webPageNode['isPartOf'] = array(
'@id' => $siteStructuredDataId,
);
}
if ($socialImageForStructuredData != '') {
$webPageNode['primaryImageOfPage'] = array(
'@type' => 'ImageObject',
'url' => $socialImageForStructuredData,
);
$webPageNode['image'] = $socialImageForStructuredData;
}
if ($pageCreatedISO != '') {
$webPageNode['datePublished'] = $pageCreatedISO;
}
if ($pageUpdatedISO != '') {
$webPageNode['dateModified'] = $pageUpdatedISO;
}
if ($authorNode !== null && isset($authorNode['@id'])) {
$webPageNode['author'] = array(
'@id' => $authorNode['@id'],
);
}
if ($publisherNode !== null && isset($publisherNode['@id'])) {
$webPageNode['publisher'] = array(
'@id' => $publisherNode['@id'],
);
}
if (count($breadcrumbListElements) > 0) {
$webPageNode['breadcrumb'] = array(
'@id' => $breadcrumbStructuredDataId,
);
}
if (isset($page->id) && $page->id) {
$webPageNode['identifier'] = (string) $page->id;
}
$jsonLdGraph[] = $webPageNode;
}
if (count($jsonLdGraph) > 0) {
$jsonLdData = array(
'@context' => 'https://schema.org',
'@graph' => $jsonLdGraph,
);
$jsonLdString = json_encode($jsonLdData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($jsonLdString !== FALSE) {
$jsonLdString = str_replace('<', '\\u003c', $jsonLdString);
$metadata .= "\n <script type=\"application/ld+json\">" . $jsonLdString . "</script>";
}
}
// mix in license metadata if we have it
$licenseData = $this->getLicenseData('all');
if (isset($this->manifest->license) && isset($licenseData[$this->manifest->license])) {
$metadata .= "\n" . ' <meta rel="cc:license" href="' . $licenseData[$this->manifest->license]['link'] . '" content="License: ' . $licenseData[$this->manifest->license]['name'] . '"/>' . "\n";
}
// add in twitter link if they provided one
if (isset($this->manifest->metadata->author->socialLink) && strpos($this->manifest->metadata->author->socialLink, 'https://twitter.com/') === 0) {
$metadata .= ' <meta name="twitter:creator" content="' . str_replace('https://twitter.com/', '@', $this->manifest->metadata->author->socialLink) . '" />';
}
return $metadata;
}
/**
* Generate or load the path to variations on the logo
* @var string $height height of the icon as a string
* @var string $width width of the icon as a string
* @var string $format (optional) png or jpeg format to return image as
* @return string path to the image (web visible) that was created or pulled together
*/
public function getLogoSize($height, $width, $format = "png") {
$fileName = &$this->staticCache(__FUNCTION__ . $height . $width);
if (!isset($fileName)) {
// if no logo, just bail with an easy standard one
if (!isset($this->manifest->metadata->site->logo) || (isset($this->manifest->metadata->site) && ($this->manifest->metadata->site->logo == '' || $this->manifest->metadata->site->logo == null || $this->manifest->metadata->site->logo == "null"))) {
$fileName = 'assets/icon-' . $height . 'x' . $width . '.png';
}
else {
// ensure this path exists otherwise let's create it on the fly
$path = '/';
// support for default so we compress it using same engine
if ($this->manifest->metadata->site->logo == 'assets/banner.jpg') {
$fileName = str_replace('assets/', 'files/haxcms-managed/' . $height . 'x' . $width . '-', $this->manifest->metadata->site->logo);
}
else {
$fileName = str_replace('files/', 'files/haxcms-managed/' . $height . 'x' . $width . '-', $this->manifest->metadata->site->logo);
}
// always replace this terrible name
$fileName = str_replace('.jpeg', '.jpg', $fileName);
if ($format == "jpg") {
$fileName = str_replace('.png', '.jpg', $fileName);
}
else {
$fileName = str_replace('.jpg', '.png', $fileName);
}
}
}
return $fileName;
}
/**
* License data for common open license
*/
public function getLicenseData($type = 'select') {
$list = array(
"by" => array(
'name' => "Creative Commons: Attribution",
'link' => "https://creativecommons.org/licenses/by/4.0/",
'image' => "https://i.creativecommons.org/l/by/4.0/88x31.png"
),
"by-sa" => array(
'name' => "Creative Commons: Attribution Share a like",
'link' => "https://creativecommons.org/licenses/by-sa/4.0/",
'image' => "https://i.creativecommons.org/l/by-sa/4.0/88x31.png"
),
"by-nd" => array(
'name' => "Creative Commons: Attribution No derivatives",
'link' => "https://creativecommons.org/licenses/by-nd/4.0/",
'image' => "https://i.creativecommons.org/l/by-nd/4.0/88x31.png"
),
"by-nc" => array(
'name' => "Creative Commons: Attribution non-commercial",
'link' => "https://creativecommons.org/licenses/by-nc/4.0/",
'image' => "https://i.creativecommons.org/l/by-nc/4.0/88x31.png"
),
"by-nc-sa" => array(
'name' => "Creative Commons: Attribution non-commercial share a like",
'link' => "https://creativecommons.org/licenses/by-nc-sa/4.0/",
'image' => "https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png"
),
"by-nc-nd" => array(
'name' => "Creative Commons: Attribution Non-commercial No derivatives",
'link' => "https://creativecommons.org/licenses/by-nc-nd/4.0/",
'image' => "https://i.creativecommons.org/l/by-nc-nd/4.0/88x31.png"
)
);
$data = array();
if ($type == 'select') {
foreach ($list as $key => $item) {
$data[$key] = $item['name'];
}
}
else {
$data = $list;
}
return $data;
}
/**
* Request URI resolution
*/
public function request_uri() {
if (isset($_SERVER['REQUEST_URI'])) {
$uri = $_SERVER['REQUEST_URI'];
}
else {
if (isset($_SERVER['argv'])) {
$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
}
elseif (isset($_SERVER['QUERY_STRING'])) {
$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
}
else {
$uri = $_SERVER['SCRIPT_NAME'];
}
}
$uri = '/' . ltrim($uri, '/');
return $uri;
}
/**
* Load a node based on a path
* @var $path the path to try loading based on or search for the active from address
*/
public function loadNodeByLocation($path = NULL) {
// load from the active address if we have one
if (is_null($path)) {
$opPath = str_replace($this->basePath . $this->sitesDirectory . '/' . $this->manifest->metadata->site->name . '/', '', $this->request_uri());
$path = $opPath;
}
$path .= "/index.html";
// failsafe in case someone had closing /
$path = 'pages/' . str_replace('//', '/', $path);
foreach ($this->manifest->items as $item) {
if ($item->location == $path || $item->slug == $opPath) {
return $item;
}
}
return $this->manifest->items[0];
}
/**
* Load wc-registry.json relative to the site in question
*/
public function getWCRegistryJson($base = './') {
$wcMap = &$this->staticCache(__FUNCTION__ . $this->manifest->metadata->site->name . $base);
if (!isset($wcMap)) {
// need to make the request relative to site
if ($base == './') {
// possible this comes up empty
if (file_exists('./wc-registry.json')) {
$wcPath = './wc-registry.json';
}
}
else {
$wcPath = $base . 'wc-registry.json';
}
// support private IP space which will block this ever going through
if (!defined('IAM_PRIVATE_ADDRESS_SPACE')) {
$wcMap = json_decode(file_get_contents($wcPath));
}
}
return $wcMap;
}
/**
* Load content of this page
* @return string HTML / contents of the page object
*/
public function getPageContent($page) {
if (isset($page->location) && $page->location != '') {
$content = &$this->staticCache(__FUNCTION__ . $page->location);
if (!isset($content)) {
$content = filter_var(file_get_contents('./' . $page->location));
}
return $content;
}
}
/**
* Get a social sharing image based on context of page or site having media
* @var string $page page to mine the image from or attempt to
* @return string full URL to an image
*/
public function getSocialShareImage($page = null) {
// resolve a JOS Item vs null
if ($page != null) {
$id = $page->id;
}
else {
$id = null;
}
$fileName = &$this->staticCache(__FUNCTION__ . $id);
if (!isset($fileName)) {
if (is_null($page)) {
$page = $this->loadNodeByLocation();
}
if (isset($page->metadata->files)) {
foreach ($page->metadata->files as $file) {
if ($file->type == 'image/jpeg') {
$fileName = $file->fullUrl;
}
}
}
// look for the theme banner
if (isset($this->manifest->metadata->theme->variables->image)) {
$fileName = $this->manifest->metadata->theme->variables->image;
}
}
return $fileName;
}
/**
* Static cache a variable that may be called multiple times
* in one transaction yet has same result
*/
public function &staticCache($name, $default_value = NULL, $reset = FALSE) {
static $data = array(), $default = array();
if (isset($data[$name]) || array_key_exists($name, $data)) {
if ($reset) {
$data[$name] = $default[$name];
}
return $data[$name];
}
if (isset($name)) {
if ($reset) {
return $data;
}
$default[$name] = $data[$name] = $default_value;
return $data[$name];
}
foreach ($default as $name => $value) {
$data[$name] = $value;
}
return $data;
}
/**
* Return the link to the cdn to use for serving dynamic pages
* if $site defines a dynamicCDN endpoint then this overrides
* any global setting. Useful for locally developed custom builds.
*/
public function getCDNForDynamic() {
if (isset($this->manifest->metadata->site->dynamicCDN)) {
return $this->manifest->metadata->site->dynamicCDN;
}
return $this->cdn;
}
/**
* Return the gaID which is the (optional) Google Analytics ID
* @return string gaID the user put in
*/
public function getGaID() {
if (isset($this->manifest->metadata->site->settings->gaID) && $this->manifest->metadata->site->settings->gaID) {
return $this->manifest->metadata->site->settings->gaID;
}
return null;
}
/**
* Return the gaIDCode if we have a gaID
*/
public function getGaCode() {
$gaID = $this->getGaID();
// Security (SEC-06): validate gaID format and escape for both the HTML
// attribute and the JS string so a crafted analytics ID cannot cause XSS.
if (!is_null($gaID) && $gaID !== '' && preg_match('/^(UA-\d+-\d+|G-[A-Za-z0-9_-]+)$/', $gaID)) {
$attrID = htmlspecialchars($gaID, ENT_QUOTES, 'UTF-8');
$jsID = addcslashes($gaID, "'\\\n\r");
return "<script async src=\"https://www.googletagmanager.com/gtag/js?id=" . $attrID . "\"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '" . $jsID . "');
</script>";
}
return '';
}
/**
* Return the sw status
* @return string status of forced upgrade, string as boolean since it'll get written into a JS file
*/
public function getServiceWorkerStatus() {
if (isset($this->manifest->metadata->site->settings->sw) && $this->manifest->metadata->site->settings->sw) {
return TRUE;
}
return FALSE;
}
/**
* Return a standard service worker that takes into account
* the context of the page it's been placed on.
* @todo this will need additional vetting based on the context applied
* @return string <script> tag that will be a rather standard service worker
*/
public function getServiceWorkerScript($basePath = null, $ignoreDevMode = FALSE, $addSW = TRUE) {
// because this can screw with caching, let's make sure we
// can throttle it locally for developers as needed
if (!$addSW || ($this->developerMode && !$ignoreDevMode)) {
return "\n <!-- Service worker disabled via settings -->\n";
}
// support dynamic calculation
if (is_null($basePath)) {
$basePath = $this->basePath . $this->manifest->metadata->site->name . '/';
}
return "
<script>
if ('serviceWorker' in navigator) {
var sitePath = " . json_encode($basePath) . ";
// discover this path downstream of the root of the domain
var swScope = window.location.pathname.substring(0, window.location.pathname.indexOf(sitePath)) + sitePath;
if (swScope != document.head.getElementsByTagName('base')[0].href) {
document.head.getElementsByTagName('base')[0].href = swScope;
}
window.addEventListener('load', function () {
navigator.serviceWorker.register('service-worker.js', {
scope: swScope
}).then(function (registration) {
registration.onupdatefound = function () {
// The updatefound event implies that registration.installing is set; see
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
var installingWorker = registration.installing;
installingWorker.onstatechange = function () {
switch (installingWorker.state) {
case 'installed':
if (!navigator.serviceWorker.controller) {
window.dispatchEvent(new CustomEvent('haxcms-toast-show', {
bubbles: true,
cancelable: false,
detail: {
text: 'Pages you view are cached for offline use.',
duration: 4000
}
}));
}
break;
case 'redundant':
throw Error('The installing service worker became redundant.');
break;
}
};
};
}).catch(function (e) {
console.warn('Service worker registration failed:', e);
});
// Check to see if the service worker controlling the page at initial load
// has become redundant, since this implies there's a new service worker with fresh content.
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.onstatechange = function(event) {
if (event.target.state === 'redundant') {
var b = document.createElement('paper-button');
b.appendChild(document.createTextNode('Reload'));
b.raised = true;
b.addEventListener('click', function(e){ window.location.reload(true); });
window.dispatchEvent(new CustomEvent('haxcms-toast-show', {
bubbles: true,
cancelable: false,
detail: {
text: 'A site update is available. Reload for latest content.',
duration: 8000,
slot: b,
clone: false
}
}));
}
};
}
});
}
</script>";
}
}
$HAXSiteConfig = new HAXSiteConfig();
}