Passed
Push — master ( 67760a...0ff2cc )
by Andreas
17:17
created

midcom_helper_nav_backend::load_leaves()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5.0061

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 5
nop 1
dl 0
loc 27
ccs 15
cts 16
cp 0.9375
crap 5.0061
rs 9.4222
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package midcom.helper
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
/**
10
 * This class is the basic building stone of the Navigation Access Point
11
 * System of MidCOM.
12
 *
13
 * It is responsible for collecting the available
14
 * information and for building the navigational tree out of it. This
15
 * class is only the internal interface to the NAP System and is used by
16
 * midcom_helper_nav as a node cache. The framework should ensure that
17
 * only one class of this type is active at one time.
18
 *
19
 * It will give you a very abstract view of the content tree, modified
20
 * by the NAP classes of the components. You can retrieve a node/leaf tree
21
 * of the content, and for each element you can retrieve a URL name and a
22
 * long name for navigation display.
23
 *
24
 * Leaves and Nodes are both indexed by integer constants which are assigned
25
 * by the framework. The framework defines two starting points in this tree:
26
 * The root node and the "current" node. The current node defined through
27
 * the topic of the component that declared to be able to handle the request.
28
 *
29
 * The class will load the necessary information on demand to minimize
30
 * database traffic.
31
 *
32
 * The interface functions should enable you to build any navigation tree you
33
 * desire. The public nav class will give you some of those high-level
34
 * functions.
35
 *
36
 * <b>Node data interchange format</b>
37
 *
38
 * Node NAP data consists of a simple key => value array with the following
39
 * keys required by the component:
40
 *
41
 * - MIDCOM_NAV_NAME => The real (= displayable) name of the element
42
 *
43
 * Other keys delivered to NAP users include:
44
 *
45
 * - MIDCOM_NAV_URL  => The URL name of the element, which is automatically
46
 *   defined by NAP.
47
 *
48
 * <b>Leaf data interchange format</b>
49
 *
50
 * Basically for each leaf the usual meta information is returned:
51
 *
52
 * - MIDCOM_NAV_URL      => URL of the leaf element
53
 * - MIDCOM_NAV_NAME     => Name of the leaf element
54
 * - MIDCOM_NAV_GUID     => Optional argument denoting the GUID of the referred element
55
 * - MIDCOM_NAV_SORTABLE => Optional argument denoting whether the element is sortable
56
 *
57
 * @package midcom.helper
58
 */
59
class midcom_helper_nav_backend
60
{
61
    /**
62
     * The ID of the MidCOM Root Content Topic
63
     *
64
     * @var int
65
     */
66
    private $_root;
67
68
    /**
69
     * The ID of the currently active Navigation Node, determined by the active
70
     * MidCOM Topic or one of its uplinks, if the subtree in question is invisible.
71
     *
72
     * @var int
73
     */
74
    private $_current;
75
76
    /**
77
     * The GUID of the currently active leaf.
78
     *
79
     * @var string
80
     */
81
    private $_currentleaf = false;
82
83
    /**
84
     * Leaf cache. It is an array which contains elements indexed by
85
     * their leaf ID. The data is again stored in an associative array:
86
     *
87
     * - MIDCOM_NAV_NODEID => ID of the parent node (int)
88
     * - MIDCOM_NAV_URL => URL name of the leaf (string)
89
     * - MIDCOM_NAV_NAME => Textual name of the leaf (string)
90
     *
91
     * @todo Update the data structure documentation
92
     * @var midcom_helper_nav_leaf[]
93
     */
94
    private $_leaves = [];
95
96
    /**
97
     * Node cache. It is an array which contains elements indexed by
98
     * their node ID. The data is again stored in an associative array:
99
     *
100
     * - MIDCOM_NAV_NODEID => ID of the parent node (-1 for the root node) (int)
101
     * - MIDCOM_NAV_URL => URL name of the leaf (string)
102
     * - MIDCOM_NAV_NAME => Textual name of the leaf (string)
103
     *
104
     * @todo Update the data structure documentation
105
     * @var midcom_helper_nav_node[]
106
     */
107
    private static $_nodes = [];
108
109
    /**
110
     * List of all topics for which the leaves have been loaded.
111
     * If the id of the node is in this array, the leaves are available, otherwise,
112
     * the leaves have to be loaded.
113
     *
114
     * @var midcom_helper_nav_leaf[]
115
     */
116
    private $_loaded_leaves = [];
117
118
    /**
119
     * The NAP cache store
120
     *
121
     * @var midcom_services_cache_module_nap
122
     */
123
    private $_nap_cache;
124
125
    /**
126
     * This array holds the node path from the URL. First value at key 0 is
127
     * the root node ID, possible second value is the first subnode ID etc.
128
     * Contains only visible nodes (nodes which can be loaded).
129
     *
130
     * @var Array
131
     */
132
    private $_node_path = [];
133
134
    /**
135
     * Constructor
136
     *
137
     * It will initialize Root Topic, Current Topic and all cache arrays.
138
     * The constructor retrieves all initialization data from the component context.
139
     *
140
     * @param midcom_db_topic $root
141
     * @param midcom_db_topic[] $urltopics
142
     */
143 280
    public function __construct(midcom_db_topic $root, array $urltopics)
144
    {
145 280
        $this->_nap_cache = midcom::get()->cache->nap;
0 ignored issues
show
Bug introduced by
The property nap does not seem to exist on midcom_services_cache.
Loading history...
146
147 280
        $this->_root = $root->id;
148 280
        $this->_current = $this->_root;
149
150 280
        $this->init_topics($root, $urltopics);
151 280
    }
152
153
    /**
154
     * Loads all nodes between root and current node.
155
     *
156
     * If the current node is behind an invisible or undescendable node, the last
157
     * known good node will be used instead for the current node.
158
     *
159
     * @param midcom_db_topic $root
160
     * @param midcom_db_topic[] $urltopics
161
     */
162 280
    private function init_topics(midcom_db_topic $root, array $urltopics)
163
    {
164 280
        $node_path_candidates = [$root];
165 280
        foreach ($urltopics as $topic) {
166 3
            $node_path_candidates[] = $topic;
167 3
            $this->_current = $topic->id;
168
        }
169
170 280
        $lastgood = null;
171 280
        foreach ($node_path_candidates as $topic) {
172 280
            if (!$this->load_node($topic)) {
173
                // Node is hidden behind an undescendable one
174
                $this->_current = $lastgood;
175
                return;
176
            }
177 280
            $this->_node_path[] = $topic->id;
178 280
            $lastgood = $topic->id;
179
        }
180 280
    }
181
182
    /**
183
     * Load the navigational information associated with the topic $param, which
184
     * can be passed as an ID or as a MidgardTopic object.
185
     *
186
     * This function is the controlling instance of the loading mechanism. It
187
     * is able to load the navigation data of any topic within MidCOM's topic
188
     * tree into memory. Any uplink nodes that are not loaded into memory will
189
     * be loaded until any other known topic is encountered.
190
     *
191
     * This method does query the topic for all information and completes it to
192
     * build up a full NAP data structure
193
     *
194
     * It determines the URL_NAME of the topic automatically using the name of the
195
     * topic in question.
196
     *
197
     * The currently active leaf is only queried if and only if the currently
198
     * processed topic is equal to the current context's content topic. This should
199
     * prevent dynamically loaded components from disrupting active leaf information,
200
     * as this can happen if dynamic_load is called before showing the navigation.
201
     *
202
     * @param mixed $topic Topic object or ID to be processed
203
     * @return bool Indicating success
204
     */
205 330
    private function load_node($topic) : bool
206
    {
207 330
        if (is_a($topic, midcom_db_topic::class)) {
208 280
            $id = $topic->id;
209
        } else {
210 317
            $id = $topic;
211
        }
212 330
        if (!array_key_exists($id, self::$_nodes)) {
213 124
            $node = new midcom_helper_nav_node($topic);
214 124
            if (!$node->is_visible()) {
215 10
                return false;
216
            }
217
218 119
            if ($node->id == $this->_root) {
219 60
                $node->nodeid = -1;
220 60
                $node->relativeurl = '';
221 60
                $node->url = '';
222
            } else {
223 69
                if (!$node->nodeid || !$this->load_node($node->nodeid)) {
224 51
                    return false;
225
                }
226 19
                $node->relativeurl = self::$_nodes[$node->nodeid]->relativeurl . $node->url;
227
            }
228
            // Rewrite all host dependent URLs based on the relative URL within our topic tree.
229 78
            $node->fullurl = midcom::get()->config->get('midcom_site_url') . $node->relativeurl;
230 78
            $node->absoluteurl = midcom_connection::get_url('self') . $node->relativeurl;
231 78
            $node->permalink = midcom::get()->permalinks->create_permalink($node->guid);
232
233
            // The node is visible, add it to the list.
234 78
            self::$_nodes[$id] = $node;
235
        } else {
236 291
            $node = self::$_nodes[$id];
237
        }
238
        // Set the current leaf, this does *not* load the leaves from the DB, this is done during get_leaf.
239 291
        if ($node->id === $this->_current) {
240 287
            $currentleaf = midcom_baseclasses_components_configuration::get($node->component, 'active_leaf');
241 287
            if ($currentleaf !== false) {
242 27
                $this->_currentleaf = "{$node->id}-{$currentleaf}";
243
            }
244
        }
245
246 291
        return true;
247
    }
248
249
    /**
250
     * Return the list of leaves for a given node. This helper will construct complete leaf
251
     * data structures for each leaf found. It will first check the cache for the leaf structures,
252
     * and query the database only if the corresponding objects have not been found there.
253
     *
254
     * @param midcom_helper_nav_node $node The NAP node data structure to load the nodes for.
255
     */
256 45
    private function load_leaves(midcom_helper_nav_node $node)
257
    {
258 45
        if (array_key_exists($node->id, $this->_loaded_leaves)) {
259 15
            return;
260
        }
261 40
        $this->_loaded_leaves[$node->id] = [];
262
263 40
        $fullprefix = midcom::get()->config->get('midcom_site_url');
264 40
        $absoluteprefix = midcom_connection::get_url('self');
265
266 40
        foreach ($node->get_leaves() as $id => $leaf) {
267 28
            if (!$leaf->is_visible()) {
268
                continue;
269
            }
270
271
            // Rewrite all host-dependent URLs based on the relative URL within our topic tree.
272 28
            $leaf->fullurl = $fullprefix . $leaf->relativeurl;
273 28
            $leaf->absoluteurl = $absoluteprefix . $leaf->relativeurl;
274
275 28
            if ($leaf->guid === null) {
276 6
                $leaf->permalink = $leaf->fullurl;
277
            } else {
278 22
                $leaf->permalink = midcom::get()->permalinks->create_permalink($leaf->guid);
279
            }
280
281 28
            $this->_leaves[$id] = $leaf;
282 28
            $this->_loaded_leaves[$node->id][$id] =& $this->_leaves[$id];
283
        }
284 40
    }
285
286
    /**
287
     * Verifies the existence of a given leaf. Call this before getting a leaf from the
288
     * $_leaves cache. It will load all necessary nodes/leaves as necessary.
289
     *
290
     * @param string $leaf_id A valid NAP leaf id ($nodeid-$leafid pattern).
291
     */
292 36
    private function load_leaf($leaf_id) : bool
293
    {
294 36
        if (!$leaf_id) {
295
            debug_add("Tried to load a suspicious leaf id, probably a false from get_current_leaf.");
296
            return false;
297
        }
298
299 36
        if (array_key_exists($leaf_id, $this->_leaves)) {
300 2
            return true;
301
        }
302
303 36
        $node_id = explode('-', $leaf_id)[0];
304
305 36
        if (!$this->load_node($node_id)) {
306
            debug_add("Tried to verify the leaf id {$leaf_id}, which should belong to node {$node_id}, but this node cannot be loaded, see debug level log for details.",
307
            MIDCOM_LOG_INFO);
308
            return false;
309
        }
310 36
        $this->load_leaves(self::$_nodes[$node_id]);
311
312 36
        return array_key_exists($leaf_id, $this->_leaves);
313
    }
314
315
    /**
316
     * Lists all Sub-nodes of $parent_node. If there are no subnodes, or if there was an error
317
     * (for instance an unknown parent node ID) you will get an empty array
318
     *
319
     * @param mixed $parent_node    The ID of the node of which the subnodes are searched.
320
     * @param boolean $show_noentry Show all objects on-site which have the noentry flag set.
321
     */
322 23
    public function list_nodes($parent_node, bool $show_noentry) : array
323
    {
324 23
        static $listed = [];
325
326 23
        if (!$this->load_node($parent_node)) {
327
            debug_add("Unable to load parent node $parent_node", MIDCOM_LOG_ERROR);
328
            return [];
329
        }
330
331 23
        $cache_identifier = $parent_node . ($show_noentry ? 'noentry' : '');
332 23
        if (!isset($listed[$cache_identifier])) {
333 12
            $listed[$cache_identifier] = [];
334
335 12
            foreach (self::$_nodes[$parent_node]->get_subnodes() as $id) {
336 1
                if (!$this->load_node($id)) {
337
                    continue;
338
                }
339
340 1
                if (   !$show_noentry
341 1
                    && self::$_nodes[$id]->noentry) {
342
                    // Hide "noentry" items
343
                    continue;
344
                }
345
346 1
                $listed[$cache_identifier][] = $id;
347
            }
348
        }
349
350 23
        return $listed[$cache_identifier];
351
    }
352
353
    /**
354
     * Lists all leaves of $parent_node. If there are no leaves, or if there was an error
355
     * (for instance an unknown parent node ID) you will get an empty array,
356
     *
357
     * @param mixed $parent_node    The ID of the node of which the leaves are searched.
358
     * @param boolean $show_noentry Show all objects on-site which have the noentry flag set.
359
     */
360 20
    public function list_leaves($parent_node, $show_noentry) : array
361
    {
362 20
        static $listed = [];
363
364 20
        if (!$this->load_node($parent_node)) {
365
            return [];
366
        }
367 20
        $cache_key = $parent_node . '--' . $show_noentry;
368
369 20
        if (!isset($listed[$cache_key])) {
370 10
            $listed[$cache_key] = [];
371 10
            $this->load_leaves(self::$_nodes[$parent_node]);
372
373 10
            foreach ($this->_loaded_leaves[self::$_nodes[$parent_node]->id] as $id => $leaf) {
374 1
                if ($show_noentry || !$leaf->noentry) {
375 1
                    $listed[$cache_key][] = $id;
376
                }
377
            }
378
        }
379
380 20
        return $listed[$cache_key];
381
    }
382
383
    /**
384
     * This is a helper function used by midcom_helper_nav::resolve_guid(). It
385
     * checks if the object denoted by the passed GUID is already loaded into
386
     * memory and returns it, if available. This should speed up GUID lookup heavy
387
     * code.
388
     *
389
     * @param string $guid The GUID to look up in the NAP cache.
390
     * @return Array A NAP structure if the GUID is known, null otherwise.
391
     */
392 28
    public function get_loaded_object_by_guid($guid)
393
    {
394 28
        $entry = $this->_nap_cache->get_guid($guid);
395 28
        if (empty($entry)) {
396 20
            return null;
397
        }
398 11
        if ($entry[MIDCOM_NAV_TYPE] == 'leaf') {
399
            return $this->get_leaf($entry[MIDCOM_NAV_ID]);
400
        }
401 11
        return $this->get_node($entry[MIDCOM_NAV_ID]);
402
    }
403
404
    /**
405
     * This will give you a key-value pair describing the node with the ID
406
     * $node_id. The defined keys are described above in Node data interchange
407
     * format. You will get false if the node ID is invalid.
408
     *
409
     * @param mixed $node_id    The node ID to be retrieved.
410
     * @return Array        The node data as outlined in the class introduction, false on failure
411
     */
412 295
    public function get_node($node_id)
413
    {
414 295
        $node = $node_id;
415 295
        if (!empty($node->guid)) {
416
            $node_id = $node->id;
417
        }
418 295
        if (!$this->load_node($node_id)) {
419 51
            return false;
420
        }
421
422 261
        return self::$_nodes[$node_id]->get_data();
423
    }
424
425
    /**
426
     * This will give you a key-value pair describing the leaf with the ID
427
     * $node_id. The defined keys are described above in leaf data interchange
428
     * format. You will get false if the leaf ID is invalid.
429
     *
430
     * @param string $leaf_id    The leaf-id to be retrieved.
431
     * @return Array        The leaf-data as outlined in the class introduction, false on failure
432
     */
433 36
    public function get_leaf($leaf_id)
434
    {
435 36
        if (!$this->load_leaf($leaf_id)) {
436 17
            debug_add("This leaf is unknown, aborting.", MIDCOM_LOG_INFO);
437 17
            return false;
438
        }
439
440 24
        return $this->_leaves[$leaf_id]->get_data();
441
    }
442
443
    /**
444
     * Retrieve the ID of the currently displayed node. Defined by the topic of
445
     * the component that declared able to handle the request.
446
     *
447
     * @return mixed    The ID of the node in question.
448
     */
449 233
    public function get_current_node()
450
    {
451 233
        return $this->_current;
452
    }
453
454
    /**
455
     * Retrieve the ID of the currently displayed leaf. This is a leaf that is
456
     * displayed by the handling topic. If no leaf is active, this function
457
     * returns false. (Remember to make a type sensitive check, e.g.
458
     * nav::get_current_leaf() !== false to distinguish "0" and "false".)
459
     *
460
     * @return string    The ID of the leaf in question or false on failure.
461
     */
462 250
    public function get_current_leaf()
463
    {
464 250
        return $this->_currentleaf;
465
    }
466
467
    /**
468
     * Retrieve the ID of the upper node of the currently displayed node.
469
     *
470
     * @return mixed    The ID of the node in question.
471
     */
472 2
    public function get_current_upper_node()
473
    {
474 2
        if (count($this->_node_path) > 1) {
475 1
            return $this->_node_path[count($this->_node_path) - 2];
476
        }
477 1
        return $this->_node_path[0];
478
    }
479
480
    /**
481
     * Retrieve the ID of the root node. Note that this ID is dependent from the
482
     * ID of the MidCOM Root topic and therefore will change as easily as the
483
     * root topic ID might. The MIDCOM_NAV_URL entry of the root node's data will
484
     * always be empty.
485
     */
486 92
    public function get_root_node() : int
487
    {
488 92
        return $this->_root;
489
    }
490
491
    /**
492
     * Retrieve the IDs of the nodes from the URL. First value at key 0 is
493
     * the root node ID, possible second value is the first subnode ID etc.
494
     * Contains only visible nodes (nodes which can be loaded).
495
     */
496 14
    public function get_node_path() : array
497
    {
498 14
        return $this->_node_path;
499
    }
500
501
    /**
502
     * Returns the ID of the node to which $leaf_id is associated to, false
503
     * on failure.
504
     *
505
     * @param string $leaf_id    The Leaf-ID to search an uplink for.
506
     * @return mixed             The ID of the Node for which we have a match, or false on failure.
507
     */
508 1
    function get_leaf_uplink($leaf_id)
509
    {
510 1
        if (!$this->load_leaf($leaf_id)) {
511
            debug_add("This leaf is unknown, aborting.", MIDCOM_LOG_ERROR);
512
            return false;
513
        }
514
515 1
        return $this->_leaves[$leaf_id]->nodeid;
516
    }
517
518
    /**
519
     * Returns the ID of the node to which $node_id is associated to, false
520
     * on failure. The root node's uplink is -1.
521
     *
522
     * @param mixed $node_id    The node ID to search an uplink for.
523
     * @return mixed             The ID of the node for which we have a match, -1 for the root node, or false on failure.
524
     */
525 70
    public function get_node_uplink($node_id)
526
    {
527 70
        if (!$this->load_node($node_id)) {
528 34
            return false;
529
        }
530
531 36
        return self::$_nodes[$node_id]->nodeid;
532
    }
533
}
534