/
NestedSet.php
executable file
·2115 lines (1880 loc) · 59.6 KB
/
NestedSet.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
//
// +----------------------------------------------------------------------+
// | PEAR :: DB_NestedSet |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Daniel Khan <dk@webcluster.at> |
// | Jason Rust <jason@rustyparts.com> |
// +----------------------------------------------------------------------+
// $Id$
//
// CREDITS:
// --------
// - Many thanks to Jason Rust for doing great improvements and cleanup work for the current release
// - Thanks to Kristian Koehntopp for publishing an explanation of the Nested Set
// technique and for the great work he did and does for the php community
// - Thanks to Daniel T. Gorski for his great tutorial on www.develnet.org
// - Thanks to Hans Lellelid for suggesting support for MDB and for helping me with the
// implementation
// ...
// - Thanks to my parents for ... just kidding :]
require_once 'PEAR.php';
// {{{ constants
// Error and message codes
define('NESE_ERROR_RECURSION', 'E100');
define('NESE_DRIVER_NOT_FOUND', 'E200');
define('NESE_ERROR_NOHANDLER', 'E300');
define('NESE_ERROR_TBLOCKED', 'E010');
define('NESE_MESSAGE_UNKNOWN', 'E0');
define('NESE_ERROR_NOTSUPPORTED', 'E1');
define('NESE_ERROR_PARAM_MISSING','E400');
define('NESE_ERROR_NOT_FOUND', 'E500');
// for moving a node before another
define('NESE_MOVE_BEFORE', 'BE');
// for moving a node after another
define('NESE_MOVE_AFTER', 'AF');
// for moving a node below another
define('NESE_MOVE_BELOW', 'SUB');
// }}}
// {{{ DB_NestedSet:: class
/**
* DB_NestedSet is a class for handling nested sets
*
* @author Daniel Khan <dk@webcluster.at>
* @package DB_NestedSet
* @version $Revision$
* @access public
*/
// }}}
class DB_NestedSet extends PEAR {
// {{{ properties
/**
* @var array The field parameters of the table with the nested set. Format: 'realFieldName' => 'fieldId'
* @access public
*/
var $params = array(
'STRID' => 'id',
'ROOTID'=> 'rootid',
'l' => 'l',
'r' => 'r',
'STREH' => 'norder',
'LEVEL' => 'level',
'STRNA' => 'name'
);
/**
* @var array The above parameters flipped for easy access
* @access private
*/
var $flparams = array();
/**
* @var array An array of field ids that must exist in the table
* Not used yet
*/
var $requiredParams = array('id', 'rootid', 'l', 'r', 'norder', 'level');
/**
* @var string The table with the actual tree data
* @access public
*/
var $node_table = 'tb_nodes';
/**
* @var string The table to handle locking
* @access public
*/
var $lock_table = 'tb_locks';
/**
* @var string The table used for sequences
* @access public
*/
var $sequence_table;
/**
* Secondary order field. Normally this is the order field, but can be changed to
* something else (i.e. the name field so that the tree can be shown alphabetically)
* @var string
* @access public
*/
var $secondarySort;
/**
* @var int The time to live of the lock
* @access public
*/
var $lockTTL = 1;
/**
* @var bool Enable debugging statements?
* @access public
*/
var $debug = false;
/**
* @var bool Lock the structure of the table?
* @access private
*/
var $structureTableLock = false;
/**
* @var bool Skip the callback events?
* @access private
*/
var $skipCallbacks = false;
/**
* @var object cache Optional PEAR::Cache object
* @access public
*/
var $cache = false;
/**
* @var bool Do we want to use caching
* @access private
*/
var $_caching = false;
/**
*
* @var bool Temporary switch for cache
* @access private
*/
var $_restcache = false;
/**
* @var array Map of error messages to their descriptions
*/
var $messages = array(
NESE_ERROR_RECURSION => 'This operation would lead to a recursion',
NESE_ERROR_TBLOCKED => 'The structure Table is locked for another database operation, please retry.',
NESE_DRIVER_NOT_FOUND => 'The selected database driver wasn\'t found',
NESE_ERROR_NOTSUPPORTED => 'Method not supported yet',
NESE_ERROR_NOHANDLER => 'Event handler not found',
NESE_ERROR_PARAM_MISSING=> 'Parameter missing',
NESE_MESSAGE_UNKNOWN => 'Unknown error or message',
NESE_ERROR_NOT_FOUND => 'Node not found',
);
/**
* @var array The array of event listeners
* @access public
*/
var $eventListeners = array();
// }}}
// +---------------------------------------+
// | Base methods |
// +---------------------------------------+
// {{{ constructor
/**
* Constructor
*
* @param array $params Database column fields which should be returned
*
* @access private
* @return void
*/
function DB_NestedSet($params)
{
$this->_debugMessage('DB_NestedSet()');
$this->PEAR();
if (is_array($params) && count($params) > 0) {
$this->params = $params;
}
$this->flparams = array_flip($this->params);
$this->sequence_table = $this->node_table . '_' . $this->flparams['id'];
$this->secondarySort = $this->flparams['norder'];
}
// }}}
// {{{ factory
/**
* Handles the returning of a concrete instance of DB_NestedSet based on the driver.
*
* @param string $driver The driver, such as DB or MDB
* @param string $dsn The dsn for connecting to the database
* @param array $params The field name params for the node table
*
* @access public
* @return object The DB_NestedSet object
*/
function & factory($driver, $dsn, $params = array())
{
$driverpath = dirname(__FILE__).'/NestedSet/'. $driver.'.php';
if(!file_exists($driverpath) || !$driver) {
return new PEAR_Error('E200',"The database driver '$driver' wasn't found");
}
include_once($driverpath);
$classname = 'DB_NestedSet_' . $driver;
return new $classname($dsn, $params);
}
// }}}
// {{{ destructor
/**
* PEAR Destructor
* Releases all locks
* Closes open database connections
*
* @access private
* @return void
*/
function _DB_NestedSet()
{
$this->_debugMessage('_DB_NestedSet()');
$this->_releaseLock();
}
// }}}
// +----------------------------------------------+
// | NestedSet manipulation and query methods |
// |----------------------------------------------+
// | Querying the tree |
// +----------------------------------------------+
// {{{ getAllNodes()
/**
* Fetch the whole NestedSet
*
* @param bool $keepAsArray (optional) Keep the result as an array or transform it into
* a set of NestedSet_Node objects?
* @param bool $aliasFields (optional) Should we alias the fields so they are the names
* of the parameter keys, or leave them as is?
* @param array $addSQL (optional) Array of additional params to pass to the query.
*
* @access public
* @return mixed False on error, or an array of nodes
*/
function getAllNodes($keepAsArray = false, $aliasFields = true, $addSQL = array())
{
$this->_debugMessage('getAllNodes()');
$sql = sprintf('SELECT %s %s FROM %s %s %s ORDER BY %s.%s, %s.%s ASC',
$this->_getSelectFields($aliasFields),
$this->_addSQL($addSQL, 'cols'),
$this->node_table,
$this->_addSQL($addSQL, 'join'),
$this->_addSQL($addSQL, 'append'),
$this->node_table,
$this->flparams['level'],
$this->node_table,
$this->secondarySort);
if (!$this->_caching) {
$nodeSet = $this->_processResultSet($sql, $keepAsArray, $aliasFields);
} else {
$nodeSet = $this->cache->call('DB_NestedSet->_processResultSet', $sql, $keepAsArray, $aliasFields);
}
// EVENT (nodeLoad)
foreach (array_keys($nodeSet) as $key) {
$this->triggerEvent('nodeLoad', $nodeSet[$key]);
}
return $nodeSet;
}
// }}}
// {{{ getRootNodes()
/**
* Fetches the first level (the rootnodes) of the NestedSet
*
* @param bool $keepAsArray (optional) Keep the result as an array or transform it into
* a set of NestedSet_Node objects?
* @param bool $aliasFields (optional) Should we alias the fields so they are the names
* of the parameter keys, or leave them as is?
* @param array $addSQL (optional) Array of additional params to pass to the query.
*
* @see _addSQL()
* @access public
* @return mixed False on error, or an array of nodes
*/
function getRootNodes($keepAsArray = false, $aliasFields = true, $addSQL = array())
{
$this->_debugMessage('getRootNodes()');
$sql = sprintf('SELECT %s %s FROM %s %s WHERE %s.%s=%s.%s %s ORDER BY %s.%s ASC',
$this->_getSelectFields($aliasFields),
$this->_addSQL($addSQL, 'cols'),
$this->node_table,
$this->_addSQL($addSQL, 'join'),
$this->node_table,
$this->flparams['id'],
$this->node_table,
$this->flparams['rootid'],
$this->_addSQL($addSQL, 'append'),
$this->node_table,
$this->secondarySort);
if (!$this->_caching) {
$nodeSet = $this->_processResultSet($sql, $keepAsArray, $aliasFields);
} else {
$nodeSet = $this->cache->call('DB_NestedSet->_processResultSet', $sql, $keepAsArray, $aliasFields);
}
// EVENT (nodeLoad)
foreach (array_keys($nodeSet) as $key) {
$this->triggerEvent('nodeLoad', $nodeSet[$key]);
}
return $nodeSet;
}
// }}}
// {{{ getBranch()
/**
* Fetch the whole branch where a given node id is in
*
* @param int $id The node ID
* @param bool $keepAsArray (optional) Keep the result as an array or transform it into
* a set of NestedSet_Node objects?
* @param bool $aliasFields (optional) Should we alias the fields so they are the names
* of the parameter keys, or leave them as is?
* @param array $addSQL (optional) Array of additional params to pass to the query.
*
* @see _addSQL()
* @access public
* @return mixed False on error, or an array of nodes
*/
function getBranch($id, $keepAsArray = false, $aliasFields = true, $addSQL = array())
{
$this->_debugMessage('getBranch($id)');
if (!($thisnode = $this->_getNodeObject($id))) {
return false;
}
$sql = sprintf('SELECT %s %s FROM %s %s WHERE %s.%s=%s %s ORDER BY %s.%s, %s.%s ASC',
$this->_getSelectFields($aliasFields),
$this->_addSQL($addSQL, 'cols'),
$this->node_table,
$this->_addSQL($addSQL, 'join'),
$this->node_table,
$this->flparams['rootid'],
$this->db->quote($thisnode->rootid),
$this->_addSQL($addSQL, 'append'),
$this->node_table,
$this->flparams['level'],
$this->node_table,
$this->secondarySort);
if (!$this->_caching) {
$nodeSet = $this->_processResultSet($sql, $keepAsArray, $aliasFields);
} else {
$nodeSet = $this->cache->call('DB_NestedSet->_processResultSet', $sql, $keepAsArray, $aliasFields);
}
// EVENT (nodeLoad)
foreach (array_keys($nodeSet) as $key) {
$this->triggerEvent('nodeLoad', $nodeSet[$key]);
}
return $nodeSet;
}
// }}}
// {{{ getParents()
/**
* Fetch the parents of a node given by id
*
* @param int $id The node ID
* @param bool $keepAsArray (optional) Keep the result as an array or transform it into
* a set of NestedSet_Node objects?
* @param bool $aliasFields (optional) Should we alias the fields so they are the names
* of the parameter keys, or leave them as is?
* @param array $addSQL (optional) Array of additional params to pass to the query.
*
* @see _addSQL()
* @access public
* @return mixed False on error, or an array of nodes
*/
function getParents($id, $keepAsArray = false, $aliasFields = true, $addSQL = array())
{
$this->_debugMessage('getParents($id)');
if (!($child = $this->_getNodeObject($id))) {
return false;
}
$sql = sprintf('SELECT %s %s FROM %s %s
WHERE %s.%s=%s AND %s.%s<%s AND %s.%s<%s AND %s.%s>%s %s
ORDER BY %s.%s ASC',
$this->_getSelectFields($aliasFields),
$this->_addSQL($addSQL, 'cols'),
$this->node_table,
$this->_addSQL($addSQL, 'join'),
$this->node_table,
$this->flparams['rootid'],
$child->rootid,
$this->node_table,
$this->flparams['level'],
$child->level,
$this->node_table,
$this->flparams['l'],
$child->l,
$this->node_table,
$this->flparams['r'],
$child->r,
$this->_addSQL($addSQL, 'append'),
$this->node_table,
$this->flparams['level']);
if (!$this->_caching) {
$nodeSet = $this->_processResultSet($sql, $keepAsArray, $aliasFields);
} else {
$nodeSet = $this->cache->call('DB_NestedSet->_processResultSet', $sql, $keepAsArray, $aliasFields);
}
// EVENT (nodeLoad)
foreach (array_keys($nodeSet) as $key) {
$this->triggerEvent('nodeLoad', $nodeSet[$key]);
}
return $nodeSet;
}
// }}}
// {{{ getChildren()
/**
* Fetch the children _one level_ after of a node given by id
*
* @param int $id The node ID
* @param bool $keepAsArray (optional) Keep the result as an array or transform it into
* a set of NestedSet_Node objects?
* @param bool $aliasFields (optional) Should we alias the fields so they are the names
* of the parameter keys, or leave them as is?
* @param bool $forceNorder (optional) Force the result to be ordered by the norder
* param (as opposed to the value of secondary sort). Used by the move and
* add methods.
* @param array $addSQL (optional) Array of additional params to pass to the query.
*
* @see _addSQL()
* @access public
* @return mixed False on error, or an array of nodes
*/
function getChildren($id, $keepAsArray = false, $aliasFields = true, $forceNorder = false, $addSQL = array())
{
$this->_debugMessage('getChildren($id)');
$parent = $this->_getNodeObject($id);
if (!$parent || $parent->l == ($parent->r - 1)) {
return false;
}
$orderBy = $forceNorder ? $this->flparams['norder'] : $this->secondarySort;
$sql = sprintf('SELECT %s %s FROM %s %s
WHERE %s.%s=%s AND %s.%s=%s+1 AND %s.%s BETWEEN %s AND %s %s
ORDER BY %s.%s ASC',
$this->_getSelectFields($aliasFields),
$this->_addSQL($addSQL, 'cols'),
$this->node_table,
$this->_addSQL($addSQL, 'join'),
$this->node_table,
$this->flparams['rootid'],
$this->db->quote($parent->rootid),
$this->node_table,
$this->flparams['level'],
$parent->level,
$this->node_table,
$this->flparams['l'],
$parent->l,
$parent->r,
$this->_addSQL($addSQL, 'append'),
$this->node_table,
$orderBy);
if (!$this->_caching) {
$nodeSet = $this->_processResultSet($sql, $keepAsArray, $aliasFields);
} else {
$nodeSet = $this->cache->call('DB_NestedSet->_processResultSet', $sql, $keepAsArray, $aliasFields);
}
// EVENT (nodeLoad)
foreach (array_keys($nodeSet) as $key) {
$this->triggerEvent('nodeLoad', $nodeSet[$key]);
}
return $nodeSet;
}
// }}}
// {{{ getSubBranch()
/**
* Fetch all the children of a node given by id
*
* getChildren only queries the immediate children
* getSubBranch returns all nodes below the given node
*
* @param string $id The node ID
* @param bool $keepAsArray (optional) Keep the result as an array or transform it into
* a set of NestedSet_Node objects?
* @param bool $aliasFields (optional) Should we alias the fields so they are the names
* of the parameter keys, or leave them as is?
* @param array $addSQL (optional) Array of additional params to pass to the query.
*
* @see _addSQL()
* @access public
* @return mixed False on error, or an array of nodes
*/
function getSubBranch($id, $keepAsArray = false, $aliasFields = true, $addSQL = array())
{
$this->_debugMessage('getSubBranch($id)');
if (!($parent = $this->_getNodeObject($id))) {
return false;
}
$sql = sprintf('SELECT %s %s FROM %s %s WHERE %s.%s BETWEEN %s AND %s AND %s.%s=%s AND %s.%s!=%s %s',
$this->_getSelectFields($aliasFields),
$this->_addSQL($addSQL, 'cols'),
$this->node_table,
$this->_addSQL($addSQL, 'join'),
$this->node_table,
$this->flparams['l'],
$parent->l,
$parent->r,
$this->node_table,
$this->flparams['rootid'],
$this->db->quote($parent->rootid),
$this->node_table,
$this->flparams['id'],
$this->db->quote($id),
$this->_addSQL($addSQL, 'append'));
if (!$this->_caching) {
$nodeSet = $this->_processResultSet($sql, $keepAsArray, $aliasFields);
} else {
$nodeSet = $this->cache->call('DB_NestedSet->_processResultSet', $sql, $keepAsArray, $aliasFields);
}
// EVENT (nodeLoad)
foreach (array_keys($nodeSet) as $key) {
$this->triggerEvent('nodeLoad', $nodeSet[$key]);
}
return $nodeSet;
}
// }}}
// {{{ pickNode()
/**
* Fetch the data of a node with the given id
*
* @param int $id The node id of the node to fetch
* @param bool $keepAsArray (optional) Keep the result as an array or transform it into
* a set of NestedSet_Node objects?
* @param bool $aliasFields (optional) Should we alias the fields so they are the names
* of the parameter keys, or leave them as is?
* @param string $idfield (optional) Which field has to be compared with $id?
* This is can be used to pick a node by other values (e.g. it's name).
* @param array $addSQL (optional) Array of additional params to pass to the query.
*
* @see _addSQL()
* @access public
* @return mixed False on error, or an array of nodes
*/
function pickNode($id, $keepAsArray = false, $aliasFields = true, $idfield = 'id', $addSQL = array())
{
$this->_debugMessage('pickNode($id)');
if (is_object($id) && $id->id) {
$id = $id->id;
}
$sql = sprintf('SELECT %s %s FROM %s %s WHERE %s.%s=%s %s',
$this->_getSelectFields($aliasFields),
$this->_addSQL($addSQL, 'cols'),
$this->node_table,
$this->_addSQL($addSQL, 'join'),
$this->node_table,
$this->flparams[$idfield],
$this->db->quote($id),
$this->_addSQL($addSQL, 'append'));
if (!$this->_caching) {
$nodeSet = $this->_processResultSet($sql, $keepAsArray, $aliasFields);
} else {
$nodeSet = $this->cache->call('DB_NestedSet->_processResultSet', $sql, $keepAsArray, $aliasFields);
}
$nsKey = false;
// EVENT (nodeLoad)
foreach (array_keys($nodeSet) as $key) {
$this->triggerEvent('nodeLoad', $nodeSet[$key]);
$nsKey = $key;
}
if (is_array($nodeSet) && $idfield != 'id') {
$id = $nsKey;
}
return isset($nodeSet[$id]) ? $nodeSet[$id] : false;
}
// }}}
// {{{ isParent()
/**
* See if a given node is a parent of another given node
*
* A node is considered to be a parent if it resides above the child
* So it doesn't mean that the node has to be an immediate parent.
* To get this information simply compare the levels of the two nodes
* after you know that you have a parent relation.
*
* @param mixed $parent The parent node as array or object
* @param mixed $child The child node as array or object
*
* @access public
* @return bool True if it's a parent
*/
function isParent($parent, $child) {
$this->_debugMessage('isParent($parent, $child)');
if (!isset($parent)|| !isset($child)) {
return false;
}
if (is_array($parent)) {
$p_rootid = $parent['rootid'];
$p_l = $parent['l'];
$p_r = $parent['r'];
} elseif (is_object($parent)) {
$p_rootid = $parent->rootid;
$p_l = $parent->l;
$p_r = $parent->r;
}
if (is_array($child)) {
$c_rootid = $child['rootid'];
$c_l = $child['l'];
$c_r = $child['r'];
} elseif (is_object($child)) {
$c_rootid = $child->rootid;
$c_l = $child->l;
$c_r = $child->r;
}
if (($p_rootid == $c_rootid) && ($p_l < $c_l && $p_r > $c_r)) {
return true;
}
return false;
}
// }}}
// {{{ _processResultSet()
/**
* Processes a DB result set by checking for a DB error and then transforming the result
* into a set of NestedSet_Node objects or leaving it as an array.
*
* @param string $sql The sql query to be done
* @param bool $keepAsArray Keep the result as an array or transform it into a set of
* NestedSet_Node objects?
* @param bool $fieldsAreAliased Are the fields aliased?
*
* @access private
* @return mixed False on error or the transformed node set.
*/
function _processResultSet($sql, $keepAsArray, $fieldsAreAliased)
{
$result = $this->db->getAll($sql);
if ($this->_testFatalAbort($result, __FILE__, __LINE__)) {
return false;
}
$nodes = array();
$idKey = $fieldsAreAliased ? 'id' : $this->flparams['id'];
foreach ($result as $row) {
$node_id = $row[$idKey];
if ($keepAsArray) {
$nodes[$node_id] = $row;
} else {
// Create an instance of the node container
$nodes[$node_id] =& new NestedSet_Node($row);
}
}
return $nodes;
}
// }}}
// {{{ _getNodeObject()
/**
* Gets the node to work on based upon an id
*
* @param mixed $id The id which can be an object or integer
*
* @access private
* @return mixed The node object for an id or false on error
*/
function _getNodeObject($id)
{
if (!is_object($id) || !$id->id) {
return $this->pickNode($id);
}
else {
return $id;
}
}
// }}}
// {{{ _addSQL()
/**
* Adds a specific type of SQL to a query string
*
* @param array $addSQL The array of SQL strings to add. Example value:
* $addSQL = array(
* 'cols' => 'tb2.col2, tb2.col3', // Additional tables/columns
* 'join' => 'LEFT JOIN tb1 USING(STRID)', // Join statement
* 'append' => 'GROUP by tb1.STRID'); // Group condition
* @param string $type The type of SQL. Can be 'cols', 'join', or 'append'.
*
* @access private
* @return string The SQL, properly formatted
*/
function _addSQL($addSQL, $type)
{
if (!isset($addSQL[$type])) {
return '';
}
switch($param) {
case 'cols':
return ', ' . $addSQL[$param];
break;
default:
return $addSQL[$param];
break;
}
}
// }}}
// {{{ _getSelectFields()
/**
* Gets the select fields based on the params
*
* @param bool $aliasFields Should we alias the fields so they are the names of the
* parameter keys, or leave them as is?
*
* @access private
* @return string A string of query fields to select
*/
function _getSelectFields($aliasFields)
{
$queryFields = array();
foreach ($this->params as $key => $val) {
$tmp_field = $this->node_table . '.' . $key;
if ($aliasFields) {
$tmp_field .= ' AS ' . $val;
}
$queryFields[] = $tmp_field;
}
$fields = implode(', ', $queryFields);
return $fields;
}
// }}}
// +----------------------------------------------+
// | NestedSet manipulation and query methods |
// |----------------------------------------------+
// | insert / delete / update of nodes |
// +----------------------------------------------+
// | [PUBLIC] |
// +----------------------------------------------+
// {{{ createRootNode()
/**
* Creates a new root node
* Optionally it deletes the whole tree and creates one initial rootnode
*
* <pre>
* +-- root1 [target]
* |
* +-- root2 [new]
* |
* +-- root3
* </pre>
*
* @param array $values Hash with param => value pairs of the node (see $this->params)
* @param integer $id ID of target node (the rootnode after which the node should be inserted)
* @param bool $first Danger: Deletes and (re)init's the hole tree - sequences are reset
*
* @access public
* @return int The node id
*/
function createRootNode($values, $id = false, $first = false)
{
$this->_debugMessage('createRootNode($values, $id = false, $first = false)');
// Try to aquire a table lock
if(PEAR::isError($lock=$this->_setLock())) {
return $lock;
}
$flft = $this->flparams['l'];
$frgt = $this->flparams['r'];
$froot = $this->flparams['rootid'];
$fid = $this->flparams['id'];
$freh = $this->flparams['norder'];
$flevel = $this->flparams['level'];
$tb = $this->node_table;
$addval = array();
$addval[$flevel] = 1;
// Shall we delete the existing tree (reinit)
if ($first) {
$sql = "DELETE FROM $tb";
$this->db->query($sql);
$this->db->dropSequence($this->sequence_table);
// New order of the new node will be 1
$addval[$freh] = 1;
} else {
// Let's open a gap for the new node
$parent = $this->pickNode($id);
if (!$parent) {
// invalid parent node, order will be 1
$addval[$freh] = 1;
// no gap to make
$first = true;
}
else {
$addval[$freh] = $parent->norder + 1;
}
}
// Sequence of node id (equals to root id in this case
$addval[$froot] = $node_id = $addval[$fid] = $this->db->nextId($this->sequence_table);
// Left/Right values for rootnodes
$addval[$flft] = 1;
$addval[$frgt] = 2;
// Transform the node data hash to a query
if (!$qr = $this->_values2Query($values, $addval)) {
return false;
}
if (!$first) {
// Open the gap
$sql = "UPDATE $tb SET $freh=$freh+1 WHERE $fid=$froot AND $freh>$parent->norder";
$res = $this->db->query($sql);
$this->_testFatalAbort($res, __FILE__, __LINE__);
}
// Insert the new node
$sql = "INSERT INTO $tb SET $qr";
$res = $this->db->query($sql);
$this->_testFatalAbort($res, __FILE__, __LINE__);
// EVENT (nodeCreate)
$thisnode = &$this->pickNode($node_id);
$this->triggerEvent('nodeCreate', $thisnode);
return $node_id;
}
// }}}
// {{{ createSubNode()
/**
* Creates a subnode
*
* <pre>
* +-- root1
* |
* +-\ root2 [target]
* | |
* | |-- subnode1 [new]
* |
* +-- root3
* </pre>
*
* @param integer $id Parent node ID
* @param array $values Hash with param => value pairs of the node (see $this->params)
*
* @access public
* @return mixed The node id or false on error
*/
function createSubNode($id, $values)
{
$this->_debugMessage('createSubNode($id, $values)');
// Try to aquire a table lock
if(PEAR::isError($lock = $this->_setLock())) {
return $lock;
}
$freh = $this->flparams['norder'];
$flevel = $this->flparams['level'];
// Get the children of the target node
$children = $this->getChildren($id, false, true, true);
// We have children here
if ($children) {
// Get the last child
$last = array_pop($children);
// What we have to do is virtually an insert of a node after the last child
// So we don't have to proceed creating a subnode
$newNode =& $this->createRightNode($last->id, $values);
return $newNode;
}
// invalid parent id, bail out
if (!($thisnode = $this->pickNode($id))) {
$this->raiseError("Parent id: $id not found", NESE_ERROR_NOT_FOUND, PEAR_ERROR_TRIGGER, E_USER_ERROR);
return false;
}
$flft = $this->flparams['l'];
$frgt = $this->flparams['r'];
$froot = $this->flparams['rootid'];
$fid = $this->flparams['id'];
$lft = $thisnode->l;
$rgt = $thisnode->r;
$rootid = $thisnode->rootid;
$plevel = $thisnode->level;
$tb = $this->node_table;
// Open the gap
$sql = "UPDATE $tb SET $flft=$flft+2
WHERE $froot=" . $this->db->quote($rootid) . " AND
$flft>" . $this->db->quote($rgt) . " AND
$frgt>=" . $this->db->quote($rgt);
$res = $this->db->query($sql);
$this->_testFatalAbort($res, __FILE__, __LINE__);
$sql = "UPDATE $tb SET $frgt=$frgt+2
WHERE $froot=" . $this->db->quote($rootid) . " AND
$frgt>=" . $this->db->quote($rgt);
$res = $this->db->query($sql);
$this->_testFatalAbort($res, __FILE__, __LINE__);
$addval = array();
$addval[$flft] = $rgt;
$addval[$frgt] = $rgt + 1;
$addval[$froot] = $rootid;
$addval[$freh] = 1;
$addval[$flevel] = $plevel + 1;
$node_id = $addval[$fid] = $this->db->nextId($this->sequence_table);
if (!$qr = $this->_values2Query($values, $addval)) {
return false;
}
$sql = "INSERT INTO $tb SET $qr";
$res = $this->db->query($sql);
$this->_testFatalAbort($res, __FILE__, __LINE__);
// EVENT (NodeCreate)
$thisnode = $this->pickNode($node_id);
$this->triggerEvent('nodeCreate', $thisnode);
return $node_id;
}
// }}}
// {{{ createRightNode()
/**
* Creates a node after a given node
* <pre>
* +-- root1