-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathepfl-menus.php
2162 lines (1889 loc) · 75 KB
/
epfl-menus.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
/*
* Plugin Name: EPFL Menus
* Description: Stitch menus across sites
* Version: 1.5
*
*/
namespace EPFL\Menus;
/* Copyright © 2018 École Polytechnique Fédérale de Lausanne, Switzerland */
/* All Rights Reserved, except as stated in the LICENSE file. */
/**
* The EPFL is a pretty big place, and Wordpress' access control is
* not up to task to its administrative complexity. The solution we
* came up with is to apportion pages and posts of large Web sites
* into as many WordPress instances, living under the same Apache
* server and URL tree, as there are administrative subdivisions to
* cater to. This is made transparent to the visitor through a number
* of tricks and extensions, including this one.
*/
if (! defined( 'ABSPATH' )) {
die( 'Access denied.' );
}
require_once(ABSPATH . 'wp-admin/includes/class-walker-nav-menu-edit.php');
require_once(__DIR__ . '/lib/model.php');
use \EPFL\Model\TypedPost;
require_once(__DIR__ . '/lib/results.php');
use \EPFL\Results\FindFromAllTrait;
require_once(__DIR__ . '/lib/rest.php');
use \EPFL\REST\REST_API;
use \EPFL\REST\RESTClient;
use \EPFL\REST\RESTClientError;
use \EPFL\REST\RESTRemoteError;
use \EPFL\REST\RESTAPIError;
require_once(__DIR__ . '/lib/admin-controller.php');
use \EPFL\AdminController\TransientErrors;
use \EPFL\AdminController\CustomPostTypeController;
require_once(__DIR__ . '/lib/pubsub.php');
use \EPFL\Pubsub\PublishController;
use \EPFL\Pubsub\SubscribeController;
use \EPFL\Pubsub\TestWebhookFlowException;
require_once(__DIR__ . '/lib/i18n.php');
use function EPFL\I18N\___;
use function EPFL\I18N\__x;
use function EPFL\I18N\__e;
use function EPFL\I18N\get_current_language;
require_once(__DIR__ . '/lib/this-plugin.php');
use EPFL\ThisPlugin\Asset;
require_once(__DIR__ . '/lib/pod.php');
use EPFL\Pod\Site;
class MenuError extends \Exception {}
class TreeError extends \Exception {}
class TreeLoopError extends TreeError {
function __construct($ids_array) {
$msg = implode(" ", array_keys($ids_array));
parent::__construct($msg);
}
}
/**
* A Wordpress-style list of menu objects.
*
* An instance represents a list of objects that are typically
* manipulated by Wordpress and its so-called walkers in order to
* construct menus. Instances are immutable: all mutating operations
* return a fresh object where all $item objects (the ones returned
* by @link as_list) are also fresh.
*/
class MenuItemBag
{
# values we don't have any use on an item when we export it.
public static $attributes_to_filter_out_on_export = ["post_content", "post_author", "post_title", "post_mime_type", "post_date", "post_date_gmt",
"post_password", "filter", "post_excerpt", "comment_status", "ping_status", "to_ping", "pinged",
"post_modified", "classes", "xfn", "attr_title", "target", "type", "post_modified_gmt",
"post_content_filtered", "comment_count", "description", "post_modified"];
function __construct ($items, $hide_tree_problems=false) {
if (! is_array($items)) {
throw new \Error('Bad argument: ' . var_export($items, true));
}
$this->items = array();
foreach ($items as $item) {
$this->_MUTATE_add_item($item);
}
$this->_MUTATE_validate_and_toposort($hide_tree_problems);
}
static function coerce ($what) {
$thisclass = get_called_class();
if ($what instanceof $thisclass) {
return $what;
} else {
return new $thisclass($what);
}
}
function copy () {
$thisclass = get_called_class();
$copied_items = array();
foreach ($this->as_list() as $item) {
$copied_items[] = clone $item;
}
return new $thisclass($copied_items);
}
function mimic_current ($another_menu_tree) {
$copy = $this->_copy_attributes($another_menu_tree,
array('classes', 'current'));
$copy->_MUTATE_fixup_current_attributes_and_classes();
return $copy;
}
/**
* Enforce the same values on attributes 'current',
* 'current_item_ancestor' and 'current_item_parent' and 'classes'
* as WordPress' @link wp_nav_menu function would:
*
* - every parent of an item that is 'current' is 'current_item_parent'
*
* - every parent or ancestor of an item that is 'current' is
* 'current_item_ancestor'
*
* - a node has class 'menu-item-has-children' if and only if
* it has children
*/
private function _MUTATE_fixup_current_attributes_and_classes() {
$current_items = array(); // Plural 'coz why not?
foreach ($this->items as $item) {
$this->_MUTATE_reset_current_ancestry_status($item);
if ($this->_is_current($item)) {
$current_items[$this->_get_id($item)] = $item;
}
}
$current_ancestors = array();
foreach ($current_items as $item) {
$current_parent_id = $this->_get_parent_id($item);
if (! $current_parent_id) continue;
if (! ($current_parent = $this->items[$current_parent_id])) continue;
$this->_MUTATE_make_parent_of_current($current_parent);
$current_ancestors[$current_parent_id] = $current_parent;
}
while(count($current_ancestors)) {
$current_ancestors_next = array();
foreach ($current_ancestors as $current_ancestor) {
$current_ancestor_id = $this->_get_parent_id($current_ancestor);
if (! ($current_ancestor =
$this->items[$current_ancestor_id])) continue;
$current_ancestors_next[$current_ancestor_id] = $current_ancestor;
$this->_MUTATE_make_ancestor_of_current($current_ancestor);
}
$current_ancestors = $current_ancestors_next;
}
$all_parents = array();
foreach ($this->items as $item) {
if (! ($parent_id = $this->_get_parent_id($item))) continue;
$all_parents[$parent_id] = 1;
}
// Fix up 'menu-item-has-children' class or lack thereof
foreach ($this->items as $item) {
if (isset($item->classes) && $classes = $item->classes) {
$item->classes = array_filter(
$classes,
function($class) {
return $class != 'menu-item-has-children';
});
}
}
foreach (array_keys($all_parents) as $parent_id) {
$this->items[$parent_id]->classes[] = 'menu-item-has-children';
// wp_nav_menu() caller will eliminate any duplicates
}
}
private function _copy_attributes ($another_menu, $attributes) {
$thisclass = get_called_class();
if ($another_menu instanceof $thisclass) {
$src_items = $another_menu_tree->items;
} else {
$src_items = array();
foreach ($another_menu as $item) {
$src_items[$this->_get_id($item)] = $item;
}
}
$copy = $this->copy();
foreach ($copy->items as $id => &$item) {
foreach ($attributes as $k) {
if ($v = @$src_items[$id]->$k) {
$item->$k = $v;
}
}
}
return $copy;
}
/**
* Sort the tree in-place in topological order (ancestors before
* descendants)
*
* At the same time, validate the tree so that
*
* - All ->_get_parent_id's are 0 or within the graph
*
* - There are no ancestry loops
*
* @param boolean $hide_tree_problems Set to true if you want to ignore the
* problematic descendants, without throwing an error
*/
private function _MUTATE_validate_and_toposort (bool $hide_tree_problems) {
// Based on https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm
$children = array(); // Adjacency list, keyed by parent ID
$safe = array(); // List of nodes with no loops in their ancestry
// (S in the Wikipedia algorithm)
$ids_to_ignore = array(); // if we have a parent id without the data,
// ignore the full subtree
foreach ($this->items as $item) {
$id = $this->_get_id($item);
$parent_id = $this->_get_parent_id($item);
if (! $parent_id) {
$safe[] = $id;
} elseif (! array_key_exists($parent_id, $this->items)) {
// Houston, we have an inconsistency. wp-admin should show it
// in menu editor. Until someone manualy fix it,
// keep the item hidden
if (!$hide_tree_problems) {
throw new TreeError("Parent of $id ($parent_id) unknown");
} else {
$ids_to_ignore[] = $id;
if (defined('WP_DEBUG') && WP_DEBUG) {
// debuggers may want to understand what is currently happening
error_log("Menu tree error : Parent of $id ($parent_id) unknown; ignoring this entry and all the current children");
}
}
} elseif (in_array($parent_id, $ids_to_ignore)) {
// as the parent has an inconsistency, ignore all the children too
$ids_to_ignore[] = $id;
if (defined('WP_DEBUG') && WP_DEBUG) {
// debuggers may want to understand what is currently happening
error_log("Menu tree error : Ignoring this entry $id as the parent $parent_id is currently ignored");
}
} elseif (! array_key_exists($parent_id, $children)) {
$children[$parent_id] = array($id);
} else {
$children[$parent_id][] = $id;
}
}
$sorted = array(); // L in the Wikipedia algorithm
while(count($safe)) {
$n = array_shift($safe); // Proof of termination starts here
// $n is 1) known not to have loops in its ancestry, 2)
// at the right place at the end of the topological sort.
$sorted[] = $n;
if (array_key_exists($n, $children)) {
// All children of a safe node are safe
$safe = array_merge($safe, $children[$n]);
// Discard the corresponding edges from the adjacency list
unset($children[$n]);
}
}
if (count($children)) {
// Some nodes were not visited; they must have cycles.
throw new TreeLoopError(array_keys($children));
}
$unsorted_items = $this->items;
$this->items = array();
foreach ($sorted as $id) {
$this->items[$id] = $unsorted_items[$id];
}
}
function as_list () {
return array_values($this->items);
}
function find ($item_or_id) {
$id = is_object($item_or_id) ? $item_or_id->ID : $item_or_id;
return $this->items[$id];
}
function annotate_roots ($annotations) {
$copy = $this->copy();
foreach ($copy->items as $item) {
if (! $this->get_parent($item)) {
foreach ($annotations as $k => $v) {
// ->copy() is a deep copy so this is safe.
$item->$k = $v;
}
}
}
return $copy;
}
function graft ($at_item, $bag) {
return static::_MUTATE_graft(
$this->_get_id($at_item),
$this->copy(), $this->_renumber(static::coerce($bag)));
}
function reverse_graft ($at_item, $into) {
$id = $this->_get_id($at_item);
$into_renumbered = $this->_renumber($into, /*&*/$id);
return static::_MUTATE_graft($id, $into_renumbered, $this->copy());
}
/**
* Pluck all items in MenuItemBag that match $callable_predicate,
* and return them separately from the pruned tree. Discard
* now-dangling descendants of the plucked items.
*
* @param $callable_predicate A callable that takes a $item as the
* sole parameter, and returns a true value for items to
* remove from the tree, and a false value for those to
* keep. Items that are descendants of an item for which
* $callable_predicate returned true, will be discarded
* (regardless of what $callable_predicate returned for them,
* if indeed $callable_predicate was called at all for them
* which is left unspecified)
*
* @return A pair of the form array($pruned_tree, $removed) where
* $pruned_tree is a newly created copy of the pruned tree
* (or $this if $callable_predicate never returned true),
* and $removed is the list of items for which
* $callable_predicate returned a true value (*not* the
* descendants thereof).
*/
function pluck ($callable_predicate) {
$remaining_candidates = array();
$pruned = array();
foreach ($this->items as $item) {
if (call_user_func($callable_predicate, $item)) {
$pruned[$this->_get_id($item)] = $item;
} else {
$remaining_candidates[] = $item;
}
}
if (! count($pruned)) {
return array($this, []); // No change
}
// Keep descendants of $pruned out of $remaining
$remaining = array();
foreach ($remaining_candidates as $rc) {
$ancestor_ids = array();
for ($ancestor = $rc; $ancestor;
$ancestor = $this->get_parent($ancestor))
{
$ancestor_id = $this->_get_id($ancestor);
if (isset($ancestor_ids[$ancestor_id])){
throw new TreeLoopError($ancestor_ids);
} else {
$ancestor_ids[$ancestor_id] = 1;
}
if (array_key_exists($ancestor_id, $pruned)) continue 2;
}
$remaining[] = $rc;
}
$thisclass = get_called_class();
return array(new $thisclass($remaining), $pruned);
}
/**
* Apply a function on each item in this MenuItemBag.
*
* @param $func A callable that takes a $item as the sole
* parameter, and returns either a menu item (with a type
* and structure similar to $item) or NULL
*
* @return A new MenuItemBag made out of all the non-NULL values
* returned by $func
*/
function map ($func) {
$mapped_items = array();
foreach ($this->items as $item) {
$mapped_item = call_user_func($func, $item);
if ($mapped_item !== NULL) {
$mapped_items[] = $mapped_item;
}
}
$thisclass = get_called_class();
return new $thisclass($mapped_items);
}
/**
* @return A copy of $this without the ExternalMenuItem nodes
*
* Parent nodes of ExternalMenuItem nodes are decorated with
* an additional attribute 'epfl_external_menu_children_count'
* counting the elements so removed. WordPress attributes and
* CSS classes that encode parent-child relationships are also
* updated.
*/
function trim_external () {
list($retval, $emis) = $this->pluck(function($item) {
return ExternalMenuItem::looks_like($item);
});
foreach ($emis as $emi) {
$parent_id = $emi->menu_item_parent;
if (! $parent_id) continue;
$parent = $retval->find($parent_id);
if (! property_exists($parent, "epfl_external_menu_children_count")) {
$parent->epfl_external_menu_children_count = 0;
}
$parent->epfl_external_menu_children_count++;
}
$retval->_MUTATE_fixup_current_attributes_and_classes();
return $retval;
}
/**
* @return A copy of $this with ExternalMenuItem entries annotated
* with their ->rest_url, and stripped from other
* irrelevant (internal-only) metadata
*/
function export_external () {
$self = $this;
return $this->map(function($item) use ($self) {
if ($emi = ExternalMenuItem::get($item)) {
$self->_MUTATE_censor_local_metadata($item);
unset($item->url); // Makes no sense to API consumers
$item->rest_url = $emi->get_rest_url();
$item->urn = $emi->get_urn();
}
// Weed out fields we don't use from exported JSON, for efficiency
foreach (self::$attributes_to_filter_out_on_export as $attribute) {
unset($item->$attribute);
}
return $item;
});
}
function get_parent ($item) {
return @$this->items[$this->_get_parent_id($item)];
}
private function _get_id ($item) {
return $item->db_id;
}
private function _get_parent_id ($item) {
return $item->menu_item_parent;
}
// Mutators must be called *only* in the constructor or
// on (the items of) an instance obtained with @link copy.
private function _MUTATE_set_id ($item, $new_id) {
$item->db_id = $new_id;
// In actual menus, ->ID and ->db_id are always the same.
// Strange things happen if they get desynched e.g. visibility
// of deeper menu items seems to be regulated by the ->ID,
// while parent/child relationship works with the ->db_id.
// #gofigure
$item->ID = $new_id;
}
private function _MUTATE_set_parent_id ($item, $new_parent_id) {
$item->menu_item_parent = $new_parent_id;
}
private function _MUTATE_censor_local_metadata ($item) {
unset($item->guid);
unset($item->object_id);
}
private function _is_current ($item) {
return @$item->current;
}
private function _MUTATE_reset_current_ancestry_status ($item) {
unset($item->current_item_parent);
unset($item->current_item_ancestor);
if (property_exists($item, 'classes') && $item->classes) {
$item->classes = array_filter(
$item->classes,
function($c) {
return ($c !== 'current-menu-parent' and
$c != 'current-menu-ancestor');
});
}
}
private function _MUTATE_make_parent_of_current ($item) {
$item->current_item_parent = true;
$item->classes[] = 'current-menu-parent';
$this->_MUTATE_make_ancestor_of_current($item);
}
private function _MUTATE_make_ancestor_of_current ($item) {
$item->current_item_ancestor = true;
$item->classes[] = 'current-menu-ancestor';
}
private function _MUTATE_add_item ($item) {
if (array_key_exists($this->_get_id($item), $this->items)) {
throw new \Error("Duplicate ID: " . $this->_get_id($item));
}
$item = clone($item);
$this->items[$this->_get_id($item)] = $item;
}
/**
* Graft $inner into $outer at $at_id, preserving ordering.
*
* Splice the node list of $inner into $outer's at the
* proper place, also taking care of reparenting the root nodes of
* $inner.
*
* _MUTATE_graft() does *not* tolerate ID clashes between $outer and
* $inner; caller should ->_renumber() first as appropriate.
*
* _MUTATE_graft() may mutate (the items of) both $outer and
* $inner (the former, because it shares them into the return
* value). Again, caller should ->copy() as appropriate.
*
* @return A new instance of the class.
*/
private static function _MUTATE_graft ($at_id, $outer, $inner) {
$new_parent_id = $outer->_get_parent_id($outer->find($at_id));
$items = array();
foreach ($outer->as_list() as $item) {
$items[] = $item;
if ($outer->_get_id($item) === $at_id) {
foreach ($inner->as_list() as $item) {
if (! $inner->_get_parent_id($item)) {
$inner->_MUTATE_set_parent_id($item, $new_parent_id);
}
$items[] = $item;
}
}
}
$thisclass = get_called_class();
return new $thisclass($items);
}
/**
* Compute and return a copy of $other_bag with all IDs changed
* so that they don't clash with those in this instance.
*
* Renumbering always uses *negative* numbers for IDs; the
* positive numbers are reserved for pristine (i.e.,
* authoritative) nodes in the menus served over REST, so be sure
* to ->_renumber() the things that you are adding to your tree
* out of some REST query, and keep the locally-issued IDs as they
* are.
*
* This method does the right thing when this instance already
* contains items with negative IDs, thanks to @link
* _get_largest_negative_unused_id. Also, it calls @link
* _MUTATE_censor_local_metadata on all (copies of) the items
* in $other_bag
*
* @param $other_bag An instance of this class (call @link coerce
* yourself if needed)
*
* @param &$follow_this_id If passed-in as the ID of an item in
* the tree being renumbered, will be
* mutated (and passed-out) as the ID of the
* same item after renumbering
*
* @return A new instance of this class, fully unshared from both
* $this and $other_bag
*/
protected function _renumber ($other_bag, &$follow_this_id = NULL) {
$next_id = $this->_get_largest_negative_unused_id();
$translation_table = array();
foreach ($other_bag->items as $item) {
$orig_id = $this->_get_id ($item);
$orig_parent_id = $this->_get_parent_id($item);
foreach (array($orig_id, $orig_parent_id) as $old_id) {
if ($old_id and ! array_key_exists($old_id, $translation_table)) {
$translation_table[$old_id] = $next_id--;
}
}
}
// Now that we have a complete $translation_table, start over
// and renumber
$translated = array();
foreach ($other_bag->items as $item) {
$item = clone $item;
$this->_MUTATE_censor_local_metadata($item);
$orig_id = $this->_get_id($item);
$this->_MUTATE_set_id($item, $translation_table[$orig_id]);
if ($orig_parent_id = $this->_get_parent_id($item)) {
$this->_MUTATE_set_parent_id(
$item, $translation_table[$orig_parent_id]);
}
$translated[] = $item;
}
if ($follow_this_id) { // Not NULL, not zero
$follow_this_id = $translation_table[$follow_this_id];
}
$thisclass = get_called_class();
return new $thisclass($translated);
}
protected function _get_largest_negative_unused_id () {
$myids = array_keys($this->items);
$myids[] = 0; // Ensure return value is -1 or less
return min($myids) - 1;
}
}
/**
* Object model for "normal" WordPress menus, augmented with support
* for EPFL-style menu stitching.
*/
class Menu
{
static function by_term ($term_or_term_id) {
if (is_object($term_or_term_id)) {
$term_id = $term_or_term_id->term_id;
} else {
$term_id = $term_or_term_id;
}
$thisclass = get_called_class();
return new $thisclass($term_id);
}
static function by_theme_location ($theme_location) {
$mme = MenuMapEntry::find(array('theme_location' => $theme_location))
->first_preferred(array('language' => get_current_language()));
if (! $mme) return false;
return $mme->get_menu();
}
private function __construct ($term_id) {
if ($term_id > 0) {
$this->term_id = $term_id;
} else {
throw new \Error("Bogus term ID $term_id");
}
}
/**
* @return A list of all instances used anywhere in the theme's menus,
* according to @link MenuMapEntry
*/
static function all_mapped () {
$all = array();
foreach (MenuMapEntry::all() as $entry) {
$menu = $entry->get_menu();
if (! array_key_exists($menu->get_term_id(), $all)) {
$all[$menu->get_term_id()] = $menu;
}
}
return array_values($all);
}
/**
* @return A site-wide unique integer ID for this Menu
*/
function get_term_id () {
return (int)$this->term_id;
}
function equals ($that) {
$thisclass = get_called_class();
if ($that and ($that instanceof $thisclass)) {
return $this->get_term_id() === $that->get_term_id();
} else {
return false;
}
}
/**
* @return A @link MenuItemBag instance
*/
function _get_local_tree () {
$items = wp_get_nav_menu_items($this->term_id);
if ($items === FALSE) {
throw new MenuError(
"Cannot find term with ID $this->term_id");
}
if (function_exists('pll_get_post_translations') &&
($homepage_id = 0 + get_option('page_on_front'))) {
// For whatever reason, URLs of homepages and their
// translations are... weird. Reconstruct them
$is_homepage_translation = array();
foreach (pll_get_post_translations($homepage_id)
as $id) {
$is_homepage_translation[$id] = 1;
}
foreach ($items as $item) {
$post_id = 0 + $item->object_id;
if (array_key_exists($post_id, $is_homepage_translation)) {
$item->url = sprintf('%s/%s/%s/',
site_url(),
pll_get_post_language($post_id),
get_post($post_id)->post_name);
}
}
}
return new MenuItemBag($items, /* $hide_tree_problems = */ true);
}
private const SOA_SLUG = 'epfl_soa';
/**
* Compute "stitched down" menu rooted at this Menu.
*
* ExternalMenuItem entries present in the menu are decorated with
* the contents of the remote menu, as obtained over REST; they
* remain in the returned tree as a positional indicator for REST
* clients (call @link MenuItemBag::trim_external to remove them,
* e.g. prior to passing to a frontend walker).
*
* Keep our own nodes (the ones we have authority for) with
* positive IDs and renumber all grafted nodes with negative IDs.
*
* @return A @link MenuItemBag instance, in which the
* authoritative menu entries (the ones retrieved from the
* local database) have positive IDs, while the remote
* IDs are negative
*/
function get_stitched_down_tree () {
$tree = $this->_get_local_tree();
foreach ($tree->as_list() as $item) {
if (! ($emi = ExternalMenuItem::get($item))) continue;
$soa_url = Site::root()->make_absolute_url(
$emi->get_site_url() ?
$emi->get_site_url() :
$emi->get_rest_url());
$remote_menu = $emi->get_remote_menu();
if ($remote_menu) {
$tree = $tree->graft(
$item,
$remote_menu->annotate_roots(array(
self::SOA_SLUG => $soa_url)));
} else {
error_log("$emi has no remote menu");
}
}
return $tree;
}
/**
* Compute the fully stitched menu that surrounds this Menu.
*
* Like @link get_stitched_down_tree, but additionally if we are
* rendering the primary menu and this is not the root site, graft
* ourselves into the root site's menu at the proper point.
*
* In both grafting operations ("down" for ExternalMenuItems, "up"
* for the root site's menu), keep our own nodes (the ones we have
* authority for) with positive IDs and renumber all foreign nodes
* with negative IDs.
*
* @param $mme A @link MenuMapEntry instance representing the menu
* being rendered.
*
* @return A @link MenuItemBag instance, in which the
* authoritative menu entries (the ones retrieved from the
* local database) have positive IDs, while the remote
* IDs are negative
*/
function get_fully_stitched_tree ($mme) {
$tree = $this->get_stitched_down_tree();
if (! $mme->is_main()) return $tree;
if (! $root_menu = $this->_get_root_menu(Site::this_site(), $mme->get_theme_location(), $mme->get_language())) {
return $tree;
}
$soa_slug = self::SOA_SLUG;
$site_url = site_url();
if (! preg_match('#/$#', $site_url)) {
$site_url .= '/';
}
$root_menu = $root_menu->pluck(
function($item) use ($soa_slug, $site_url) {
return property_exists($item, $soa_slug) && $item->$soa_slug === $site_url;
})[0];
// When stitching up, the graft point(s) are any and all
// ExternalMenuItem's that point to ourselves.
$grafted_count = 0;
$self = $this;
foreach (
array_filter($root_menu->as_list(),
function($item) use ($self) {
return $self->_corresponds($item);
})
as $graft_point)
{
$tree = $tree->annotate_roots(array($soa_slug => $site_url))->reverse_graft($graft_point, $root_menu);
$grafted_count++;
}
if (! $grafted_count) {
error_log(sprintf(
'Cannot find graft point - Unable to stitch up %s (in %s)',
$self,
get_site_url()));
}
return $tree;
}
protected function _get_root_menu ($site, $theme_slug, $language=NULL) {
if (! $language) {
$language = get_current_language();
}
# if we have configured top menu url, get it
$menu_root_provider_url = $site->get_configured_root_menu_url();
if(empty($menu_root_provider_url)) {
if ($site->is_root()) {
return; // No root menu for ya
}
$menu_root_provider_url = Site::root()->get_path();
if (! $menu_root_provider_url) return;
}
$emi = ExternalMenuItem::find(array(
'site_url' => $menu_root_provider_url,
'remote_slug' => $theme_slug
))
->first_preferred(array(
'language' => $language));
if (! $emi) return;
return $emi->get_remote_menu();
}
public function has_root_menu ($theme_slug) {
return (boolean) $this->_get_root_menu(Site::this_site(), $theme_slug);
}
/**
* Only called for the main ("top") menu
* @param $item An item out of a @link MenuItemBag
*
* @return True iff $item designates us - That is, it came from
* the JSON representation of some ExternalMenuItem in
* another WordPress in the same pod, that points to this
* Menu instance.
*/
protected function _corresponds ($item) {
if (! ExternalMenuItem::looks_like($item)) return false;
# is an item with url or an urn ?
$urn = $item->urn;
$url = Site::this_site()->make_relative_url($item->rest_url);
$matched = array();
if (!empty($url) && preg_match(
'#^/wp-json/(.*)/menus/(.*?)(?:\?lang=(.*))?$#',
$url, $matched)) {
// Works by parsing the ->rest_url, so there is coupling with
// MenuRESTController
$mme = MenuMapEntry::find(array('theme_location' => $matched[2]))
->first_preferred(array('language' => $matched[3]));
if (! $mme) return false;
return $this->equals($mme->get_menu());
} elseif (!empty($urn)) {
# Check if this item is the configured place
$menu_root_provider_self_urn = Site::this_site()->get_pod_config('menu_root_provider_self_urn');
if ($menu_root_provider_self_urn === $urn) {
return true;
}
} else {
return false;
}
}
/**
* Whether our "authoritative" menu subtree depends on $emi
*
* @param $emi An @link ExternalMenuItem instance
*
* @return false if no change in $emi could possibly make "us"
* change (in the sense of @link get_stitched_down_tree,
* i.e. the part that we are authoritative for - Not the
* parts "above us" created with @link
* get_fully_stitched_tree). true otherwise.
*/
function depends ($emi) {
foreach ($this->_get_local_tree()->as_list() as $item) {
if ($emi->equals($item)) {
return true;
}
}
return false;
}
function __toString () {
$thisclass = get_called_class();
return "<$thisclass(term_id=$this->term_id)>";
}
}
/**
* Model for menus as belonging to the theme's menu map.
*
* An instance represents one menu from the Appearance → Menus screen
* in wp-admin; it has-a @link Menu, and also a description, a theme
* location (e.g. "primary") and a language.
*/
class MenuMapEntry
{
private function __construct(
$term_or_term_id, $theme_location, $description, $language = NULL)
{
$this->menu = Menu::by_term($term_or_term_id);
$this->theme_location = $theme_location;
$this->description = $description;
$this->language = $language;
}
function __toString () {
$thisclass = get_called_class();
return "<$thisclass('$this->theme_location', '$this->language')>";
}
function get_menu () {
return $this->menu;
}
function get_menu_term_id () {
return (int) $this->menu->get_term_id();
}
/**
* Returns the name of the location (as defined by the theme) that
* this entry appears under; also used as a portion of the URL
* ("slug") by API consumers (see @link ExternalMenuItem).
*
* @return A string designating the menu position, e.g. "primary"
* or "footer"
*/
function get_theme_location () {
return $this->theme_location;
}
function get_description () {
return $this->description;
}
function get_language () {
return $this->language;
}