BEdita API doc | 4-cactus
  • Class
  • Tree
  • Deprecated
  • Download

Classes

  • Addon
  • AddressbookController
  • AddressbookShell
  • AdminController
  • Alias
  • Annotation
  • ApiAuthComponent
  • ApiBaseController
  • ApiFormatterComponent
  • ApiUploadComponent
  • ApiValidatorComponent
  • AppController
  • AppError
  • AppHelper
  • Application
  • AppModel
  • Area
  • AreasController
  • Audio
  • AuthenticationsController
  • BannedIp
  • BEAppModel
  • BEAppObjectModel
  • BeAuthComponent
  • BeAuthFacebookComponent
  • BeAuthGoogleComponent
  • BeAuthTwitterComponent
  • BeCallbackManager
  • BeConfigure
  • BeCustomPropertyComponent
  • BeditaAnnotationModel
  • BeditaBaseShell
  • BeditaCollectionModel
  • BeditaContentModel
  • BeditaExportFilter
  • BeditaImportFilter
  • BeditaObjectModel
  • BeditaProductModel
  • BeditaShell
  • BeditaSimpleObjectModel
  • BeditaSimpleStreamModel
  • BeditaStreamModel
  • BeEmbedFlashHelper
  • BeEmbedHtml5Helper
  • BeEmbedMediaHelper
  • BeErrorCode
  • BeExceptionHandler
  • BEFile
  • BeFileHandlerComponent
  • BeFormHelper
  • BeFrontHelper
  • BeHashComponent
  • BeHtmlHelper
  • BeLangTextComponent
  • BeLib
  • BeMailComponent
  • BEObject
  • BeObjectCache
  • BePaginatorToolbarHelper
  • BeSchema
  • BeSecurityComponent
  • BeSystem
  • BeSystemComponent
  • BeThumb
  • BeTimeHelper
  • BeToolbarHelper
  • BeTreeComponent
  • BeTreeHelper
  • BeUploadToObjComponent
  • BeurlHelper
  • BeVimeoComponent
  • BeYoutubeComponent
  • BuildFilterBehavior
  • CacheableBehavior
  • CacheShell
  • CallbackBehavior
  • CaptchaComponent
  • Caption
  • CaptionsBehavior
  • Card
  • CardsImportFilter
  • Category
  • CleanupDataTask
  • CleanupTask
  • Comment
  • CommentsController
  • CompactResultBehavior
  • Content
  • CreateIndexFieldsBehavior
  • DataShell
  • DataTransfer
  • DateItem
  • DbadminShell
  • DeleteDependentObjectBehavior
  • DeleteObjectBehavior
  • DeployShell
  • Document
  • DocumentsController
  • DumpModel
  • EditorialContentsShell
  • EditorNote
  • Event
  • EventLog
  • EventsController
  • FilesController
  • ForeignDependenceSaveBehavior
  • FrontendController
  • FrontendShell
  • GalleriesController
  • Gallery
  • GeoTag
  • GettextShell
  • Git
  • GravatarHelper
  • Group
  • HashJob
  • History
  • HomeController
  • Image
  • ImageInfoHelper
  • JsonExportFilter
  • JsonImportFilter
  • JsonView
  • LangText
  • Link
  • MailGroup
  • MailGroupCard
  • MailJob
  • MailLog
  • MailMessage
  • MailShell
  • MailTemplate
  • Mask
  • MediaShell
  • MigrateDumpModel
  • MigrateShell
  • Migration
  • MigrationBase
  • MigrationDateItemsShell
  • Module
  • ModulesController
  • ModuleShell
  • MultimediaController
  • NewsController
  • NewsletterController
  • NewsletterShell
  • NotifyBehavior
  • ObjectEditor
  • ObjectProperty
  • ObjectRelation
  • ObjectType
  • ObjectUser
  • PagesController
  • Permission
  • PermissionModule
  • PermsHelper
  • Product
  • Property
  • PropertyOption
  • PublicationShell
  • RedisShell
  • RelationCheck
  • RelationRepair
  • RelationShell
  • RelationStats
  • RemoveDummyNameBehavior
  • ResponseHandlerComponent
  • RestClientModel
  • Revision
  • RevisionObjectBehavior
  • SearchText
  • SearchTextSaveBehavior
  • Section
  • SectionDummy
  • SessionFilterComponent
  • SessionFilterHelper
  • ShortNews
  • SmartyView
  • SoapClientModel
  • SplitterSql
  • StatisticsController
  • Stream
  • StreamLog
  • StreamsController
  • Svn
  • TagsController
  • ThemeSmartyView
  • ThumbnailHelper
  • ThumbShell
  • TransactionComponent
  • TransactionFS
  • TranslationsController
  • Tree
  • TrHelper
  • User
  • UserProperty
  • UsersController
  • Utility
  • Version
  • Video
  • VimeoHelper
  • WebmarksController
  • XmlExportFilter
  • XmlImportFilter
  • XmlJsonConverter
  • XmlView
  • YoutubeHelper

Interfaces

  • ApiAuthInterface
  • MediaProviderInterface
  • UploadableInterface

Exceptions

  • BeditaAjaxException
  • BEditaAllowURLException
  • BeditaBadRequestException
  • BeditaConflictException
  • BEditaDeleteStreamObjException
  • BeditaException
  • BEditaFileExistException
  • BeditaForbiddenException
  • BeditaFrontAccessException
  • BeditaHashException
  • BEditaInfoException
  • BeditaInternalErrorException
  • BEditaIOException
  • BeditaLengthRequiredException
  • BeditaMailException
  • BEditaMediaProviderException
  • BeditaMethodNotAllowedException
  • BEditaMIMEException
  • BeditaNotFoundException
  • BeditaNotImplementedException
  • BeditaPublicationException
  • BeditaRuntimeException
  • BEditaSaveStreamObjException
  • BeditaServiceUnavailableException
  • BeditaUnauthorizedException
  • BEditaUploadPHPException
  • BEditaURLException
   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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 
<?php
/*-----8<--------------------------------------------------------------------
 *
 * BEdita - a semantic content management framework
 *
 * Copyright 2008-2016 ChannelWeb Srl, Chialab Srl
 *
 * This file is part of BEdita: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * BEdita is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with BEdita (see LICENSE.LGPL).
 * If not, see <http://gnu.org/licenses/lgpl-3.0.html>.
 *
 *------------------------------------------------------------------->8-----
 */

/**
 * Tree operations model
 */
class Tree extends BEAppModel
{

    /**
     * Name of event dispatched when an object's parents are updated.
     *
     * @var string
     */
    const EVENT_PARENTS_UPDATED = 'Tree.parentsUpdated';

    /**
     * Name of event dispatched when a node's children are updated.
     *
     * @var string
     */
    const EVENT_CHILDREN_UPDATED = 'Tree.childrenUpdated';

    public $primaryKey = "object_path";
    
    /**
     * Object cache 
     * 
     */
    protected $BeObjectCache = null;

    /**
     * {@inheritDoc}
     */
    public $validate = array(
        'id' => array(
            'rule' => 'isUniqueSection',
            'message' => 'Ubiquitous sections/publications are not allowed',
        ),
    );

    public function  __construct() {
        parent::__construct();
        if (!BACKEND_APP && Configure::read('objectCakeCache') && !Configure::read('staging')) {
            $this->BeObjectCache = BeLib::getObject('BeObjectCache');
        }
    }

    /**
     * Custom validation rule to verify that a branch node (section, publication)
     * is not already on the tree.
     * A section must stay only in one tree node.
     *
     * @param array $check The array to validate
     * @return bool
     */
    public function isUniqueSection($check) {
        if (empty($check) || empty($check['id'])) {
            return false;
        }

        $objectTypeId = ClassRegistry::init('BEObject')->findObjectTypeId($check['id']);
        $objectType = Configure::read('objectTypes.' . $objectTypeId . '.name');
        if (!in_array($objectType, array('section', 'area'))) {
            return true;
        }

        return $this->isUnique($check);
    }

    /**
     * check object_path and parent_path, avoid object is parent or ancestor of itself
     *
     * @return boolean
     */
    public function beforeSave() {

        // check object_path and parent_path consistency if they are defined (no recursion)
        $pathToCheck = array("object_path", "parent_path");
        foreach ($pathToCheck as $path) {
            if (isset($this->data["Tree"][$path])) {

                // no empty path permitted
                if (empty($this->data["Tree"][$path])) {
                    return false;
                }

                // check for duplicates ids in path and stop save if find it
                $objectIds = explode("/", trim($this->data["Tree"][$path], "/"));
                if (!empty($objectIds)) {
                    $countValues = array_count_values($objectIds);
                    $sumCountValues = array_sum($countValues);
                    if (count(array_unique($objectIds)) < $sumCountValues) {
                        return false;
                    }
                }
            }
        }

        if (!empty($this->data["Tree"]["id"])) {
            // avoid object is parent of itself
            if (isset($this->data["Tree"]["parent_id"]) && $this->data["Tree"]["id"] == $this->data["Tree"]["parent_id"]) {
                return false;
            }

            // avoid object is ancestor of itself
            if (isset($this->data["Tree"]["parent_path"]) && $this->data["Tree"]["parent_path"] != "/") {
                $parents = explode("/", $this->data["Tree"]["parent_path"]);
                foreach ($parents as $parent_id) {
                    if ($this->data["Tree"]["id"] == $parent_id) {
                        return false;
                    }
                }
            }
        }
        if (!empty($this->data["Tree"]) && empty($this->data["Tree"]["area_id"]) && !empty($this->data["Tree"]["object_path"])) {
            $this->data["Tree"]["area_id"] = $this->getAreaIdByPath($this->data["Tree"]["object_path"]);
        }
        return true;
    }

    /**
     * get parent or array of parents
     *
     * @param integer $id
     * @param integer $area_id, publication id: if defined search parent only inside the publication
     *
     * @return mixed    integer, if only one parent found
     *                  array, if two or more parents found
     *                  false, error or none parent found
     */
    public function getParent($id, $area_id=null, $status = array()) {
        if (empty($id)) {
            return false;
        }
        $conditions["Tree.id"] = $id;
        if (!empty($area_id)) {
            $conditions["Tree.area_id"] = $area_id;
        }

        if (!empty($status)) {
            // bind BEObject to get only parents with status in $status
            $this->bindModel(array(
                'belongsTo' => array(
                    'BEObject'=> array(
                        'foreignKey' => 'parent_id'
                    )
                )
            ));

            $conditions['BEObject.status'] = $status;
        }

        $ret = $this->find("all", array(
                "conditions" => $conditions,
                "fields" => array("parent_id")
            )
        );

        if(!$ret) {
            return false;
        }

        if(!count($ret)) {
            return false ;
        } else if (count($ret) == 1) {
            return $ret[0]['Tree']['parent_id'] ;
        } else {
            $tmp = array() ;
            for($i=0; $i < count($ret) ; $i++) {
                $tmp[] = $ret[$i]['Tree']['parent_id'] ;
            }

            return $tmp ;
        }
    }

    /**
     * Array of object $id tree parents objects
     *
     * If `$useCache` is true it will try to read/write from/to cache 
     *
     * @param int|null $id The child id
     * @param int|null $area_id The publication (area) id
     * @param array $status An array of object status that parent must have
     * @param bool $useCache If it has to use cache (true default)
     * @return array, parent ids (may be empty)
     */
    public function getParents($id = null, $area_id=null, $status = array(), $useCache = true) {
        if ($id === null) {
            return array();
        }

        $cacheOpts = array($area_id, $status);
        if ($this->BeObjectCache && $useCache) {
            $cachedValue = $this->BeObjectCache->read($id, $cacheOpts, 'parents');
            if ($cachedValue !== false) {
                return $cachedValue;
            }
        }

        $parents = $this->getParent($id, $area_id, $status) ;
        if ($parents === false) {
            $parents = array();
        } elseif (!is_array($parents)) {
            $parents = array($parents);
        }

        if ($this->BeObjectCache && $useCache) {
            $this->BeObjectCache->write($id, $cacheOpts, $parents, 'parents');
        }
        return $parents;
    }

    /**
     * Update tree position of object $id with new $destination array
     *
     * To update tree:
     * - all parents are taken
     * - ids in all parents that missing from $destination are removed
     * - ids in $destination that missing from all parents are added
     *
     * With $options you can limit the parents taken
     *
     * Possible values are:
     * - `area_id` to limit parents to some publication.
     * - `status` to limit parents with specific status.
     * - `mantain_hidden_branch` if hidden branches are to mantain. Default true.
     *
     * @param int $id The object id
     * @param array|int $destination An array of parents or a parent.
     * @param array $options Options.
     * @return void
     * @throws BeditaException If $id is an area or a section with too much destination.
     * @throws BeditaBadRequestException If errors happen moving a section.
     */
    public function updateTree($id, $destination, array $options = array()) {
        $options += array(
            'area_id' => null,
            'status' => array(),
            'mantain_hidden_branch' => true
        );
        if (!is_array($destination)) {
            $destination = (empty($destination))? array() : array($destination);
        }

        $objectTypeId = ClassRegistry::init('BEObject')->field('object_type_id', array('BEObject.id' => $id));
        if ($objectTypeId == Configure::read('objectTypes.area.id')) {
            throw new BeditaBadRequestException(__('Publication cannot be moved to destination', true));
        }

        $isSection = $objectTypeId == Configure::read('objectTypes.section.id');
        
        $excludeFromTreeIds = Configure::read('excludeFromTreeIds');
        if ($options['mantain_hidden_branch'] === true && !empty($excludeFromTreeIds)) {
            foreach ($excludeFromTreeIds as $excludeFromTreeId) {
                $result = $this->find('list', array(
                    'fields' => array('parent_id'),
                    'conditions' => array(
                        'id' => $id,
                        'object_path LIKE' => '%/' . $excludeFromTreeId . '/%'
                    )
                ));
                if (!empty($result)) {
                    $destination = array_merge($destination, $result);
                }
            }
        }

        // if section with none or too much destination
        if ($isSection && count($destination) !== 1) {
            throw new BeditaBadRequestException(__('Section can have just one parent.', true));
        }

        $currParents = $this->getParents($id, $options['area_id'], $options['status'], false);

        // remove
        $remove = array_diff($currParents, $destination);

        // section to move
        if ($isSection && !empty($remove)) {
            $newParent = current($destination);
            $oldParent = current($currParents);
            if (!$this->move($newParent, $oldParent, $id)) {
                throw new BeditaException(__('Failing to move section', true));
            }

            return;
        }

        foreach ($remove as $parent_id) {
            $this->removeChildWorker($id, $parent_id);
            $this->dispatchUpdatedTreeEvent($parent_id, static::EVENT_CHILDREN_UPDATED);
        }
        // insert
        $add = array_diff($destination, $currParents) ;
        foreach ($add as $parent_id) {
            $this->appendChildWorker($id, $parent_id);
            $this->dispatchUpdatedTreeEvent($parent_id, static::EVENT_CHILDREN_UPDATED);
        }

        $this->dispatchUpdatedTreeEvent($id, static::EVENT_PARENTS_UPDATED);
    }

    /**
     * Return id of publication that contains the section, by id
     *
     * @param int $id
     * @return int
     */
    public function getRootForSection($id) {
        $area_id = $this->field("area_id", array("id"=>$id));
        return $area_id;
    }

    /**
     * Append an object to a parent.
     *
     * @see Tree::appendChildWorker()
     *
     * @param int $id Child object's ID.
     * @param int|null $idParent Parent object's ID (`null` for roots).
     * @param int|null $priority Priority in children's list (`null` to append as last child).
     * @return bool
     */
    public function appendChild($id, $idParent = null, $priority = null) {
        $res = $this->appendChildWorker($id, $idParent, $priority);

        $this->dispatchUpdatedTreeEvent($id, static::EVENT_PARENTS_UPDATED);
        $this->dispatchUpdatedTreeEvent($idParent, static::EVENT_CHILDREN_UPDATED);

        return $res;
    }

    /**
     * append an object to a parent in tree
     *
     * @param int $id object id
     * @param int $idParent parent object id
     * @param int $priority if not passed append as last child else use passed position
     * @return boolean
     */
    protected function appendChildWorker($id, $idParent = null, $priority = null)
    {
        // avoid to append item to itself
        if ($id == $idParent) {
            return false;
        }
        // root
        if (empty($idParent)) {
            $data["Tree"] = array(
                "id" => $id,
                "area_id" => $id,
                "object_path" => "/".$id,
                "parent_path" => "/",
                "priority" => 1
            );
        } else {
            $parentPath = $this->field("object_path", array("id" => $idParent));
            if ($parentPath === false) {
                $this->log('Error: object_path to use as parentPath not found for object id: ' . $idParent);
                $this->log('Tree->appendChildWorker(): no object_path for tree id ' . $idParent, 'tree');

                return false;
            }
            $area_id = $this->getAreaIdByPath($parentPath);
            if (empty($priority)) {
                $maxPriority = $this->field("priority", array("parent_id" => $idParent), "priority DESC");
                $priority = (!empty($maxPriority))? $maxPriority + 1 : 1;
            }

            $data["Tree"] = array(
                "id" => $id,
                "area_id" => $area_id,
                "parent_id" => $idParent,
                "object_path" => $parentPath . "/".$id,
                "parent_path" => $parentPath,
                "priority" => $priority
            );
        }

        $ret = $this->save($data);

        return (($ret === false)?false:true) ;
    }

    /**
     * Return id of publication by path
     *
     * @param string $path
     * @return int
     */
    public function getAreaIdByPath($path) {
        $pathArr = explode("/", trim($path, "/"));
        return $pathArr[0];
    }

    /**
     * move up or down a leaf tree inside a branch
     *
     * @param int $id object id to move
     * @param int $idParent parent object (branch)
     * @param boolean $up true move up (priority - 1), false move down (priority + 1)
     * @return boolean
     */
    public function movePriority($id, $idParent, $up=true) {
        $treeRow = $this->find("first", array(
            "conditions" => array("id" => $id, "parent_id" => $idParent)
        ));

        if (empty($treeRow)) {
            return false;
        }

        $origPriority = $treeRow["Tree"]["priority"];

        if ($up) {
            $op = " < ";
            $dir = "DESC";
        } else {
            $op = " > ";
            $dir = "ASC";
        }
        $op = ($up)? " < " : " > ";
        $otherRow = $this->find("first", array(
            "conditions" => array("parent_id" => $idParent, "priority" . $op . $origPriority),
            "limit" => 1,
            "order" => "priority " . $dir
        ));

        if (empty($otherRow["Tree"]["priority"])) {
            return false;
        }

        $treeRow["Tree"]["priority"] = $otherRow["Tree"]["priority"];
        $otherRow["Tree"]["priority"] = $origPriority;

        if (!$this->save($treeRow)) {
            return false;
        }
        $this->create();
        if (!$this->save($otherRow)) {
            return false;
        }

        return true;
    }

    /**
     * move up a leaf tree inside a branch
     *
     * @param int $id to move
     * @param int $idParent parent object (branch)
     * @return boolean
     */
    public function movePriorityUp($id, $idParent) {
        return $this->movePriority($id, $idParent);
    }

    /**
     * move down a leaf tree inside a branch
     *
     * @param int $id to move
     * @param int $idParent parent object (branch)
     * @return boolean
     */
    public function movePriorityDown($id, $idParent) {
        return $this->movePriority($id, $idParent, false);
    }

    /**
     * Remove a leaf node from a tree.
     *
     * @see Tree::removeChildWorker()
     *
     * @param int $id Leaf node ID.
     * @param int $idParent Parent node ID.
     * @return bool
     */
    public function removeChild($id, $idParent) {
        $res = $this->removeChildWorker($id, $idParent);

        $this->dispatchUpdatedTreeEvent($id, static::EVENT_PARENTS_UPDATED);
        $this->dispatchUpdatedTreeEvent($idParent, static::EVENT_CHILDREN_UPDATED);

        return $res;
    }

    /**
     * remove a leaf tree from a branch
     *
     * @param int $id to remove
     * @param int $idParent parent object (branch)
     * @return boolean
     */
    protected function removeChildWorker($id, $idParent) {
        $ret = $this->deleteAll(array("id" => $id, "parent_id" => $idParent));
        return (($ret === false)?false:true) ;
    }

    /**
     * set position for a leaf tree in a branch
     *
     * @param int $id to move
     * @param int $idParent parent object (branch)
     * @return boolean
     */
    public function setPriority($id, $priority, $idParent) {
        $row = $this->find("first", array(
            "conditions" => array(
                "id" => $id,
                "parent_id" => $idParent
            )
        ));
        if (empty($row["Tree"])) {
            return false;
        }
        $row["Tree"]["priority"] = $priority;
        $ret =  $this->save($row);
        return (($ret === false)?false:true) ;
    }


    /**
     * object position in a tree branch 
     *
     * @param int $id object id
     * @param int $idParent parent object (branch) id
     * @return int
     */
    public function getPriority($id, $idParent) {
        return $this->field("priority", 
                array("id" => $id, "parent_id" => $idParent));
    }
    
    
    /**
     * Move branch to another parent.
     *
     * @param int $idNewParent The new parent id.
     * @param int $idOldParent The old parent id.
     * @param int $id The object id to move.
     * @return bool
     */
    public function move($idNewParent, $idOldParent, $id) {
        // avoid recursive move (item inside itself)
        if ($id == $idNewParent) {
            return false;
        }
        // Verify that new parent is not a descendant on the tree to move
        if ($this->isParent($id, $idNewParent)) {
            return false;
        }

        $rowToMove = $this->find('first', array(
            'conditions' => array(
                'id' => $id,
                'parent_id' => $idOldParent
            )
        ));

        $newParentRow = $this->find('first', array(
            'conditions' => array(
                'id' => $idNewParent
            )
        ));

        $newParentPath = $newParentRow['Tree']['object_path'];
        $newPath = $newParentPath . '/' . $rowToMove['Tree']['id'];
        $oldPath = $rowToMove['Tree']['object_path'];

        $children = $this->find('all', array(
            'conditions' => array('object_path LIKE' => $oldPath.'/%')
        ));

        if (!$this->delete($rowToMove['Tree']['object_path'])) {
            return false;
        }

        $area_id = $this->getAreaIdByPath($newPath);
        $rowToMove['Tree']['parent_path'] = $newParentPath;
        $rowToMove['Tree']['object_path'] = $newPath;
        $rowToMove['Tree']['parent_id'] = $idNewParent;
        $rowToMove['Tree']['area_id'] = $area_id;

        $maxBranchPriority = $this->field('priority', array('parent_id' => $idNewParent), 'priority DESC');
        $rowToMove['Tree']['priority'] = empty($maxBranchPriority) ? 1 : $maxBranchPriority + 1;

        $this->create();
        if (!$this->save($rowToMove)) {
            return false;
        }

        foreach ($children as $child) {
            if (!$this->delete($child['Tree']['object_path'])) {
                return false;
            }
            $child['Tree']['parent_path'] = str_replace($oldPath, $newPath, $child['Tree']['parent_path']);
            $child['Tree']['object_path'] = str_replace($oldPath . '/', $newPath . '/', $child['Tree']['object_path']);
            $child['Tree']['area_id'] = $area_id;
            $this->create();
            if (!$this->save($child)) {
                return false;
            }
            
            $this->dispatchUpdatedTreeEvent($child['Tree']['parent_id'], static::EVENT_CHILDREN_UPDATED);
        }
        
        $this->dispatchUpdatedTreeEvent($id, static::EVENT_PARENTS_UPDATED);

        return true;
    }

    /**
     * get all tree roots objects (publications)
     *
     * @param  int $userid
     * @param  mixed $status string or array of status
     * @param  array  $filter filter options see BEAppModel::findObjects
     * @param  array  $expandBranch array of branch ids of which roots have to expanded
     * @return array
     */
    public function getAllRoots($userid = null, $status = null, $filter = array(), $expandBranch = array()) {
        $filter['object_type_id'] = array(Configure::read('objectTypes.area.id'));
        $roots = $this->getAll(null, $userid, $status, $filter);
        if (!empty($expandBranch)) {
            // get root of $expandedBranch array
            foreach ($expandBranch as &$branchId) {
                $branchId = $this->getRootForSection($branchId);
            }
            $filter['object_type_id'][] = Configure::read('objectTypes.section.id');
            foreach ($roots as $key => $root) {
                if (in_array($root['id'], $expandBranch)) {
                    $res = $this->getAll($root['id'], $userid, $status, $filter);
                    $roots[$key] = $res[0];
                }
            }
        }
        return $roots;
    }

    /**
     * Get Tree where 'id' (if it passed) has to be tree root
     * If it's a section id then an empty array is returned
     * @param integer $id       publication id. If null get all trees, one for every publication
     * @param string $userid    user. if null: no permission check (default); if '': guest user
     * @param string $status    only objs with this status
     * @param array $filter     see BEAppModel::findObjects
     * @return array every first level key is a publication
     */
    public function getAll($id = null, $userid = null, $status = null, $filter = array()) {
        // build tree
        $tree = array();

        $filter["Tree.*"] = "";
        if (!empty($id)) {
            $filter["Tree.area_id"] = $id;
        }

        $res = $this->findObjects(null, $userid, $status, $filter, "parent_path, priority, title", true, 1, null, true);

        $tree = $this->buildTree($res["items"]);
        return $tree ;
    }

    /**
     * Return a tree build for the items passed
     *
     * @param array $items
     * @return array
     */
    public function buildTree($items) {
        $tree = array();
        $roots = array();
        foreach ($items as $root) {

            $root['children']   = array() ;
            $roots[$root['id']] = &$root ;

            if(isset($root['parent_id']) && isset($roots[$root['parent_id']])) {
                $roots[$root['parent_id']]['children'][] = &$root ;
            } elseif (!empty($root['parent_id'])) {
                $this->putBranchInTree($tree, $root);
            } elseif ($root["object_type_id"] == Configure::read("objectTypes.area.id")) {
                $tree[] = &$root;
            }

            unset($root);
        }
        return $tree;
    }

    /**
     * search where have to stay $branch in $tree and put in
     * @param array $tree
     * @param array $branch to put in tree
     */
    private function putBranchInTree(&$tree, $branch) {
        foreach ($tree as $k => $t) {
            if (!empty($branch['parent_id']) && $t["id"] == $branch['parent_id']) {
                $tree[$k]['children'][] = $branch;
            } elseif (!empty($t['children'])) {
                $this->putBranchInTree($t['children'], $branch);
            }
        }
    }

    /**
     * check if $idParent is an ancestor
     *
     * @param integer $idParent
     * @param integer $id
     * @return boolean
     */
    public function isParent($idParent, $id) {
        $c = $this->find('count', array(
            'conditions' => array(
                'object_path LIKE' => '%/' . $idParent . '/%',
                'id' => $id
            ),
            'contain' => array(),
        ));

        if ($c === 0) {
            return false;
        }

        return true;
    }

    /**
     * Titles paths for branches related to $id passed
     * Returns array, each element is like:
     * [
     *     {
     *         'ids' => [223481, 274603], // array of integers
     *         'parentId' => 274603, // integer parent id
     *         'idsPath' => '/223481/274603', // string representing ids path
     *         'titles' => [
     *             223481 => 'Publication A', // publication title
     *             274603 => 'Section B' // section title
     *          ],
     *         'titlesPath' => 'Publication A > Section B' // string that concats titles
     *     },,
     *     // ...
     * ]
     *
     * @param int $id object id
     * @param array $hiddenBranchIds ids
     * @return array tree descriptive data
     */
    public function titlesPaths($id, $hiddenBranchIds = array()) {
        $result = array();
        $paths = $this->find('list', array(
            'fields' => 'Tree.parent_path',
            'conditions' => array('Tree.id' => $id)
        ));
        foreach ($paths as $path) {
            $ids = array_filter(explode("/", $path));
            $intersection = (!empty($hiddenBranchIds)) ? array_intersect($ids, $hiddenBranchIds) : array();
            if (!empty($intersection)) {
                $titles = ClassRegistry::init('BEObject')->find('list', array(
                    'fields' => array('BEObject.id', 'BEObject.title'),
                    'conditions' => array('BEObject.id' => $ids)
                ));
                $idsPath = $path;
                $titlesPath = '';
                foreach ($titles as $key => $value) {
                    if (!empty($titlesPath)) {
                        $titlesPath.= ' > ';
                    }
                    $titlesPath.= $value;
                }
                $result[] = array(
                    'ids' => $ids,
                    'parentId' => end(array_values($ids)),
                    'idsPath' => $idsPath,
                    'titles' => $titles,
                    'titlesPath' => $titlesPath
                );
            }
        }
        return $result;
    }

    /**
     * check if an object is on the tree
     *
     * @param integer $id
     * @param integer $area_id if defined check if the object is a descendant of a publication
     * @return boolean
     */
    public function isOnTree($id, $area_id = null, $status = array()) {
        $result = true;
        $cacheOpts = array($area_id, $status);
        if ($this->BeObjectCache) {
            $cachedValue = $this->BeObjectCache->read($id, $cacheOpts, 'is-on-tree');
            if ($cachedValue !== false) {
                return ($cachedValue == 1);
            }
        }
        $conditions['Tree.id'] = $id;
        if (!empty($area_id)) {
            $conditions['Tree.area_id'] = $area_id;
        }
        $joins = array();
        if (!empty($status)) {
            $conditions['BEObject.status'] = $status;
            $joins = array(
                array(
                    'table' => 'objects',
                    'alias' => 'BEObject',
                    'type' => 'inner',
                    'conditions' => array(
                        'BEObject.id = Tree.id'
                    )
                )
            );
        }
        $c = $this->find('count', array(
            'fields' => 'DISTINCT Tree.id',
            'conditions' => $conditions,
            'joins' => $joins
        ));
        if ($c === 0) {
            $result = false;
        }
        if ($this->BeObjectCache) {
            $resultToCache = ($result) ? 1 : 'no';
            $this->BeObjectCache->write($id, $cacheOpts, $resultToCache, 'is-on-tree');
        }
        return $result;
    }

    /**
     * Return a list of a count (based on $option['count']) of related object to $id that are on tree
     *
     *  $options can contain
     *  - 'area_id' to filter on publication
     *  - 'status' to filter on object status
     *  - 'count' (default false) to get a count or a list of object ids
     *  - 'relation' to filter on relation name
     *
     * @param int $id the object id
     * @param array $options
     * @return array|int
     */
    public function relatedObjectsOnTree($id, array $options = array()) {
        $options += array(
            'area_id' => null,
            'status' => array(),
            'count' => false,
            'relation' => null
        );
        if (!empty($options['area_id'])) {
            $conditions['Tree.area_id'] = $options['area_id'];
        }

        $objectRelationJoin = array(
            'table' => 'object_relations',
            'alias' => 'ObjectRelation',
            'type' => 'INNER',
            'conditions' => array(
                'ObjectRelation.object_id = Tree.id',
                'ObjectRelation.id' => $id
            )
        );
        if (!empty($options['relation'])) {
            $objectRelationJoin['conditions']['ObjectRelation.switch'] = $options['relation'];
        }

        $objectJoin = array();
        if (!empty($options['status'])) {
            $objectJoin = array(
                'table' => 'objects',
                'alias' => 'BEObject',
                'type' => 'INNER',
                'conditions' => array(
                    'BEObject.id = Tree.id',
                    'BEObject.status' => $options['status']
                )
            );
        }
        if ($options['count']) {
            $findType = 'count';
            $fields = 'DISTINCT Tree.id';
            $group = '';
        } else {
            $findType = 'list';
            $fields = array('Tree.id');
            $group = 'Tree.id';
        }

        $objects = $this->find($findType, array(
            'fields' => $fields,
            'conditions' => $conditions,
            'group' => $group,
            'joins' => array(
                $objectRelationJoin,
                $objectJoin
            )
        ));

        if (!$options['count']) {
            $objects = array_values($objects);
        }

        return $objects;
    }

    /**
     * Children of id element (only 1 level in tree).
     * If userid != null, only objects with read permissione for user, if ' ' - use guest/anonymous user,
     * if userid = null -> no permission check.
     * Filter: object types, search text query.
     *
     * @param integer $id       root id
     * @param string $userid    user: null (default) => no permission check. ' ' => guest/anonymous user,
     * @param string $status    object status
     * @param array  $filter    Filter: object types, search text query, eg. array(21, 22, "search" => "text to search").
     *                          Default: all object types
     * @param string $order     field to order result (id, status, modified..)
     * @param boolean $dir      true (default), ascending, otherwiese descending.
     * @param integer $page     Page number (for pagination)
     * @param integer $dim      Page dim (for pagination)
     * @param array $excludeIds array of ids to exclude
     * @return array
     */
    function getChildren($id = null, $userid = null, $status = null, $filter = array(), $order = null, $dir  = true, $page = 1, $dim = null, $excludeIds = array()) {
        return $this->findObjects($id, $userid, $status, $filter, $order, $dir, $page, $dim, false, $excludeIds) ;
    }

    /**
     * Descendants of id element (all elements in tree).
     * (see: BEObject->find(), to search not using content tree ).
     * If userid present, only objects with read permissione, if ' ' - guest/anonymous user,
     * if userid = null -> no permission check.
     * Filter: object types, search text query.
     *
     * @param integer $id       root id
     * @param string $userid    user: null (default) => no permission check. ' ' => guest/anonymous user,
     * @param string $status    object status
     * @param array  $filter    Filter: object types, search text query, eg. array(21, 22, "search" => "text to search").
     *                          Default: all object types
     * @param string $order     field to order result (id, status, modified..)
     * @param boolean $dir      true (default), ascending, otherwiese descending.
     * @param integer $page     Page number (for pagination)
     * @param integer $dim      Page dim (for pagination)
     * @param array $excludeIds array of ids to exclude
     * @return array
     */
    function getDescendants($id = null, $userid = null, $status = null, $filter = array(), $order = null, $dir  = true, $page = 1, $dim = null, $excludeIds = array()) {
        return $this->findObjects($id, $userid, $status, $filter, $order, $dir, $page, $dim, true, $excludeIds) ;
    }

    /**
     * save Tree.menu field to set menu and canonical path visibility
     *
     * @param mixed $ids, id or array of ids on which save menu field.
     *          if it's an array cycles on ids and save $menu value foreach of them
     * @param int $parent_id
     * @param mixed $menu, can be 1, 0 or null
     *          if it's null the default value for every object is used (section = 1, other objects = 0)
     * @throws BeditaException
     */
    public function saveMenuVisibility($ids, $parent_id, $menu = null) {
        if (empty($ids) || empty($parent_id)) {
            throw new BeditaException(__("Missing mandatory data id and/or parent_id to save menu visibility", true), array("ids" => $ids, "parent_id" => $parent_id));
        }
        if (is_numeric($ids)) {
            $ids = array($ids);
        }
        foreach ($ids as $id) {
            // set default value for every object (section = 1, other objects = 0)
            if ($menu === null) {
                $objectTypeId = ClassRegistry::init("BEObject")->findObjectTypeId($id);
                $menu = ($objectTypeId == Configure::read("objectTypes.section.id"))? 1 : 0;
            }
            $this->id = $this->field($this->primaryKey, array('id' => $id, 'parent_id' => $parent_id));
            if (!$this->id) {
                throw new BeditaException( __("Error saving visibility in menu and canonical paths", true), "Error retrieving Tree model primary key " . $this->primaryKey . " for id=" . $id);
            }
            if (!$this->saveField('menu', $menu)) {
                throw new BeditaException( __("Error saving visibility in menu and canonical paths", true), "Error saving Tree.menu field " . $menu . " for object " . $id);
            }
        }
    }

    /**
     * Clone a tree structure
     * Clone Publication and sections and add related contents
     *
     * @param int $id, publication/section id
     * @param array $options, see BEAppObjectModel::arrangeDataForClone()
     * @return array, contain couple of original id and cloned id
     * @throws BeditaException
     */
    public function cloneStructure($id, array $options = array()) {
        $idConversion = array();
        $objectTypeId = ClassRegistry::init("BEObject")->findObjectTypeId($id);
        // publication
        if ($objectTypeId == Configure::read("objectTypes.area.id")) {
            // clone publication
            $Area = ClassRegistry::init("Area");
            if (!$Area->cloneObject($id, $options)) {
                throw new BeditaException(__("Error cloning Publication", true) . ": id =  " . $id, array("id" => $id));
            }

            $newPubId = $Area->id;
            $idConversion[$id] = $newPubId;

            // clone publication's contents
            $this->copyContentsToBranch($id, $newPubId);

            // clone tree: get sections, clone them and build tree structure, get sections' children and clone tree structure
            $Section = ClassRegistry::init("Section");
            $sections = $Section->find("all", array(
                "conditions" => array(
                    "Tree.area_id" => $id,
                    "BEObject.object_type_id" => Configure::read("objectTypes.section.id")
                ),
                "order" => "Tree.object_path ASC",// . $publication["priority_order"]
                "contain" => array(
                    "BEObject" => array(
                        "Permission",
                        "Category",
                        "ObjectProperty",
                        "LangText"
                        ),
                    "Tree"
                )
            ));

            if (!empty($sections)) {
                // reorder with natural sort of object_path
                $sectionsTmp = Set::combine($sections, "{n}.object_path", "{n}");
                $objectPaths = array_keys($sectionsTmp);
                natsort($objectPaths);
                $sections = array();
                foreach ($objectPaths as $path) {
                    $sections[] = $sectionsTmp[$path];
                }

                foreach ($sections as $s) {
                    $sectionId = $s["id"];
                    // clone section
                    $s["parent_id"] = $idConversion[$s["parent_id"]];
                    $Section->arrangeDataForClone($s, $options);
                    $Section->create();
                    if (!$Section->save($s)) {
                        throw new BeditaException(__("Error cloning Section", true) . " " . $s["title"], array("id" => $sectionId));
                    }
                    $newSectionId = $Section->id;
                    $idConversion[$sectionId] = $newSectionId;

                    // set priority
                    if (!$this->setPriority($newSectionId, $s["priority"], $s["parent_id"])) {
                        throw new BeditaException(__("Error setting Section priority", true), array("id" => $newSectionId, "priority" => $s["priority"]));
                    }

                    $this->copyContentsToBranch($sectionId, $newSectionId);
                }
            }
        } elseif ($objectTypeId == Configure::read("objectTypes.section.id")) {
            //@todo: a parent_id it has to be defined otherwise the root section will be transformed in a Publication
        }

        return $idConversion;
    }

    /**
     * copy contents from a branch to another brnach
     *
     * @param int $originalBranchId, branch (publication/section) id where the contents are
     * @param int $newBranchId, branch (publication/section) id where the contents have to be copied
     * @throws BeditaException
     */
    public function copyContentsToBranch($originalBranchId, $newBranchId) {
        $children = $this->getChildren(
            $originalBranchId,
            null,
            null,
            array(
                'NOT' => array('object_type_id' => Configure::read('objectTypes.section.id'))
            )
        );
        if (!empty($children["items"])) {
            foreach ($children["items"] as $item) {
                if (!$this->appendChildWorker($item["id"], $newBranchId)) {
                    throw new BeditaException(__("Error cloning tree", true), array("child id" => $item["id"]));
                }
                // set priority
                if (!$this->setPriority($item["id"], $item["priority"], $newBranchId)) {
                    throw new BeditaException(__("Error setting contents priority", true), array("id" => $item["id"], "parent_id" => $newBranchId, "priority" => $s["priority"]));
                }

                $this->dispatchUpdatedTreeEvent($item['id'], static::EVENT_PARENTS_UPDATED);
            }

            $this->dispatchUpdatedTreeEvent($newBranchId, static::EVENT_CHILDREN_UPDATED);
        }
    }

    /**
     * Add to array of BEdita objects a count of ubiquity
     *
     * @param array $objects
     * @param array $options
     * @return array
     */
    public function countUbiquity(array $objects, array $options = array()) {
        foreach ($objects as &$obj) {
            $obj['ubiquity'] = $this->find('count', array(
                'conditions' => array('id' => $obj['id'])
            ));
        }
        return $objects;
    }

    /**
     * Removes a full branch that originates from the element with passed `$id`.
     * 
     * @param int $id ID of element to remove.
     * @return bool `true` if everything was ok, `false` otherwise.
     * @throws BeditaException Throws an exception if attempting to remove a leaf (or a branch generated by an object that should be a leaf instead!), or an ubiquitous branch.
     */
    // * @param mixed $parentId ID of parent object. Necessary to determinate "context". For root elements, please use `null`. If missing or `=== false` will delete ALL branches that originate from the given `$id`!
    public function removeBranch($id/* , $parentId = false */) {
        $collectionTypes = array(Configure::read('objectTypes.area.id'), Configure::read('objectTypes.section.id'));  // Types of 'collection' objects.

        // Check if it's a leaf.
        $check = ClassRegistry::init('BEObject')->find('count', array(
            'contain' => array(),
            'conditions' => array(
                'id' => $id,
                'object_type_id NOT' => $collectionTypes
            ),
        ));
        if ($check) {
            throw new BeditaException(__('Error deleting tree branch', true), array('id' => $id));
        }

        // If it's not a leaf, check if it's ubiquitous.
        $check = $this->find('count', array(
            'conditions' => array('id' => $id),
        ));
        if ($check > 1) {
            throw new BeditaException(__('Tree branch is ubiquitous', true), array('id' => $id));
        }

        // Find all descendant nodes (we'll need to call different methods to delete 'em according to their `object_type_id`).
        $descendants = $this->find('all', array(
            'contain' => array(),
            'fields' => array('Tree.id', 'BEObject.object_type_id'),
            'joins' => array(
                array(
                    'table' => 'objects',
                    'alias' => 'BEObject',
                    'type' => 'INNER',
                    'conditions' => array('BEObject.id = Tree.id'),
                ),
            ),
            'conditions' => array('parent_id' => $id),
        ));
        $descendants = Set::combine($descendants, '{n}.Tree.id', '{n}.BEObject.object_type_id');

        // Remove sub-branches and leafs.
        $ok = true;
        foreach ($descendants as $desc => $objectType) {
            if (in_array($objectType, $collectionTypes)) {
                // Remove sub-branches.
                $ok = $this->removeBranch($desc) && $ok;
            } else {
                // Remove leafs.
                $ok = $this->removeChildWorker($desc, $id) && $ok;
                $this->dispatchUpdatedTreeEvent($desc, static::EVENT_PARENTS_UPDATED);
            }
        }

        // If everything went OK, remove current tree node, which has descendants no more, so it behaves like a leaf.
        $ok = $ok && ($this->deleteAll(compact('id')) !== false);

        $this->dispatchUpdatedTreeEvent($id, static::EVENT_CHILDREN_UPDATED);

        return $ok;
    }

    /**
     * Removes a full tree that originates from the element with passed `$id`.
     * This method is an alias of `Tree::removeBranch()`.
     * 
     * @param int $id ID of element to remove.
     * @return bool `true` if everything was ok, `false` otherwise.
     * @throws BeditaException Throws an exception if attempting to remove a non-root element, a leaf (or a tree generated by an object that should be a leaf instead!), or an ubiquitous tree (?!).
     * @see Tree::removeBranch()
     */
    public function removeTree($id) {
        // Check if it's root.
        $check = $this->find('count', array(
            'contain' => array(),
            'conditions' => array('id' => $id, 'area_id' => $id, 'parent_id' => null),
        ));
        if (!$check) {
            throw new BeditaException(__('Object is not root', true), array('id' => $id));
        }

        return $this->removeBranch($id/*, null*/);
    }

    /**
     * Count children using $options if any
     * $options can contain every params used to customize Model::find()
     *
     * @see self::countChildren()
     * @param int $parentId the parent id
     * @param array $options
     * @return int
     */
    public function countChildrenContents($parentId, array $options = array()) {
        $sectionObjectTypeId = Configure::read('objectTypes.section.id');
        $this->bindModel(array(
            'belongsTo' => array(
                'BEObject' => array(
                    'foreignKey' => 'id',
                    'type' => 'inner'
                )
            )
        ));

        if (empty($options['conditions']['NOT'])) {
            $options['conditions']['NOT'] = array();
        }
        $options['conditions']['NOT'] = array('BEObject.object_type_id' => $sectionObjectTypeId) + $options['conditions']['NOT'];

        return $this->countChildren($parentId, $options);
    }

    /**
     * Count children using $options if any
     * $options can contain every params used to customize Model::find()
     *
     * @see self::countChildren()
     * @param int $parentId the parent id
     * @param array $options
     * @return int
     */
    public function countChildrenSections($parentId, array $options = array()) {
        $sectionObjectTypeId = Configure::read('objectTypes.section.id');
        $this->bindModel(array(
            'belongsTo' => array(
                'BEObject' => array(
                    'foreignKey' => 'id',
                    'type' => 'inner'
                )
            )
        ));
        $options['conditions']['BEObject.object_type_id'] = $sectionObjectTypeId;
        return $this->countChildren($parentId, $options);
    }

    /**
     * Count children using $options if any
     * $options can contain every params used to customize Model::find()
     *
     * @param int $parentId the parent id
     * @param array $options
     * @return int
     */
    public function countChildren($parentId, array $options = array()) {
        $cacheOpts = $options;
        if ($this->BeObjectCache) {
            $cachedValue = $this->BeObjectCache->read($parentId, $cacheOpts, 'count-children');
            if ($cachedValue !== false) {
                return $cachedValue;
            }
        }
        $options += array(
            'fields' => 'DISTINCT (Tree.id)',
            'conditions' => array()
        );
        $options['conditions']['Tree.parent_id'] = $parentId;
        $count = $this->find('count', $options);
        if ($this->BeObjectCache) {
            $this->BeObjectCache->write($parentId, $cacheOpts, $count, 'count-children');
        }
        return $count;
    }

    /**
     * Return a list of children ids
     *
     * @param int $parentId The parent id
     * @param boolean $descendants True to get all descendants, false to get just children
     * @return array
     */
    public function findChildrenList($parentId, $descendants = false) {
        if ($descendants) {
            return $this->find('list', array(
                'fields' => array('id'),
                'conditions' => array('object_path LIKE' => '%/' . $parentId . '/%'),
                'group' => 'id'
            ));
        }

        return $this->find('list', array(
            'fields' => array('id'),
            'conditions' => array('parent_id' => $parentId)
        ));
    }

    /**
     * Dispatch event to notify that tree has been updated for an object.
     *
     * @param int $id ID of object whose position in tree has been updated.
     * @param string $eventType Name of event to dispatch. Should be one of `static::EVENT_*` constants.
     * @return void
     */
    protected function dispatchUpdatedTreeEvent($id, $eventType)
    {
        BeLib::eventManager()->trigger($eventType, compact('id'));
    }
}
BEdita API doc | 4-cactus API documentation generated by ApiGen