Completed
Push — master ( b9159b...6bb916 )
by Andreas
18:31
created

midcom_helper_nav_backend::load_node_data()   A

Complexity

Conditions 6
Paths 14

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6

Importance

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