Subversion-Projekte lars-tiefland.cakephp

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/* SVN FILE: $Id: tree.php 8004 2009-01-16 20:15:21Z gwoo $ */
3
/**
4
 * Tree behavior class.
5
 *
6
 * Enables a model object to act as a node-based tree.
7
 *
8
 * PHP versions 4 and 5
9
 *
10
 * CakePHP :  Rapid Development Framework (http://www.cakephp.org)
11
 * Copyright 2006-2008, Cake Software Foundation, Inc.
12
 *
13
 * Licensed under The MIT License
14
 * Redistributions of files must retain the above copyright notice.
15
 *
16
 * @filesource
17
 * @copyright     Copyright 2006-2008, Cake Software Foundation, Inc.
18
 * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
19
 * @package       cake
20
 * @subpackage    cake.cake.libs.model.behaviors
21
 * @since         CakePHP v 1.2.0.4487
22
 * @version       $Revision: 8004 $
23
 * @modifiedby    $LastChangedBy: gwoo $
24
 * @lastmodified  $Date: 2009-01-16 12:15:21 -0800 (Fri, 16 Jan 2009) $
25
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
26
 */
27
/**
28
 * Short description for file
29
 *
30
 * Long description for file
31
 *
32
 * @package       cake
33
 * @subpackage    cake.cake.libs.model.behaviors
34
 */
35
class TreeBehavior extends ModelBehavior {
36
/**
37
 * Errors
38
 *
39
 * @var array
40
 */
41
	var $errors = array();
42
/**
43
 * Defaults
44
 *
45
 * @var array
46
 * @access protected
47
 */
48
	var $_defaults = array(
49
		'parent' => 'parent_id', 'left' => 'lft', 'right' => 'rght',
50
		'scope' => '1 = 1', 'type' => 'nested', '__parentChange' => false, 'recursive' => -1
51
	);
52
/**
53
 * Initiate Tree behavior
54
 *
55
 * @param object $Model
56
 * @param array $config
57
 * @return void
58
 * @access public
59
 */
60
	function setup(&$Model, $config = array()) {
61
		if (!is_array($config)) {
62
			$config = array('type' => $config);
63
		}
64
		$settings = array_merge($this->_defaults, $config);
65
 
66
		if (in_array($settings['scope'], $Model->getAssociated('belongsTo'))) {
67
			$data = $Model->getAssociated($settings['scope']);
68
			$parent =& $Model->{$settings['scope']};
69
			$settings['scope'] = $Model->alias . '.' . $data['foreignKey'] . ' = ' . $parent->alias . '.' . $parent->primaryKey;
70
			$settings['recursive'] = 0;
71
		}
72
		$this->settings[$Model->alias] = $settings;
73
	}
74
/**
75
 * After save method. Called after all saves
76
 *
77
 * Overriden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
78
 * parameters to be saved.
79
 *
80
 * @param AppModel $Model
81
 * @param boolean $created indicates whether the node just saved was created or updated
82
 * @return boolean true on success, false on failure
83
 * @access public
84
 */
85
	function afterSave(&$Model, $created) {
86
		extract($this->settings[$Model->alias]);
87
		if ($created) {
88
			if ((isset($Model->data[$Model->alias][$parent])) && $Model->data[$Model->alias][$parent]) {
89
				return $this->_setParent($Model, $Model->data[$Model->alias][$parent], $created);
90
			}
91
		} elseif ($__parentChange) {
92
			$this->settings[$Model->alias]['__parentChange'] = false;
93
			return $this->_setParent($Model, $Model->data[$Model->alias][$parent]);
94
		}
95
	}
96
/**
97
 * Before delete method. Called before all deletes
98
 *
99
 * Will delete the current node and all children using the deleteAll method and sync the table
100
 *
101
 * @param AppModel $Model
102
 * @return boolean true to continue, false to abort the delete
103
 * @access public
104
 */
105
	function beforeDelete(&$Model) {
106
		extract($this->settings[$Model->alias]);
107
		list($name, $data) = array($Model->alias, $Model->read());
108
		$data = $data[$name];
109
 
110
		if (!$data[$right] || !$data[$left]) {
111
			return true;
112
		}
113
		$diff = $data[$right] - $data[$left] + 1;
114
 
115
		if ($diff > 2) {
116
			if (is_string($scope)) {
117
				$scope = array($scope);
118
			}
119
			$scope[]["{$Model->alias}.{$left} BETWEEN ? AND ?"] = array($data[$left] + 1, $data[$right] - 1);
120
			$Model->deleteAll($scope);
121
		}
122
		$this->__sync($Model, $diff, '-', '> ' . $data[$right]);
123
		return true;
124
	}
125
/**
126
 * Before save method. Called before all saves
127
 *
128
 * Overriden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
129
 * parameters to be saved. For newly created nodes with NO parent the left and right field values are set directly by
130
 * this method bypassing the setParent logic.
131
 *
132
 * @since         1.2
133
 * @param AppModel $Model
134
 * @return boolean true to continue, false to abort the save
135
 * @access public
136
 */
137
	function beforeSave(&$Model) {
138
		extract($this->settings[$Model->alias]);
139
 
140
		if (isset($Model->data[$Model->alias][$Model->primaryKey])) {
141
			if ($Model->data[$Model->alias][$Model->primaryKey]) {
142
				if (!$Model->id) {
143
					$Model->id = $Model->data[$Model->alias][$Model->primaryKey];
144
				}
145
			}
146
			unset($Model->data[$Model->alias][$Model->primaryKey]);
147
		}
148
 
149
		$this->_addToWhitelist($Model, array($left, $right));
150
		if (!$Model->id) {
151
			if (array_key_exists($parent, $Model->data[$Model->alias]) && $Model->data[$Model->alias][$parent]) {
152
				$parentNode = $Model->find('first', array(
153
					'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),
154
					'fields' => array($Model->primaryKey, $right), 'recursive' => $recursive
155
				));
156
				if (!$parentNode) {
157
					return false;
158
				}
159
				list($parentNode) = array_values($parentNode);
160
				$Model->data[$Model->alias][$left] = 0; //$parentNode[$right];
161
				$Model->data[$Model->alias][$right] = 0; //$parentNode[$right] + 1;
162
			} else {
163
				$edge = $this->__getMax($Model, $scope, $right, $recursive);
164
				$Model->data[$Model->alias][$left] = $edge + 1;
165
				$Model->data[$Model->alias][$right] = $edge + 2;
166
			}
167
		} elseif (array_key_exists($parent, $Model->data[$Model->alias])) {
168
			if ($Model->data[$Model->alias][$parent] != $Model->field($parent)) {
169
				$this->settings[$Model->alias]['__parentChange'] = true;
170
			}
171
			if (!$Model->data[$Model->alias][$parent]) {
172
				$Model->data[$Model->alias][$parent] = null;
173
				$this->_addToWhitelist($Model, $parent);
174
			} else {
175
				list($node) = array_values($Model->find('first', array(
176
					'conditions' => array($scope,$Model->escapeField() => $Model->id),
177
					'fields' => array($Model->primaryKey, $parent, $left, $right ), 'recursive' => $recursive)
178
				));
179
 
180
				$parentNode = $Model->find('first', array(
181
					'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),
182
					'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
183
				));
184
				if (!$parentNode) {
185
					return false;
186
				}
187
				list($parentNode) = array_values($parentNode);
188
 
189
				if (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
190
					return false;
191
				} elseif ($node[$Model->primaryKey] == $parentNode[$Model->primaryKey]) {
192
					return false;
193
				}
194
			}
195
		}
196
		return true;
197
	}
198
/**
199
 * Get the number of child nodes
200
 *
201
 * If the direct parameter is set to true, only the direct children are counted (based upon the parent_id field)
202
 * If false is passed for the id parameter, all top level nodes are counted, or all nodes are counted.
203
 *
204
 * @param AppModel $Model
205
 * @param mixed $id The ID of the record to read or false to read all top level nodes
206
 * @param boolean $direct whether to count direct, or all, children
207
 * @return integer number of child nodes
208
 * @access public
209
 */
210
	function childcount(&$Model, $id = null, $direct = false) {
211
		if (is_array($id)) {
212
			extract (array_merge(array('id' => null), $id));
213
		}
214
		if ($id === null && $Model->id) {
215
			$id = $Model->id;
216
		} elseif (!$id) {
217
			$id = null;
218
		}
219
		extract($this->settings[$Model->alias]);
220
 
221
		if ($direct) {
222
			return $Model->find('count', array('conditions' => array($scope, $Model->escapeField($parent) => $id)));
223
		}
224
 
225
		if ($id === null) {
226
			return $Model->find('count', array('conditions' => $scope));
227
		} elseif (isset($Model->data[$Model->alias][$left]) && isset($Model->data[$Model->alias][$right])) {
228
			$data = $Model->data[$Model->alias];
229
		} else {
230
			$data = $Model->find('first', array('conditions' => array($scope, $Model->escapeField() => $id), 'recursive' => $recursive));
231
			if (!$data) {
232
				return 0;
233
			}
234
			$data = $data[$Model->alias];
235
		}
236
		return ($data[$right] - $data[$left] - 1) / 2;
237
	}
238
/**
239
 * Get the child nodes of the current model
240
 *
241
 * If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field)
242
 * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
243
 *
244
 * @param AppModel $Model
245
 * @param mixed $id The ID of the record to read
246
 * @param boolean $direct whether to return only the direct, or all, children
247
 * @param mixed $fields Either a single string of a field name, or an array of field names
248
 * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") defaults to the tree order
249
 * @param integer $limit SQL LIMIT clause, for calculating items per page.
250
 * @param integer $page Page number, for accessing paged data
251
 * @param integer $recursive The number of levels deep to fetch associated records
252
 * @return array Array of child nodes
253
 * @access public
254
 */
255
	function children(&$Model, $id = null, $direct = false, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
256
		if (is_array($id)) {
257
			extract (array_merge(array('id' => null), $id));
258
		}
259
		$overrideRecursive = $recursive;
260
 
261
		if ($id === null && $Model->id) {
262
			$id = $Model->id;
263
		} elseif (!$id) {
264
			$id = null;
265
		}
266
		$name = $Model->alias;
267
		extract($this->settings[$Model->alias]);
268
 
269
		if (!is_null($overrideRecursive)) {
270
			$recursive = $overrideRecursive;
271
		}
272
		if (!$order) {
273
			$order = $Model->alias . '.' . $left . ' asc';
274
		}
275
		if ($direct) {
276
			$conditions = array($scope, $Model->escapeField($parent) => $id);
277
			return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
278
		}
279
 
280
		if (!$id) {
281
			$conditions = $scope;
282
		} else {
283
			$result = array_values($Model->find('first', array(
284
				'conditions' => array($scope, $Model->escapeField() => $id),
285
				'fields' => array($left, $right),
286
				'recursive' => $recursive
287
			)));
288
 
289
			if (empty($result) || !isset($result[0])) {
290
				return array();
291
			}
292
			$conditions = array($scope,
293
				$Model->escapeField($right) . ' <' => $result[0][$right],
294
				$Model->escapeField($left) . ' >' => $result[0][$left]
295
			);
296
		}
297
		return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
298
	}
299
/**
300
 * A convenience method for returning a hierarchical array used for HTML select boxes
301
 *
302
 * @param AppModel $Model
303
 * @param mixed $conditions SQL conditions as a string or as an array('field' =>'value',...)
304
 * @param string $keyPath A string path to the key, i.e. "{n}.Post.id"
305
 * @param string $valuePath A string path to the value, i.e. "{n}.Post.title"
306
 * @param string $spacer The character or characters which will be repeated
307
 * @param integer $recursive The number of levels deep to fetch associated records
308
 * @return array An associative array of records, where the id is the key, and the display field is the value
309
 * @access public
310
 */
311
	function generatetreelist(&$Model, $conditions = null, $keyPath = null, $valuePath = null, $spacer = '_', $recursive = null) {
312
		$overrideRecursive = $recursive;
313
		extract($this->settings[$Model->alias]);
314
		if (!is_null($overrideRecursive)) {
315
			$recursive = $overrideRecursive;
316
		}
317
 
318
		if ($keyPath == null && $valuePath == null && $Model->hasField($Model->displayField)) {
319
			$fields = array($Model->primaryKey, $Model->displayField, $left, $right);
320
		} else {
321
			$fields = null;
322
		}
323
 
324
		if ($keyPath == null) {
325
			$keyPath = '{n}.' . $Model->alias . '.' . $Model->primaryKey;
326
		}
327
 
328
		if ($valuePath == null) {
329
			$valuePath = array('{0}{1}', '{n}.tree_prefix', '{n}.' . $Model->alias . '.' . $Model->displayField);
330
 
331
		} elseif (is_string($valuePath)) {
332
			$valuePath = array('{0}{1}', '{n}.tree_prefix', $valuePath);
333
 
334
		} else {
335
			$valuePath[0] = '{' . (count($valuePath) - 1) . '}' . $valuePath[0];
336
			$valuePath[] = '{n}.tree_prefix';
337
		}
338
		$order = $Model->alias . '.' . $left . ' asc';
339
		$results = $Model->find('all', compact('conditions', 'fields', 'order', 'recursive'));
340
		$stack = array();
341
 
342
		foreach ($results as $i => $result) {
343
			while ($stack && ($stack[count($stack) - 1] < $result[$Model->alias][$right])) {
344
				array_pop($stack);
345
			}
346
			$results[$i]['tree_prefix'] = str_repeat($spacer,count($stack));
347
			$stack[] = $result[$Model->alias][$right];
348
		}
349
		if (empty($results)) {
350
			return array();
351
		}
352
		return Set::combine($results, $keyPath, $valuePath);
353
	}
354
/**
355
 * Get the parent node
356
 *
357
 * reads the parent id and returns this node
358
 *
359
 * @param AppModel $Model
360
 * @param mixed $id The ID of the record to read
361
 * @param integer $recursive The number of levels deep to fetch associated records
362
 * @return array Array of data for the parent node
363
 * @access public
364
 */
365
	function getparentnode(&$Model, $id = null, $fields = null, $recursive = null) {
366
		if (is_array($id)) {
367
			extract (array_merge(array('id' => null), $id));
368
		}
369
		$overrideRecursive = $recursive;
370
		if (empty ($id)) {
371
			$id = $Model->id;
372
		}
373
		extract($this->settings[$Model->alias]);
374
		if (!is_null($overrideRecursive)) {
375
			$recursive = $overrideRecursive;
376
		}
377
		$parentId = $Model->read($parent, $id);
378
 
379
		if ($parentId) {
380
			$parentId = $parentId[$Model->alias][$parent];
381
			$parent = $Model->find('first', array('conditions' => array($Model->escapeField() => $parentId), 'fields' => $fields, 'recursive' => $recursive));
382
 
383
			return $parent;
384
		}
385
		return false;
386
	}
387
/**
388
 * Get the path to the given node
389
 *
390
 * @param AppModel $Model
391
 * @param mixed $id The ID of the record to read
392
 * @param mixed $fields Either a single string of a field name, or an array of field names
393
 * @param integer $recursive The number of levels deep to fetch associated records
394
 * @return array Array of nodes from top most parent to current node
395
 * @access public
396
 */
397
	function getpath(&$Model, $id = null, $fields = null, $recursive = null) {
398
		if (is_array($id)) {
399
			extract (array_merge(array('id' => null), $id));
400
		}
401
		$overrideRecursive = $recursive;
402
		if (empty ($id)) {
403
			$id = $Model->id;
404
		}
405
		extract($this->settings[$Model->alias]);
406
		if (!is_null($overrideRecursive)) {
407
			$recursive = $overrideRecursive;
408
		}
409
		$result = $Model->find('first', array('conditions' => array($Model->escapeField() => $id), 'fields' => array($left, $right), 'recursive' => $recursive));
410
		if ($result) {
411
			$result = array_values($result);
412
		} else {
413
			return null;
414
		}
415
		$item = $result[0];
416
		$results = $Model->find('all', array(
417
			'conditions' => array($scope, $Model->escapeField($left) . ' <=' => $item[$left], $Model->escapeField($right) . ' >=' => $item[$right]),
418
			'fields' => $fields, 'order' => array($Model->escapeField($left) => 'asc'), 'recursive' => $recursive
419
		));
420
		return $results;
421
	}
422
/**
423
 * Reorder the node without changing the parent.
424
 *
425
 * If the node is the last child, or is a top level node with no subsequent node this method will return false
426
 *
427
 * @param AppModel $Model
428
 * @param mixed $id The ID of the record to move
429
 * @param mixed $number how many places to move the node or true to move to last position
430
 * @return boolean true on success, false on failure
431
 * @access public
432
 */
433
	function movedown(&$Model, $id = null, $number = 1) {
434
		if (is_array($id)) {
435
			extract (array_merge(array('id' => null), $id));
436
		}
437
		if (!$number) {
438
			return false;
439
		}
440
		if (empty ($id)) {
441
			$id = $Model->id;
442
		}
443
		extract($this->settings[$Model->alias]);
444
		list($node) = array_values($Model->find('first', array(
445
			'conditions' => array($scope, $Model->escapeField() => $id),
446
			'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive
447
		)));
448
		if ($node[$parent]) {
449
			list($parentNode) = array_values($Model->find('first', array(
450
				'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
451
				'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
452
			)));
453
			if (($node[$right] + 1) == $parentNode[$right]) {
454
				return false;
455
			}
456
		}
457
		$nextNode = $Model->find('first', array(
458
			'conditions' => array($scope, $Model->escapeField($left) => ($node[$right] + 1)),
459
			'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive)
460
		);
461
		if ($nextNode) {
462
			list($nextNode)= array_values($nextNode);
463
		} else {
464
			return false;
465
		}
466
		$edge = $this->__getMax($Model, $scope, $right, $recursive);
467
		$this->__sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]);
468
		$this->__sync($Model, $nextNode[$left] - $node[$left], '-', 'BETWEEN ' . $nextNode[$left] . ' AND ' . $nextNode[$right]);
469
		$this->__sync($Model, $edge - $node[$left] - ($nextNode[$right] - $nextNode[$left]), '-', '> ' . $edge);
470
 
471
		if (is_int($number)) {
472
			$number--;
473
		}
474
		if ($number) {
475
			$this->moveDown($Model, $id, $number);
476
		}
477
		return true;
478
	}
479
/**
480
 * Reorder the node without changing the parent.
481
 *
482
 * If the node is the first child, or is a top level node with no previous node this method will return false
483
 *
484
 * @param AppModel $Model
485
 * @param mixed $id The ID of the record to move
486
 * @param mixed $number how many places to move the node, or true to move to first position
487
 * @return boolean true on success, false on failure
488
 * @access public
489
 */
490
	function moveup(&$Model, $id = null, $number = 1) {
491
		if (is_array($id)) {
492
			extract (array_merge(array('id' => null), $id));
493
		}
494
		if (!$number) {
495
			return false;
496
		}
497
		if (empty ($id)) {
498
			$id = $Model->id;
499
		}
500
		extract($this->settings[$Model->alias]);
501
		list($node) = array_values($Model->find('first', array(
502
			'conditions' => array($scope, $Model->escapeField() => $id),
503
			'fields' => array($Model->primaryKey, $left, $right, $parent ), 'recursive' => $recursive
504
		)));
505
		if ($node[$parent]) {
506
			list($parentNode) = array_values($Model->find('first', array(
507
				'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
508
				'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
509
			)));
510
			if (($node[$left] - 1) == $parentNode[$left]) {
511
				return false;
512
			}
513
		}
514
		$previousNode = $Model->find('first', array(
515
			'conditions' => array($scope, $Model->escapeField($right) => ($node[$left] - 1)),
516
			'fields' => array($Model->primaryKey, $left, $right),
517
			'recursive' => $recursive
518
		));
519
 
520
		if ($previousNode) {
521
			list($previousNode) = array_values($previousNode);
522
		} else {
523
			return false;
524
		}
525
		$edge = $this->__getMax($Model, $scope, $right, $recursive);
526
		$this->__sync($Model, $edge - $previousNode[$left] +1, '+', 'BETWEEN ' . $previousNode[$left] . ' AND ' . $previousNode[$right]);
527
		$this->__sync($Model, $node[$left] - $previousNode[$left], '-', 'BETWEEN ' .$node[$left] . ' AND ' . $node[$right]);
528
		$this->__sync($Model, $edge - $previousNode[$left] - ($node[$right] - $node[$left]), '-', '> ' . $edge);
529
		if (is_int($number)) {
530
			$number--;
531
		}
532
		if ($number) {
533
			$this->moveUp($Model, $id, $number);
534
		}
535
		return true;
536
	}
537
/**
538
 * Recover a corrupted tree
539
 *
540
 * The mode parameter is used to specify the source of info that is valid/correct. The opposite source of data
541
 * will be populated based upon that source of info. E.g. if the MPTT fields are corrupt or empty, with the $mode
542
 * 'parent' the values of the parent_id field will be used to populate the left and right fields. The missingParentAction
543
 * parameter only applies to "parent" mode and determines what to do if the parent field contains an id that is not present.
544
 *
545
 * @todo Could be written to be faster, *maybe*. Ideally using a subquery and putting all the logic burden on the DB.
546
 * @param AppModel $Model
547
 * @param string $mode parent or tree
548
 * @param mixed $missingParentAction 'return' to do nothing and return, 'delete' to
549
 * delete, or the id of the parent to set as the parent_id
550
 * @return boolean true on success, false on failure
551
 * @access public
552
 */
553
	function recover(&$Model, $mode = 'parent', $missingParentAction = null) {
554
		if (is_array($mode)) {
555
			extract (array_merge(array('mode' => 'parent'), $mode));
556
		}
557
		extract($this->settings[$Model->alias]);
558
		$Model->recursive = $recursive;
559
		if ($mode == 'parent') {
560
			$Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
561
				'className' => $Model->alias,
562
				'foreignKey' => $parent,
563
				'fields' => array($Model->primaryKey, $left, $right, $parent),
564
			))));
565
			$missingParents = $Model->find('list', array(
566
				'recursive' => 0,
567
				'conditions' => array($scope, array(
568
					'NOT' => array($Model->escapeField($parent) => null), $Model->VerifyParent->escapeField() => null
569
				))
570
			));
571
			$Model->unbindModel(array('belongsTo' => array('VerifyParent')));
572
			if ($missingParents) {
573
				if ($missingParentAction == 'return') {
574
					foreach ($missingParents as $id => $display) {
575
						$this->errors[]	= 'cannot find the parent for ' . $Model->alias . ' with id ' . $id . '(' . $display . ')';
576
 
577
					}
578
					return false;
579
				} elseif ($missingParentAction == 'delete') {
580
					$Model->deleteAll(array($Model->primaryKey => array_flip($missingParents)));
581
				} else {
582
					$Model->updateAll(array($parent => $missingParentAction), array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)));
583
				}
584
			}
585
			$count = 1;
586
			foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey), 'order' => $left)) as $array) {
587
				$Model->id = $array[$Model->alias][$Model->primaryKey];
588
				$lft = $count++;
589
				$rght = $count++;
590
				$Model->save(array($left => $lft, $right => $rght), array('callbacks' => false));
591
			}
592
			foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
593
				$Model->create();
594
				$Model->id = $array[$Model->alias][$Model->primaryKey];
595
				$this->_setParent($Model, $array[$Model->alias][$parent]);
596
			}
597
		} else {
598
			$db =& ConnectionManager::getDataSource($Model->useDbConfig);
599
			foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
600
				$path = $this->getpath($Model, $array[$Model->alias][$Model->primaryKey]);
601
				if ($path == null || count($path) < 2) {
602
					$parentId = null;
603
				} else {
604
					$parentId = $path[count($path) - 2][$Model->alias][$Model->primaryKey];
605
				}
606
				$Model->updateAll(array($parent => $db->value($parentId, $parent)), array($Model->escapeField() => $array[$Model->alias][$Model->primaryKey]));
607
			}
608
		}
609
		return true;
610
	}
611
/**
612
 * Reorder method.
613
 *
614
 * Reorders the nodes (and child nodes) of the tree according to the field and direction specified in the parameters.
615
 * This method does not change the parent of any node.
616
 *
617
 * Requires a valid tree, by default it verifies the tree before beginning.
618
 *
619
 * @param AppModel $Model
620
 * @param array $options
621
 * @return boolean true on success, false on failure
622
 */
623
	function reorder(&$Model, $options = array()) {
624
		$options = array_merge(array('id' => null, 'field' => $Model->displayField, 'order' => 'ASC', 'verify' => true), $options);
625
		extract($options);
626
		if ($verify && !$this->verify($Model)) {
627
			return false;
628
		}
629
		$verify = false;
630
		extract($this->settings[$Model->alias]);
631
		$fields = array($Model->primaryKey, $field, $left, $right);
632
		$sort = $field . ' ' . $order;
633
		$nodes = $this->children($Model, $id, true, $fields, $sort, null, null, $recursive);
634
 
635
		if ($nodes) {
636
			foreach ($nodes as $node) {
637
				$id = $node[$Model->alias][$Model->primaryKey];
638
				$this->moveDown($Model, $id, true);
639
				if ($node[$Model->alias][$left] != $node[$Model->alias][$right] - 1) {
640
					$this->reorder($Model, compact('id', 'field', 'order', 'verify'));
641
				}
642
			}
643
		}
644
		return true;
645
	}
646
/**
647
 * Remove the current node from the tree, and reparent all children up one level.
648
 *
649
 * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted
650
 * after the children are reparented.
651
 *
652
 * @param AppModel $Model
653
 * @param mixed $id The ID of the record to remove
654
 * @param boolean $delete whether to delete the node after reparenting children (if any)
655
 * @return boolean true on success, false on failure
656
 * @access public
657
 */
658
	function removefromtree(&$Model, $id = null, $delete = false) {
659
		if (is_array($id)) {
660
			extract (array_merge(array('id' => null), $id));
661
		}
662
		extract($this->settings[$Model->alias]);
663
 
664
		list($node) = array_values($Model->find('first', array(
665
			'conditions' => array($scope, $Model->escapeField() => $id),
666
			'fields' => array($Model->primaryKey, $left, $right, $parent),
667
			'recursive' => $recursive
668
		)));
669
 
670
		if ($node[$right] == $node[$left] + 1) {
671
			if ($delete) {
672
				return $Model->delete($id);
673
			} else {
674
				$Model->id = $id;
675
				return $Model->saveField($parent, null);
676
			}
677
		} elseif ($node[$parent]) {
678
			list($parentNode) = array_values($Model->find('first', array(
679
				'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
680
				'fields' => array($Model->primaryKey, $left, $right),
681
				'recursive' => $recursive
682
			)));
683
		} else {
684
			$parentNode[$right] = $node[$right] + 1;
685
		}
686
 
687
		$db =& ConnectionManager::getDataSource($Model->useDbConfig);
688
		$Model->updateAll(array($parent => $db->value($node[$parent], $parent)), array($parent => $node[$Model->primaryKey]));
689
		$this->__sync($Model, 1, '-', 'BETWEEN ' . ($node[$left] + 1) . ' AND ' . ($node[$right] - 1));
690
		$this->__sync($Model, 2, '-', '> ' . ($node[$right]));
691
		$Model->id = $id;
692
 
693
		if ($delete) {
694
			$Model->updateAll(
695
				array(
696
					$Model->escapeField($left) => 0,
697
					$Model->escapeField($right) => 0,
698
					$Model->escapeField($parent) => null
699
				),
700
				array($Model->escapeField() => $id)
701
			);
702
			return $Model->delete($id);
703
		} else {
704
			$edge = $this->__getMax($Model, $scope, $right, $recursive);
705
			if ($node[$right] == $edge) {
706
				$edge = $edge - 2;
707
			}
708
			$Model->id = $id;
709
			return $Model->save(
710
				array($left => $edge + 1, $right => $edge + 2, $parent => null),
711
				array('callbacks' => false)
712
			);
713
		}
714
	}
715
/**
716
 * Check if the current tree is valid.
717
 *
718
 * Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message)
719
 *
720
 * @param AppModel $Model
721
 * @return mixed true if the tree is valid or empty, otherwise an array of (error type [index, node],
722
 *  [incorrect left/right index,node id], message)
723
 * @access public
724
 */
725
	function verify(&$Model) {
726
		extract($this->settings[$Model->alias]);
727
		if (!$Model->find('count', array('conditions' => $scope))) {
728
			return true;
729
		}
730
		$min = $this->__getMin($Model, $scope, $left, $recursive);
731
		$edge = $this->__getMax($Model, $scope, $right, $recursive);
732
		$errors =  array();
733
 
734
		for ($i = $min; $i <= $edge; $i++) {
735
			$count = $Model->find('count', array('conditions' => array(
736
				$scope, 'OR' => array($Model->escapeField($left) => $i, $Model->escapeField($right) => $i)
737
			)));
738
			if ($count != 1) {
739
				if ($count == 0) {
740
					$errors[] = array('index', $i, 'missing');
741
				} else {
742
					$errors[] = array('index', $i, 'duplicate');
743
				}
744
			}
745
		}
746
		$node = $Model->find('first', array('conditions' => array($scope, $Model->escapeField($right) . '< ' . $Model->escapeField($left)), 'recursive' => 0));
747
		if ($node) {
748
			$errors[] = array('node', $node[$Model->alias][$Model->primaryKey], 'left greater than right.');
749
		}
750
 
751
		$Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
752
			'className' => $Model->alias,
753
			'foreignKey' => $parent,
754
			'fields' => array($Model->primaryKey, $left, $right, $parent)
755
		))));
756
 
757
		foreach ($Model->find('all', array('conditions' => $scope, 'recursive' => 0)) as $instance) {
758
			if (is_null($instance[$Model->alias][$left]) || is_null($instance[$Model->alias][$right])) {
759
				$errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
760
					'has invalid left or right values');
761
			} elseif ($instance[$Model->alias][$left] == $instance[$Model->alias][$right]) {
762
				$errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
763
					'left and right values identical');
764
			} elseif ($instance[$Model->alias][$parent]) {
765
				if (!$instance['VerifyParent'][$Model->primaryKey]) {
766
					$errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
767
						'The parent node ' . $instance[$Model->alias][$parent] . ' doesn\'t exist');
768
				} elseif ($instance[$Model->alias][$left] < $instance['VerifyParent'][$left]) {
769
					$errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
770
						'left less than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
771
				} elseif ($instance[$Model->alias][$right] > $instance['VerifyParent'][$right]) {
772
					$errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
773
						'right greater than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
774
				}
775
			} elseif ($Model->find('count', array('conditions' => array($scope, $Model->escapeField($left) . ' <' => $instance[$Model->alias][$left], $Model->escapeField($right) . ' >' => $instance[$Model->alias][$right]), 'recursive' => 0))) {
776
				$errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'The parent field is blank, but has a parent');
777
			}
778
		}
779
		if ($errors) {
780
			return $errors;
781
		}
782
		return true;
783
	}
784
/**
785
 * Sets the parent of the given node
786
 *
787
 * The force parameter is used to override the "don't change the parent to the current parent" logic in the event
788
 * of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this
789
 * method could be private, since calling save with parent_id set also calls setParent
790
 *
791
 * @param AppModel $Model
792
 * @param mixed $parentId
793
 * @return boolean true on success, false on failure
794
 * @access protected
795
 */
796
	function _setParent(&$Model, $parentId = null, $created = false) {
797
		extract($this->settings[$Model->alias]);
798
		list($node) = array_values($Model->find('first', array(
799
			'conditions' => array($scope, $Model->escapeField() => $Model->id),
800
			'fields' => array($Model->primaryKey, $parent, $left, $right),
801
			'recursive' => $recursive
802
		)));
803
		$edge = $this->__getMax($Model, $scope, $right, $recursive, $created);
804
 
805
		if (empty ($parentId)) {
806
			$this->__sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
807
			$this->__sync($Model, $node[$right] - $node[$left] + 1, '-', '> ' . $node[$left], $created);
808
		} else {
809
			$parentNode = array_values($Model->find('first', array(
810
				'conditions' => array($scope, $Model->escapeField() => $parentId),
811
				'fields' => array($Model->primaryKey, $left, $right),
812
				'recursive' => $recursive
813
			)));
814
 
815
			if (empty($parentNode) || empty($parentNode[0])) {
816
				return false;
817
			}
818
			$parentNode = $parentNode[0];
819
 
820
			if (($Model->id == $parentId)) {
821
				return false;
822
 
823
			} elseif (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
824
				return false;
825
			}
826
			if (empty ($node[$left]) && empty ($node[$right])) {
827
				$this->__sync($Model, 2, '+', '>= ' . $parentNode[$right], $created);
828
				$result = $Model->save(
829
					array($left => $parentNode[$right], $right => $parentNode[$right] + 1, $parent => $parentId),
830
					array('validate' => false, 'callbacks' => false)
831
				);
832
				$Model->data = $result;
833
			} else {
834
				$this->__sync($Model, $edge - $node[$left] +1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
835
				$diff = $node[$right] - $node[$left] + 1;
836
 
837
				if ($node[$left] > $parentNode[$left]) {
838
					if ($node[$right] < $parentNode[$right]) {
839
						$this->__sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
840
						$this->__sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
841
					} else {
842
						$this->__sync($Model, $diff, '+', 'BETWEEN ' . $parentNode[$right] . ' AND ' . $node[$right], $created);
843
						$this->__sync($Model, $edge - $parentNode[$right] + 1, '-', '> ' . $edge, $created);
844
					}
845
				} else {
846
					$this->__sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
847
					$this->__sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
848
				}
849
			}
850
		}
851
		return true;
852
	}
853
/**
854
 * get the maximum index value in the table.
855
 *
856
 * @param AppModel $Model
857
 * @param string $scope
858
 * @param string $right
859
 * @return int
860
 * @access private
861
 */
862
	function __getMax($Model, $scope, $right, $recursive = -1, $created = false) {
863
		$db =& ConnectionManager::getDataSource($Model->useDbConfig);
864
		if ($created) {
865
			if (is_string($scope)) {
866
				$scope .= " AND {$Model->alias}.{$Model->primaryKey} <> ";
867
				$scope .= $db->value($Model->id, $Model->getColumnType($Model->primaryKey));
868
			} else {
869
				$scope['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
870
			}
871
		}
872
		list($edge) = array_values($Model->find('first', array(
873
			'conditions' => $scope,
874
			'fields' => $db->calculate($Model, 'max', array($right)),
875
			'recursive' => $recursive
876
		)));
877
		return (empty($edge[$right])) ? 0 : $edge[$right];
878
	}
879
/**
880
 * get the minimum index value in the table.
881
 *
882
 * @param AppModel $Model
883
 * @param string $scope
884
 * @param string $right
885
 * @return int
886
 * @access private
887
 */
888
	function __getMin($Model, $scope, $left, $recursive = -1) {
889
		$db =& ConnectionManager::getDataSource($Model->useDbConfig);
890
		list($edge) = array_values($Model->find('first', array(
891
			'conditions' => $scope,
892
			'fields' => $db->calculate($Model, 'min', array($left)),
893
			'recursive' => $recursive
894
		)));
895
		return (empty($edge[$left])) ? 0 : $edge[$left];
896
	}
897
/**
898
 * Table sync method.
899
 *
900
 * Handles table sync operations, Taking account of the behavior scope.
901
 *
902
 * @param AppModel $Model
903
 * @param integer $shift
904
 * @param string $direction
905
 * @param array $conditions
906
 * @param string $field
907
 * @access private
908
 */
909
	function __sync(&$Model, $shift, $dir = '+', $conditions = array(), $created = false, $field = 'both') {
910
		$ModelRecursive = $Model->recursive;
911
		extract($this->settings[$Model->alias]);
912
		$Model->recursive = $recursive;
913
 
914
		if ($field == 'both') {
915
			$this->__sync($Model, $shift, $dir, $conditions, $created, $left);
916
			$field = $right;
917
		}
918
		if (is_string($conditions)) {
919
			$conditions = array("{$Model->alias}.{$field} {$conditions}");
920
		}
921
		if (($scope != '1 = 1' && $scope !== true) && $scope) {
922
			$conditions[] = $scope;
923
		}
924
		if ($created) {
925
			$conditions['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
926
		}
927
		$Model->updateAll(array($Model->alias . '.' . $field => $Model->escapeField($field) . ' ' . $dir . ' ' . $shift), $conditions);
928
		$Model->recursive = $ModelRecursive;
929
	}
930
}
931
?>