Completed
Push — master ( 131e79...afdc39 )
by Andreas
34:52 queued 12:29
created

midcom_helper_nav_backend::get_leaf()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
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 = array_merge([$root], $urltopics);
165 280
        $this->_current = end($node_path_candidates)->id;
166
167 280
        $lastgood = null;
168 280
        foreach ($node_path_candidates as $topic) {
169 280
            if (!$this->load_node($topic)) {
170
                // Node is hidden behind an undescendable one
171
                $this->_current = $lastgood;
172
                return;
173
            }
174 280
            $this->_node_path[] = $topic->id;
175 280
            $lastgood = $topic->id;
176
        }
177 280
    }
178
179
    /**
180
     * Load the navigational information associated with the topic $param, which
181
     * can be passed as an ID or as a MidgardTopic object.
182
     *
183
     * This function is the controlling instance of the loading mechanism. It
184
     * is able to load the navigation data of any topic within MidCOM's topic
185
     * tree into memory. Any uplink nodes that are not loaded into memory will
186
     * be loaded until any other known topic is encountered.
187
     *
188
     * This method does query the topic for all information and completes it to
189
     * build up a full NAP data structure
190
     *
191
     * It determines the URL_NAME of the topic automatically using the name of the
192
     * topic in question.
193
     *
194
     * The currently active leaf is only queried if and only if the currently
195
     * processed topic is equal to the current context's content topic. This should
196
     * prevent dynamically loaded components from disrupting active leaf information,
197
     * as this can happen if dynamic_load is called before showing the navigation.
198
     *
199
     * @param mixed $topic Topic object or ID to be processed
200
     * @return bool Indicating success
201
     */
202 331
    private function load_node($topic) : bool
203
    {
204 331
        if (is_a($topic, midcom_db_topic::class)) {
205 280
            $id = $topic->id;
206
        } else {
207 318
            $id = $topic;
208
        }
209 331
        if (!array_key_exists($id, self::$_nodes)) {
210 125
            $node = new midcom_helper_nav_node($topic);
211 125
            if (!$node->is_visible()) {
212 12
                return false;
213
            }
214
215 118
            if ($node->id == $this->_root) {
216 60
                $node->nodeid = -1;
217 60
                $node->relativeurl = '';
218 60
                $node->url = '';
219
            } else {
220 68
                if (!$node->nodeid || !$this->load_node($node->nodeid)) {
221 50
                    return false;
222
                }
223 19
                $node->relativeurl = self::$_nodes[$node->nodeid]->relativeurl . $node->url;
224
            }
225
            // Rewrite all host dependent URLs based on the relative URL within our topic tree.
226 78
            $node->fullurl = midcom::get()->config->get('midcom_site_url') . $node->relativeurl;
227 78
            $node->absoluteurl = midcom_connection::get_url('self') . $node->relativeurl;
228 78
            $node->permalink = midcom::get()->permalinks->create_permalink($node->guid);
229
230
            // The node is visible, add it to the list.
231 78
            self::$_nodes[$id] = $node;
232
        } else {
233 291
            $node = self::$_nodes[$id];
234
        }
235
        // Set the current leaf, this does *not* load the leaves from the DB, this is done during get_leaf.
236 291
        if ($node->id === $this->_current) {
237 287
            $currentleaf = midcom_baseclasses_components_configuration::get($node->component, 'active_leaf');
238 287
            if ($currentleaf !== false) {
239 27
                $this->_currentleaf = "{$node->id}-{$currentleaf}";
240
            }
241
        }
242
243 291
        return true;
244
    }
245
246
    /**
247
     * Return the list of leaves for a given node. This helper will construct complete leaf
248
     * data structures for each leaf found. It will first check the cache for the leaf structures,
249
     * and query the database only if the corresponding objects have not been found there.
250
     *
251
     * @param midcom_helper_nav_node $node The NAP node data structure to load the nodes for.
252
     */
253 45
    private function load_leaves(midcom_helper_nav_node $node)
254
    {
255 45
        if (array_key_exists($node->id, $this->_loaded_leaves)) {
256 15
            return;
257
        }
258 40
        $this->_loaded_leaves[$node->id] = [];
259
260 40
        $fullprefix = midcom::get()->config->get('midcom_site_url');
261 40
        $absoluteprefix = midcom_connection::get_url('self');
262
263 40
        foreach ($node->get_leaves() as $id => $leaf) {
264 28
            if (!$leaf->is_visible()) {
265
                continue;
266
            }
267
268
            // Rewrite all host-dependent URLs based on the relative URL within our topic tree.
269 28
            $leaf->fullurl = $fullprefix . $leaf->relativeurl;
270 28
            $leaf->absoluteurl = $absoluteprefix . $leaf->relativeurl;
271
272 28
            if ($leaf->guid === null) {
273 6
                $leaf->permalink = $leaf->fullurl;
274
            } else {
275 22
                $leaf->permalink = midcom::get()->permalinks->create_permalink($leaf->guid);
276
            }
277
278 28
            $this->_leaves[$id] = $leaf;
279 28
            $this->_loaded_leaves[$node->id][$id] =& $this->_leaves[$id];
280
        }
281 40
    }
282
283
    /**
284
     * Verifies the existence of a given leaf. Call this before getting a leaf from the
285
     * $_leaves cache. It will load all necessary nodes/leaves as necessary.
286
     *
287
     * @param string $leaf_id A valid NAP leaf id ($nodeid-$leafid pattern).
288
     */
289 36
    private function load_leaf($leaf_id) : bool
290
    {
291 36
        if (!$leaf_id) {
292
            debug_add("Tried to load a suspicious leaf id, probably a false from get_current_leaf.");
293
            return false;
294
        }
295
296 36
        if (array_key_exists($leaf_id, $this->_leaves)) {
297 2
            return true;
298
        }
299
300 36
        $node_id = explode('-', $leaf_id)[0];
301
302 36
        if (!$this->load_node($node_id)) {
303
            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.",
304
            MIDCOM_LOG_INFO);
305
            return false;
306
        }
307 36
        $this->load_leaves(self::$_nodes[$node_id]);
308
309 36
        return array_key_exists($leaf_id, $this->_leaves);
310
    }
311
312
    /**
313
     * Lists all Sub-nodes of $parent_node. If there are no subnodes, or if there was an error
314
     * (for instance an unknown parent node ID) you will get an empty array
315
     *
316
     * @param mixed $parent_node    The ID of the node of which the subnodes are searched.
317
     * @param boolean $show_noentry Show all objects on-site which have the noentry flag set.
318
     */
319 23
    public function list_nodes($parent_node, bool $show_noentry) : array
320
    {
321 23
        static $listed = [];
322
323 23
        if (!$this->load_node($parent_node)) {
324
            debug_add("Unable to load parent node $parent_node", MIDCOM_LOG_ERROR);
325
            return [];
326
        }
327
328 23
        $cache_identifier = $parent_node . ($show_noentry ? 'noentry' : '');
329 23
        if (!isset($listed[$cache_identifier])) {
330 12
            $listed[$cache_identifier] = [];
331
332 12
            foreach (self::$_nodes[$parent_node]->get_subnodes() as $id) {
333 1
                if (!$this->load_node($id)) {
334
                    continue;
335
                }
336
337 1
                if (   !$show_noentry
338 1
                    && self::$_nodes[$id]->noentry) {
339
                    // Hide "noentry" items
340
                    continue;
341
                }
342
343 1
                $listed[$cache_identifier][] = $id;
344
            }
345
        }
346
347 23
        return $listed[$cache_identifier];
348
    }
349
350
    /**
351
     * Lists all leaves of $parent_node. If there are no leaves, or if there was an error
352
     * (for instance an unknown parent node ID) you will get an empty array,
353
     *
354
     * @param mixed $parent_node    The ID of the node of which the leaves are searched.
355
     * @param boolean $show_noentry Show all objects on-site which have the noentry flag set.
356
     */
357 20
    public function list_leaves($parent_node, $show_noentry) : array
358
    {
359 20
        static $listed = [];
360
361 20
        if (!$this->load_node($parent_node)) {
362
            return [];
363
        }
364 20
        $cache_key = $parent_node . '--' . $show_noentry;
365
366 20
        if (!isset($listed[$cache_key])) {
367 10
            $listed[$cache_key] = [];
368 10
            $this->load_leaves(self::$_nodes[$parent_node]);
369
370 10
            foreach ($this->_loaded_leaves[self::$_nodes[$parent_node]->id] as $id => $leaf) {
371 1
                if ($show_noentry || !$leaf->noentry) {
372 1
                    $listed[$cache_key][] = $id;
373
                }
374
            }
375
        }
376
377 20
        return $listed[$cache_key];
378
    }
379
380
    /**
381
     * This is a helper function used by midcom_helper_nav::resolve_guid(). It
382
     * checks if the object denoted by the passed GUID is already loaded into
383
     * memory and returns it, if available. This should speed up GUID lookup heavy
384
     * code.
385
     *
386
     * @param string $guid The GUID to look up in the NAP cache.
387
     * @return Array A NAP structure if the GUID is known, null otherwise.
388
     */
389 28
    public function get_loaded_object_by_guid($guid)
390
    {
391 28
        $entry = $this->_nap_cache->get_guid($guid);
392 28
        if (empty($entry)) {
393 20
            return null;
394
        }
395 11
        if ($entry[MIDCOM_NAV_TYPE] == 'leaf') {
396
            return $this->get_leaf($entry[MIDCOM_NAV_ID]);
397
        }
398 11
        return $this->get_node($entry[MIDCOM_NAV_ID]);
399
    }
400
401
    /**
402
     * This will give you a key-value pair describing the node with the ID
403
     * $node_id. The defined keys are described above in Node data interchange
404
     * format. You will get false if the node ID is invalid.
405
     *
406
     * @param mixed $node_id    The node ID to be retrieved.
407
     * @return Array        The node data as outlined in the class introduction, false on failure
408
     */
409 296
    public function get_node($node_id)
410
    {
411 296
        $node = $node_id;
412 296
        if (!empty($node->guid)) {
413
            $node_id = $node->id;
414
        }
415 296
        if (!$this->load_node($node_id)) {
416 52
            return false;
417
        }
418
419 261
        return self::$_nodes[$node_id]->get_data();
420
    }
421
422
    /**
423
     * This will give you a key-value pair describing the leaf with the ID
424
     * $node_id. The defined keys are described above in leaf data interchange
425
     * format. You will get false if the leaf ID is invalid.
426
     *
427
     * @param string $leaf_id    The leaf-id to be retrieved.
428
     * @return Array        The leaf-data as outlined in the class introduction, false on failure
429
     */
430 36
    public function get_leaf($leaf_id)
431
    {
432 36
        if (!$this->load_leaf($leaf_id)) {
433 17
            debug_add("This leaf is unknown, aborting.", MIDCOM_LOG_INFO);
434 17
            return false;
435
        }
436
437 24
        return $this->_leaves[$leaf_id]->get_data();
438
    }
439
440
    /**
441
     * Retrieve the ID of the currently displayed node. Defined by the topic of
442
     * the component that declared able to handle the request.
443
     *
444
     * @return mixed    The ID of the node in question.
445
     */
446 233
    public function get_current_node()
447
    {
448 233
        return $this->_current;
449
    }
450
451
    /**
452
     * Retrieve the ID of the currently displayed leaf. This is a leaf that is
453
     * displayed by the handling topic. If no leaf is active, this function
454
     * returns false. (Remember to make a type sensitive check, e.g.
455
     * nav::get_current_leaf() !== false to distinguish "0" and "false".)
456
     *
457
     * @return string    The ID of the leaf in question or false on failure.
458
     */
459 250
    public function get_current_leaf()
460
    {
461 250
        return $this->_currentleaf;
462
    }
463
464
    /**
465
     * Retrieve the ID of the upper node of the currently displayed node.
466
     *
467
     * @return mixed    The ID of the node in question.
468
     */
469 2
    public function get_current_upper_node()
470
    {
471 2
        if (count($this->_node_path) > 1) {
472 1
            return $this->_node_path[count($this->_node_path) - 2];
473
        }
474 1
        return $this->_node_path[0];
475
    }
476
477
    /**
478
     * Retrieve the ID of the root node. Note that this ID is dependent from the
479
     * ID of the MidCOM Root topic and therefore will change as easily as the
480
     * root topic ID might. The MIDCOM_NAV_URL entry of the root node's data will
481
     * always be empty.
482
     */
483 92
    public function get_root_node() : int
484
    {
485 92
        return $this->_root;
486
    }
487
488
    /**
489
     * Retrieve the IDs of the nodes from the URL. First value at key 0 is
490
     * the root node ID, possible second value is the first subnode ID etc.
491
     * Contains only visible nodes (nodes which can be loaded).
492
     */
493 14
    public function get_node_path() : array
494
    {
495 14
        return $this->_node_path;
496
    }
497
498
    /**
499
     * Returns the ID of the node to which $leaf_id is associated to, false
500
     * on failure.
501
     *
502
     * @param string $leaf_id    The Leaf-ID to search an uplink for.
503
     * @return mixed             The ID of the Node for which we have a match, or false on failure.
504
     */
505 1
    function get_leaf_uplink($leaf_id)
506
    {
507 1
        if (!$this->load_leaf($leaf_id)) {
508
            debug_add("This leaf is unknown, aborting.", MIDCOM_LOG_ERROR);
509
            return false;
510
        }
511
512 1
        return $this->_leaves[$leaf_id]->nodeid;
513
    }
514
515
    /**
516
     * Returns the ID of the node to which $node_id is associated to, false
517
     * on failure. The root node's uplink is -1.
518
     *
519
     * @param mixed $node_id    The node ID to search an uplink for.
520
     * @return mixed             The ID of the node for which we have a match, -1 for the root node, or false on failure.
521
     */
522 70
    public function get_node_uplink($node_id)
523
    {
524 70
        if (!$this->load_node($node_id)) {
525 34
            return false;
526
        }
527
528 36
        return self::$_nodes[$node_id]->nodeid;
529
    }
530
}
531