forked from kongondo/MenuBuilder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MarkupMenuBuilder.module
2261 lines (1884 loc) · 81.8 KB
/
MarkupMenuBuilder.module
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;
/**
* Markup Menu Builder Module for ProcessWire
* This module enables you to display on your website custom menus built using ProcessMenuBuilder
*
* @author Francis Otieno (Kongondo)
*
* https://github.com/kongondo/ProcessMenuBuilder
* Created 1 September 2013
* Major update in March 2015
*
* ProcessWire 3.x
* Copyright (C) 2016 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://www.processwire.com
*
*/
class MarkupMenuBuilder extends WireData implements Module {
/**
* Return information about this module (required)
* @ Requires ProcessMenubuilder
*
*/
public static function getModuleInfo() {
return array(
'title' => 'Menu Builder: Markup',
'summary' => 'Render menus created by Process Menu Builder',
'author' => 'Francis Otieno (Kongondo)',
'version' => '0.2.82',
'href' => 'http://processwire.com/talk/topic/4451-module-menu-builder/',
'singular' => true,
'autoload' => false,
'requires' => 'ProcessMenuBuilder'
);
}
/**
* Array to store menu items for easy retrieval through the whole class.
*
*/
protected $menuItems = array();
/**
* Array to store a single menu's options for easy retrieval throughout the class.
*
*/
protected $options = array();
/**
* Array to store names and options of optional extra fields validated for use in getMenuItems().
*
*/
private $validExtraFields = array();
/**
* Current count to use as a menu items' ID ($m->id) for easy retrieval throughout the class.
*
*/
public $currentMenuItemID;
/**
* Initialise the module. This is an optional initialisation method called before any execute methods.
*
* Initialises various class properties ready for use throughout the class.
*
* @access public
*
*/
public function init() {
// required
}
/**
* Get nested array of given menu identity's menu_items
*
* @param int|string $menuID
* @return array $nested
*
*/
public function nestedArray(int|string $menuID) {
$m = wire('pages')->get('template=menus, name|id|title='.$menuID);
if (!$m->id) return false;
// Get flat items array:
$json = $m->menu_items;
$array = json_decode($json, true);
// Init nested array:
$nested = [];
// Populate nested array:
foreach ($array as $k => $v) {
if (array_key_exists('parent_id', $v)) $nested[$v['parent_id']][$k] = $v;
else $nested[$k] = $v;
}
return $nested;
}
/**
* Pass on menu items for processing and rendering.
*
* This is just a method that the user interfaces with.
* The processing work is done by other methods.
*
* @access public
* @param mixed $menuItems Page, ID, Title, Name of a menu or Array of menu items.
* @param array $options Array of menu options.
* @return string $menu Markup of built menu.
*
*/
public function render($menuItems, array $options = null) {
// processed menu options (object)
$options = $this->processOptions($options); // run options first so that some properties can be set early on
$cachedMenu = array();
// check if can build menu from cache
// if yes, convert fully cached menu items to Menu objects for use in buildMenuFromCache()
if ($options->cachedMenu) $cachedMenu = $this->processMenuFromCache($menuItems);
// building menu from cache
if (!empty($cachedMenu)) {
// convert raw menu items settings to WireData Objects for use in buildMenuFromCache()
$this->menuItems = $this->arrayToObject($cachedMenu); // @note: returns an array containing WireData objects
$menu = $this->buildMenuFromCache();
}
// building menu as normal
else {
// process menu items
$rawMenuItems = $this->processRawMenu($menuItems);
if (!is_array($rawMenuItems)) return $this->throwError();
// convert raw menu items settings to Menu objects for use in buildMenu()
$this->menuItems = $this->processMenu($rawMenuItems);
$menu = $this->buildMenu();
}
// render the menu
return $menu;
}
/**
* Process menu/breadcrumb items before passing on for building/rendering.
*
* The method determines and processes $menu variable type to return an array of menu settings from saved JSON.
* The JSON string is saved in the backend when menu is edited.
* Used by renderMenu() and renderBreadcrumbs()
*
* @access private
* @param mixed $menu Page, ID, Title, Name of a menu or Array of menu items.
* @return array $menuItems Array of menu items settings as per decoded JSON string.
*
*/
private function processRawMenu($menu) {
$menuItems = '';
$menuPage = null;
#### - work on the menu items - ###
// if we got a Page object
if ($menu instanceof Page) {
// we already have a menu page
$menuPage = $menu;// for consistency
}
// if we got a populated array of menu items
elseif (is_array($menu)) {
$menuItems = $menu; // for consistency
}
// if we got a menu title|name
elseif (is_string($menu)) {
// grab the menu
$menuName = $this->wire('sanitizer')->pageName($menu);
// get menu name selector
/* @note: this caters for multi-lingual sites in cases menu is called using its language name or title
*/
$fieldSelector = $this->getMenuNameSearchFieldSelector();
// get ProcessWire setup page (this is the parent of Menu Builder Page)
$setupPage = $this->wire('pages')->get($this->config->adminRootPageID)->child("$fieldSelector=setup, include=all");
// get Menu Builder Page
$menuBuilderPage = $setupPage->child("$fieldSelector=menu-builder, include=all");
// grab the menu page
$menuPage = $menuBuilderPage->child("$fieldSelector=$menuName, include=all");
}
// if we got an id
elseif (is_integer($menu)) {
// grab the menu page
$menuPage = $this->wire('pages')->get($menu);
}
####
// if we have a menu page, check that the menu IS NOT unpublished
if($menuPage && !$menuPage->is(Page::statusUnpublished)) {
$menuItems = json_decode($menuPage->menu_items, true);
}
return $menuItems;
}
/**
* Convert each menu/breadcrumb item to a Menu object ready for building/rendering.
*
* Menu objects are stored in a WireArray.
*
* @access private
* @param array $menuItems Array of processed menu items.
* @return object $menuItems WireArray with processed menu items.
*
*/
private function processMenu(array $menuItems) {
# STEP 1: create new menu objects from each item in the array #
$menu = $this->processMenuObjects($menuItems);
# STEP 2: add some other menu properties directly to the menu objects in this WireArray #
$menu = $this->processMenuObjects2($menu);
# STEP 3: APPLY 'current_class_level' to both mb and non-mb (included) menu items #
$menu = $this->processMenuObjects3($menu);
$this->menuItems = $menu;
return $this->menuItems;
}
/**
* Create new menu objects from each item in a given array of menu items.
*
* @access private
* @param array $menuItems Array of processed menu items.
* @return WireArray $menu A menu WireArray object with menu objects added
*
*/
private function processMenuObjects($menuItems) {
$o = $this->options;
$language = $this->wire('user')->language ? $this->wire('user')->language : null;
$page = $this->wire('page');
$pages = $this->wire('pages');
$menu = new WireArray();
foreach ($menuItems as $id => $item) {
// if menu item disabled, ignore it
if (isset($item['disabled_item'])) continue;
$pagesID = isset($item['pages_id']) ? (int) $item['pages_id'] : '';
$p = null;
if ($pagesID) {
$p = $pages->get($pagesID);
if (!$p || $p->id < 0) continue;
// skip inactive language page @note: PW will do this automatically for 'include_children'
if (!$p->viewable($language)) continue;
}
// if option to check listable, skip if page not listable
if ($o->checkListable && $p && !$p->listable()) continue;
$m = new Menu();
## set Object Properties ##
$m->id = $id;
$m->parentID = isset($item['parent_id']) ? $item['parent_id'] : 0; // if parent_id not set, it means they are top tier items
$m->pagesID = $pagesID ? $pagesID : 0; // for PW pages, use their native IDs
// TITLE
$title = $item['title'];
// display saved actual/multilingual menu title/label
if ($o->defaultTitle == 0 || $m->pagesID == 0) {
// if multi-lingual site, check for multi-lingual title, otherwise fall back to default
if (!is_null($language)) {
if ($language->name != 'default' && isset($item["title_{$language->name}"])) $title = $item["title_{$language->name}"];
else $title = $item['title'];
}
}
// pw page, if showing default title
elseif ($o->defaultTitle == 1) $title = $p->title;
$m->title = $title;
// URL
if ($m->pagesID) $url = $p->url;
elseif (!is_null($language)) {
// if multi-lingual site, check for multi-lingual url, otherwise fall back to default
if ($language->name != 'default' && isset($item["url_{$language->name}"])) $url = $item["url_{$language->name}"];
else $url = $item['url'];
} else $url = $item['url'];
$m->url = $url;
// NEW TAB
$m->newtab = isset($item['newtab']) ? 1 : '';
// TARGET
$m->target = isset($item['target']) ? $item['target'] : '';
// CSS
$m->cssID = isset($item['css_itemid']) ? $item['css_itemid'] : '';
$cssItemClass = isset($item['css_itemclass']) ? $item['css_itemclass'] : '';
$cssItemClass .= ' ' . $o->defaultClass;
//$m->cssClass = isset($item['css_itemclass']) ? $item['css_itemclass'] : '';
#$m->cssClass = trim($cssItemClass) != '' ? $cssItemClass : '';
$m->cssClass = !ctype_space($cssItemClass) ? $cssItemClass : '';
// if current class level is unlimited (0) it means we apply current class to all ANCESTORS of CURRENT PAGE BEING VIEWED irrespective of whether the current page is part of the menu (including via includeChildren) or not
// @note: we exclude 'Home' since it is always a parent
if ($o->currentClassLevel == 0 && $m->pagesID != 1 && $page->parents->has('id=' . $m->pagesID)) $m->isCurrent = 1;
// INCLUDE CHILDREN
$m->includeChildren = isset($item['include_children']) ? $item['include_children'] : '';
if ($m->includeChildren == 5) $m->includeChildren = 0; // for consistency with $o->includeChildren
$m->menuMaxLevel = isset($item['m_max_level']) ? $item['m_max_level'] : '';
// ADD EXTRA FIELDS if requested
// @note: : this is only applicable to getMenuItems(). check already done in getMenuItems()!
// @note: we skip non PW pages here!
if ($p !== null && !empty($this->validExtraFields)) $m = $this->addExtraFields($m, $p);
// add menu Object to WireArray
$menu->add($m);
} // end foreach $menuItems
return $menu;
}
/**
* Add other menu properties directly to the menu objects in a given WireArray.
*
* We add 'isParent', 'isFirst' and 'isLast' properties.
*
* @access private
* @param object $menu WireArray of processed menu objects.
* @return WireArray $menu A menu WireArray object with menu objects processed further.
*
*/
private function processMenuObjects2($menu) {
// deal with top level menu items first
$topMenuItems = $menu->find("parentID=0");
// if we found
// assign isFirst to the first top most menu item
$firstTop = $topMenuItems->first();
// if we found the first item
if($firstTop) $firstTop->isFirst = 1;
// assign isLast to last top most menu item
$lastTop = $topMenuItems->last();
// if we found the last item
if($lastTop) $lastTop->isLast = 1;
// assign isFirst and isLast as applicable to sub-menu items
foreach ($menu as $m) {
$children = $menu->find("parentID=$m->id"); // @note: we need these children for first and last
if ($children->count()) {
// set this item as a parent if it has children - for 'has_children'
$m->isParent = 1;
// add a first-child property to the menu item that is a first child - for use with 'first_class'
$first = $menu->get('id=' . $children->first()->id);
$first->isFirst = 1;
// add a last-child property to the menu item that is a last child - for use with 'last_class'
$last = $menu->get('id=' . $children->last()->id);
$last->isLast = 1;
}
}
return $menu;
}
/**
* Apply 'current_class_level' to both Menu Builder and non-Menu Builder (included) ancestors of menu items.
*
* @access private
* @param object $menu WireArray of processed menu objects.
* @return WireArray $menu A menu WireArray object with menu objects processed further.
*
*/
private function processMenuObjects3($menu) {
$o = $this->options;
$page = $this->wire('page');
# 1. CURRENT PAGE BEING VIEWED IS NOT already part of this menu
// we we will check if it is perhaps an INCLUDED ITEM
if (!$menu->get('pagesID=' . $page->id)) {
// closest natural parent that is PART of this menu
$closestNaturalParent = '';
// returns a normal array with reversed parent IDs, closest first
$currentPageNaturalParentsIDs = $this->currentPageParents(true);
// find the closest parent. We'll use it to determine if 'include_children' was used...
// and if we have 'net' mb parents needing a 'current_class'
// we assume that any included children were added via a closest parent
foreach ($currentPageNaturalParentsIDs as $id) {
$closestNaturalParent = $menu->get('pagesID=' . $id); // menu object
if ($closestNaturalParent) break; // stop if we found a natural parent
}
// if we have a closest natural parent AND the parent does not forbid 'include_children' either locally (in backend menu settings) OR globally (in options in template file)...
//...OR, the closest parent DOES NOT only allow 'include_children' in Breadcrumbs...
if ($closestNaturalParent && ($closestNaturalParent->includeChildren !== 0 && $closestNaturalParent->includeChildren != 2 && $o->includeChildren != 0)) {
// if 'include_children' in menu declared locally (item-level) or globally (options-level)
if (($closestNaturalParent->includeChildren == 1 || $closestNaturalParent->includeChildren == 3) || ($o->includeChildren == 1 || $o->includeChildren == 3)) {
//$net = $o->currentClassLevel - count($currentPageNaturalParentsIDs);// determine if we have 'remaining' parents
/*
@TODO: REVISIT THIS -> sometimes we get unexpected results
E.g., where we have /about-us/what-we-do/mission/ and about-us is an MB child of sports
sports
about-us
what-we-do
mission
with current_class_level = 0, we get current class applied all the way up to 'sports' when viewing page 'mission'
However, when viewing 'what-we-do' OR 'about-us', current class is NOT applied all the way up to 'sports'
In the latter case, a high enough 'current_class_level' solves the issue
*/
// in limited mode
if ($o->currentClassLevel != 0) {
$net = $o->currentClassLevel - count($currentPageNaturalParentsIDs); // determine if we have 'remaining' parents
}
// in unlimited mode
else $net = count($currentPageNaturalParentsIDs);
// if we have 'remaining' parents to apply 'current_class' to
if ($net > 0) {
$closestNaturalParent->isCurrent = 1; // we first apply isCurrent to closest parent
// we then apply isCurrent property to limited number of mb parents of our natural parent
$netParents = $this->currentItemParents($closestNaturalParent->parentID, $menu);
$i = 1;
foreach (explode(',', $netParents) as $netParent) {
if ($i == $net) break;
$m = $menu->get('id=' . $netParent);
if ($m) $m->isCurrent = 1;
$i++;
}
} // end if $net > 0
} // end if valid includeChildren declared
} // END if $closestNaturalParent->includeChildren allowed
} //END if current page being viewed is NOT already part of this menu
# 2. CURRENT PAGE BEING VIEWED IS PART OF THIS MB MENU but we check if we need to apply 'current_class' to ANCESTORS: parents, grandparents, etc...
else {
// first apply isCurrent to the current item
$c = $menu->get('pagesID=' . $page->id);
if ($c) $c->isCurrent = 1;
// if 'current_class' needs to be applied to $c's ancestors
if ($o->currentClassLevel && $o->currentClassLevel > 1) {
// we've already applied isCurrent to the current menu item so we subtract it
$net = $o->currentClassLevel - 1;
// we apply isCurrent property to limited ($net) number of the current item's mb parents
$cParents = $this->currentItemParents($c->parentID, $menu);
$i = 0;
foreach (explode(',', $cParents) as $cParent) {
$m = $menu->get('id=' . $cParent);
if ($m) $m->isCurrent = 1;
$i++;
if ($i == $net) break;
}
} // END if currentClassLevel > 1
} // END else the current page is part of this menu
return $menu;
}
/**
* Processes menu items for building menu from Cache.
*
* Useful for large menus/lists or busy sites.
* Avoids making API calls to retrieve pages to build menus.
*
* @access private
* @param mixed $menu Page, ID, Title or Name of a menu.
* @return array $cachedMenu Array with menu items that were saved to cache.
*
*/
private function processMenuFromCache($menu) {
// validate. we need the ID of the menu
$menuID = 0;
$cachedMenu = array();
// if we got a Page object
if ($menu instanceof Page) $menuID = $menu->id;
// if we got an id
elseif (is_integer($menu)) $menuID = $menu;
// if we got a menu title|name
elseif (is_string($menu)) {
// grab the menu
$menuName = $this->wire('sanitizer')->pageName($menu);
$menuParent = $this->wire('pages')->get($this->config->adminRootPageID)->child('name=setup, check_access=0')->child('name=menu-builder, check_access=0');
$menu = $menuParent->child("name=$menuName, check_access=0");
if ($menu) $menuID = $menu->id;
}
if ($menuID) {
$cachedMenu = $this->getMenuCache($menuID);
// if no menu cache, build one
if (empty($cachedMenu)) $this->createMenuCache($menuID);
}
return $cachedMenu;
}
/**
* Determine field selector for searching for a menu by name.
*
* This is multi-lingual aware.
*
* @access private
* @return string $fieldSelector String to use as field selector to search for a given menu name|title.
*
*/
private function getMenuNameSearchFieldSelector() {
// if in multi-lingual environment
if($this->wire('languages')) {
$languagesIDs = array();
foreach($this->wire('languages') as $language) {
// for default language, we just search 'name'
if($language->name == 'default') $languagesIDs[] = "name";
// else for other languages: @note: this will set the field to name1012, etc, where '1012' is the language id
else $languagesIDs[] = "name{$language->id}";
}
$fieldSelector = implode("|", $languagesIDs);
}
// non multi-lingual site
else $fieldSelector = "name";
return $fieldSelector;
}
/**
* Fetch cached data of a given menu.
*
* @access private
* @param integer $menuID ID of the Menu Builder Menu whose cache we want to retrieve.
* @return array $cacheData Data to build menu from.
*
*/
private function getMenuCache($menuID) {
$cacheName = 'menu-builder-' . $menuID . $this->setLanguageSuffix();
$cacheData = $this->wire('cache')->get($cacheName);
$cacheData = is_array($cacheData) ? $cacheData : array();
return $cacheData;
}
/**
* Create cache of a given Menu.
*
* This is for use with buildMenuFromCache().
*
* @access private
* @param integer $menuID ID of the Menu Builder Menu whose cache we want to create.
*
*/
private function createMenuCache($menuID) {
$cacheName = 'menu-builder-' . $menuID . $this->setLanguageSuffix();
$menuItems = $this->getMenuItems($menuID, 1, $this->options); // get array of menu items @note: it includes 'included children'
$cachedMenuTime = $this->options->cachedMenuTime;
$this->wire('cache')->save($cacheName, $menuItems, $cachedMenuTime);
}
/**
* Set the name of user's language as suffix for finding cached menus.
*
* @access private
* @return string $languageSuffix Hyphenated language name.
*
*/
private function setLanguageSuffix() {
$language = $this->wire('user')->language ? $this->wire('user')->language : null;
$languageSuffix = $language ? "-" . $language->name : '';
return $languageSuffix;
}
/**
* Returns a collection of WireData objects of a multi-dimensional array.
*
* @param array $data Array to convert to collection of WireData objects.
* @return array $data Array carrying WireData Objects of menu items.
*
*/
private function arrayToObject($data) {
/* @credits:
https://www.if-not-true-then-false.com/2009/php-tip-convert-stdclass-object-to-multidimensional-array-and-convert-multidimensional-array-to-stdclass-object/
*/
// Return array converted to WireArray object Using $this->arrayToWireData for recursive callback
if (is_array($data)) return array_map(array($this, "arrayToWireData"), $data);
// if we already have an object, just return it
else return $data;
}
/**
* Set a given array to a new WireData object.
*
* Used as a callback in $this->arrayToObject() method.
*
* @param array $data Array to set to WireData object.
* @return object $menuItem WireData with set array.
*/
private function arrayToWireData($data) {
$menuItem = new WireData();
$menuItem->setArray($data);
return $menuItem;
}
/**
* Builds a nested list (menu items) of a single menu.
*
* A recursive function to return nested list of menu items.
*
* @access private
* @param Int $parent ID of a menu item's parent to determine if to build sub-menus.
* @return string $out Markup of menu.
*
*/
private function buildMenu($parent = 0) {
$menu = $this->menuItems; // WireArray with Menu objects
// $total = count($menu);
$cnt = 0;
$o = $this->options;
$out = '';
$hasChild = false;
$wTag = $o->wrapperListType; // item wrapper tag. default = <ul>
$iTag = $o->listType; // item tag. default = <li>
foreach ($menu as $m) {
// set properties
$newtab = $m->newtab && empty($m->target) ? " target='_blank'" : '';
$target = $m->target ? " target='".$m->target."'" : '';
// if (!empty($target)) $newtab = ''; // Override newtab target attribute
// if this menu item is a parent; create the sub-items/child-menu-items
if ($m->parentID == $parent) {
// if this is the first child output '<ul>'/specified $wTag
if ($hasChild === false) {
$hasChild = true; // This is a parent
if ($cnt == 0) {
// assign menu css id and class if provided
$cssMenuID = $o->menucssID ? ' id="' . $o->menucssID . '"' : '';
$cssMenuClass = $o->menucssClass ? ' class="' . $o->menucssClass . '"' : '';
$out .= "\n<{$wTag}{$cssMenuID}{$cssMenuClass}>";
$first = 1;
} elseif ($cnt > 0 && $m->isFirst) {
// assign sub-menu classes if provided
$cssSubMenuClass = $o->submenucssClass ? ' class="' . $o->submenucssClass . '"' : '';
$out .= "\n<{$wTag}{$cssSubMenuClass}>";
}
} // end if has child
// check if this menu item will be including native children using includeChildren option
// we need this here to be able to apply 'has_children' css class to parent
// items with native children added via includeChildren
$pInclude = $this->includeChildrenCheck($o->includeChildren, $m);
$home = 0;
$hasNativeChildren = 0;
if ($pInclude) {
// get PW page whose natural children we will be including
$p = $this->wire('pages')->get($pInclude);
if ($p->id == 1) $home = 1; // we skip home since all children are hers anyway
if ($p->numChildren) $hasNativeChildren = 1; // has children to add
} // end if $pInclude
// item CSS
$itemCSSID = $m->cssID ? ' id="' . $m->cssID . '"' : '';
$itemCSSClass = $m->cssClass ? $m->cssClass . ' ' : '';
$itemFirst = $m->isFirst ? $o->firstClass : '';
$itemHasChildren = $m->isParent || $hasNativeChildren ? $o->hasChildrenClass . ' ' : '';
$itemLast = $m->isLast ? $o->lastClass . ' ' : '';
// apply current item class to current page + ancestors if specified for both native and included menu items
$itemCurrent = $m->isCurrent == 1 ? $o->currentClass . ' ' : '';
// a tag:
$aTopLevelClass = $o['aTopLevelClass'] ? $o['aTopLevelClass'].' ' : '';
$aChildrenClass = $o['aChildrenClass'] ? $o['aChildrenClass'].' ' : '';
$aParentClass = $o['aParentClass'] ? $o['aParentClass'].' ' : '';
$aTagClass = $parent == 0 ? $aTopLevelClass : $aChildrenClass;
if ($m->isParent) $aTagClass .= $aParentClass;
$aTagClass = trim($aTagClass);
$classes = $itemCSSClass . $itemHasChildren . $itemLast . $itemCurrent . $itemFirst;
$classes = trim(preg_replace('/\s+/', ' ', $classes));
$class = strlen($classes) ? ' class="' . $classes . '"' : '';
// if $iTag is empty, apply css id and classes to <a> instead
if (!$iTag) $out .= "\n\t<a{$itemCSSID}{$class}{$newtab}{$target} href='{$m->url}'>{$m->title}</a>";
else $out .= "\n\t<{$iTag}{$itemCSSID}{$class}>\n\t\t<a{$newtab}{$target} class=\"{$aTagClass}\" href=\"{$m->url}\">{$m->title}</a>";
// build nested/sub-elements
$out .= str_replace("\n", "\n\t\t", $this->buildMenu($m->id));
// children menu items included via 'includeChildren option'
if ($home == 0 && $hasNativeChildren == 1) {
#if item-level $m->menuMaxLevel is set, use that, otherwise default to $o->menuMaxLevel;
$depth = $m->menuMaxLevel ? $m->menuMaxLevel : $o->menuMaxLevel;
$firstChild = $m->isParent ? $p->child->id : null; // for skipping 'first_class' when native MB children already exist for this item
$out .= str_replace("\n", "\n\t\t", $this->includedFamilyMenu($p, $depth, $firstChild));
}
$out .= $iTag ? "\n\t</{$iTag}>" : ''; // if $iTag specified, close it
} // end if $parentID == $parent
$cnt++;
} // end foreach
if ($hasChild === true) $out .= "\n</{$wTag}>";
return $out;
}
/**
* Builds a nested list (menu items) of a single menu from cached values.
*
* A recursive function to return nested list of menu items.
* @note: objects here built directly from array so property names are the array indices.
*
* @access private
* @param integer $parent ID of a menu item's parent to determine if to build sub-menus.
* @return string $out Markup of menu.
*
*/
private function buildMenuFromCache($parent = 0) {
$menu = $this->menuItems; // array with collection of WireData objects
$total = count($menu);
$cnt = 0;
$o = $this->options;
$page = $this->wire('page');
$out = '';
$hasChild = false;
$wTag = $o->wrapperListType; // item wrapper tag. default = <ul>
$iTag = $o->listType; // item tag. default = <li>
foreach ($menu as $id => $m) {
// set properties
$newtab = $m->newtab ? " target='_blank'" : '';
$target = $m->target ? " target='".$m->target."'" : '';
// if this menu item is a parent; create the sub-items/child-menu-items
if ($m->parent_id == $parent) { // @note: here and throughout, property names == original array index!
// if this is the first child output '<ul>'/specified $wTag
if ($hasChild === false) {
$hasChild = true; // This is a parent
if ($cnt == 0) {
// assign menu css id and class if provided
$cssMenuID = $o->menucssID ? ' id="' . $o->menucssID . '"' : '';
$cssMenuClass = $o->menucssClass ? ' class="' . $o->menucssClass . '"' : '';
$out .= "\n<{$wTag}{$cssMenuID}{$cssMenuClass}>";
$first = 1;
} elseif ($cnt > 0 && $m->is_first) {
// assign sub-menu classes if provided
$cssSubMenuClass = $o->submenucssClass ? ' class="' . $o->submenucssClass . '"' : '';
$out .= "\n<{$wTag}{$cssSubMenuClass}>";
}
} // end if has child
// item CSS
$itemCSSID = $m->css_itemid ? ' id="' . $m->css_itemid . '"' : '';
$itemCSSClass = $m->css_itemclass ? $m->css_itemclass . ' ' : '';
$itemFirst = $m->is_first || $cnt == 0 ? $o->firstClass : '';
$itemHasChildren = $m->is_parent ? $o->hasChildrenClass . ' ' : '';
$itemLast = $m->is_last || $total - $cnt == 1 ? $o->lastClass . ' ' : '';
// apply current item class to current page + ancestors if specified for both native and included menu items
//$itemCurrent = $m->is_current == 1 ? $o->currentClass . ' ' : '';
// @note: $itemCurrent: This needs to be live! it cannot be cached
$itemCurrent = '';
if ($o->currentClassLevel == 0 && $m->pages_id != 1 && $page->parents->has('id=' . $m->pages_id)) $itemCurrent = $o->currentClass . ' ';
elseif ($page->id == $m->pages_id) $itemCurrent = $o->currentClass . ' ';
// @TODO: MAKE $currentClassLevel > 1 work with cached items
/* elseif($o->currentClassLevel > 1) {
} */
$classes = $itemCSSClass . $itemHasChildren . $itemLast . $itemCurrent . $itemFirst;
$classes = trim(preg_replace('/\s+/', ' ', $classes));
$class = strlen($classes) ? ' class="' . $classes . '"' : '';
// if $iTag is empty, apply css id and classes to <a> instead
if (!$iTag) $out .= "\n\t<a{$itemCSSID}{$class}{$newtab}{$target} href='{$m->url}'>{$m->title}</a>";
else $out .= "\n\t<{$iTag}{$itemCSSID}{$class}>\n\t\t<a{$newtab}{$target} href='{$m->url}'>{$m->title}</a>";
// build nested/sub-elements
$out .= str_replace("\n", "\n\t\t", $this->buildMenuFromCache($id));
$out .= $iTag ? "\n\t</{$iTag}>" : ''; // if $iTag specified, close it
} // end if $parentID == $parent
$cnt++;
} // end foreach
if ($hasChild === true) $out .= "\n</{$wTag}>";
return $out;
}
/**
* Displays a breadcrumb of menu items.
*
* A recursive function to display a breadcrumb trail of menu items built of the current menu item.
*
* @access public
* @param mixed $menu Page, ID, Title, Name of a menu or Array of menu items.
* @param array $options Array of markup options for displaying the breadcrumb.
* @return string $out.
*
*/
public function renderBreadcrumbs($menuItems, array $options = null) {
$o = $this->processOptions($options);
// process menu items
$rawMenuItems = $this->processRawMenu($menuItems);
// exit with error if no menu items found
if (!is_array($rawMenuItems)) return $this->throwError();
$menu = $this->processMenu($rawMenuItems); // convert raw menu items to Menu objects
### - checks to see if to apply 'include_children' etc... - ###
// step #1: First we check if the current page is already part of the menu items/navigation
$currentItem = $this->currentItem(true);
// if we found a menu item, just return the breadcrumb
if ($currentItem) {
return $this->buildBreadcrumbs($currentItem);
}
/*
step #2 & #3:
- if current page is not part of menu items/navigation
- check if there's at least one menu item that has 'include_children' set OR if that is set in $options
*/ elseif (!$currentItem) {
// check for API/template file breadcrumb 'include_children' setting
$selectedParents = $this->currentPageParents(false); // will return a PageArray of this item's parents
// find closest parent of the current page that is already in the menu
// we'll start building breadcrumbs off of that (i.e. it is our $currentItem)
$closestParent = $this->currentItem(false, $selectedParents); // returns a Page Object
// if we find a $closestParent, it becomes our $currentItem
// it will be a Page object with an overloaded property menuID
// we pass this $closestParent->menuID to buildBreadcrumbs()
if ($closestParent) {
// add selected parents if any to our breadcrumbs
$cp = $closestParent;
// if overriding with 'never show'
if ($o->includeChildren === 0 || $cp->includeChildren === 0) {
// return early without including children
return $this->buildBreadcrumbs($cp->menuID);
}
// no need to check for zeros again, only check if can display in breadcrumbs (2|3)
elseif ($cp->includeChildren === 2 || $cp->includeChildren === 3) {
$includeFamily = $this->includedFamilyBreadcrumbs($selectedParents, $cp);
return $this->buildBreadcrumbs($cp->menuID, $includeFamily);
}
// $option overriding item-level only when blank. Other conditions covered above and below
elseif (($o->includeChildren === 2 || $o->includeChildren === 3) && (!strlen($cp->includeChildren))) {
$includeFamily = $this->includedFamilyBreadcrumbs($selectedParents, $cp);
return $this->buildBreadcrumbs($cp->menuID, $includeFamily);
}
// either $options is 1 OR not set OR $cp is 1 (i.e., only applicable to menus)
else {
// return early without including children
return $this->buildBreadcrumbs($cp->menuID);
}
} // end if $closestparent
else {
// @todo - should we not just show breadcrumb up to valid parents? Problem is in that case there is no closest parent
return $this->throwError();
}
} // end elseif no $currentItem matching this page in menu items
}
/**
* Displays a breadcrumb of menu items.
*
* A recursive function to display a breadcrumb trail of menu items built off of the current (base) menu item.
*
* @access private
* @param Int $currentItem ID of the current menu item to start building breadcrumbs from.
* @param string $includeFamily String with non-MB menu item pages if 'include_children option set.
* @return string $out.
*
*/
private function buildBreadcrumbs($currentItem, $includeFamily = null) {
$itemIDs = '';
$menuItemsIDs = null;
$menu = $this->menuItems;
$o = $this->options;
// append the current item's ID
$itemIDs .= $currentItem . ',';
// the 'parent_id' of the current menu item
$parentID = $menu->get('id=' . $currentItem)->parentID ? $menu->get('id=' . $currentItem)->parentID : '';
// recursively build the breadcrumbs
$itemIDs .= $this->currentItemParents($parentID, $menu); // returns comma separated string of parent IDs of this menu item
$itemIDs = rtrim($itemIDs, ',');
if ($itemIDs) {
// array of menu item IDs
$menuItemsIDs = explode(',', $itemIDs);
// we reverse the items array, starting with grandparents first....
$menuItemsIDs = array_reverse($menuItemsIDs, true);
}
if (is_array($menuItemsIDs)) {
$wTag = $o->wrapperListType; // item wrapper tag. default = <ul>
$iTag = $o->listType; // item tag. default = <li>
// assign menu css id and class if provided
$cssMenuID = $o->menucssID ? ' id ="' . $o->menucssID . '" ' : '';
$cssMenuClass = $o->menucssClass ? 'class ="' . $o->menucssClass . '"' : '';
// css ID + Class for current menu item {there is only one}
$itemCurrent = $o->currentCSSID;
$cssID = strlen($itemCurrent) ? 'id="' . $itemCurrent . '"' : '';
$currentClass = $o->currentClass ? 'class ="' . $o->currentClass . '"' : '';
// build the breadcrumb
$out = '';
$out .= "<{$wTag} {$cssMenuID} {$cssMenuClass}>" . "\n";
// if option to prepend homepage specified, we prepend to menuItemsIDs
if ($o->prependHome) $menuItemsIDs = array_merge(array('Home' => 'Home'), $menuItemsIDs);
$i = 0;
$total = count($menuItemsIDs);
foreach ($menuItemsIDs as $item) {
// if prepended homepage
if ($item === 'Home') {
$item = $this->wire('pages')->get('/');
$title = $item->title;
// if we prepended homepage AND homepage is also part of this breadcrumb navigation AND we are on the homepage...
// we exit early to avoid duplicate Home >> Home
if ($item->id === $this->wire('page')->id) {
$out .= !$iTag ? "{$title}" : "<{$iTag} {$cssID} >{$title}</{$iTag}></{$wTag}>";
return $out;
}
$url = $item->url;
$newtab = '';
$target = '';
} else {
// grab the menu item in the WireArray with the id=$item
$m = $menu->get('id=' . $item);
$title = $m->title;
$url = $m->url;
$newtab = $m->newtab ? "target='_blank'" : '';
$target = $m->target ? "target='".$m->target."'" : '';
}
// ancestor items
if ($total - $i != 1) {
$divider = " {$o->divider} "; // note the spaces before and after!
// if $iTag is empty, default to <a> instead
if (!$iTag) $out .= "<a {$newtab}{$target} href='{$url}'>{$title}</a>{$divider}";
else $out .= "<$iTag><a {$newtab}{$target} href='{$url}'>{$title}</a>{$divider}</$iTag>";
}