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 
<?php
/*-----8<--------------------------------------------------------------------
 * 
 * BEdita - a semantic content management framework
 * 
 * Copyright 2015 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-----
 */

/**
 * Category model
 * 
*/
class Category extends BEAppModel {
    var $actsAs = array(
            'CompactResult'         => array()
    );
    
    var $validate = array(
        'label' => array(
            'rule' => 'notEmpty'
        ),
        'status' => array(
            'rule' => 'notEmpty'
        ),
        'name' => array(
            'rule' => 'notEmpty'
        )
    ) ;

    // static vars used by reorderTag static function
    static $dirTag, $orderTag;

    /**
     * Special key used in pagination count to remove unwanted options during the count
     * 
     * @var string
     */
    const COUNT_DENY_OPTIONS = '_countDenyOptions';
    
    function afterFind($result) {
        foreach ($result as &$res) {
            if(isset($res['name']))
                $res['url_label'] = $res['name'];
        }
        return $result;         
    }

    /**
     * Custom pagination count.
     *
     * @param array $conditions The conditions
     * @param int $recursive Recursive option
     * @param array $extra Extra options
     * @return int
     */
    function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
        if (!empty($extra[static::COUNT_DENY_OPTIONS])) {
            $extra = array_diff_key($extra, array_flip((array)$extra[static::COUNT_DENY_OPTIONS]));
        }
        
        $parameters = compact('conditions');
        if ($recursive != $this->recursive) {
            $parameters['recursive'] = $recursive;
        }
        
        return $this->find('count', array_merge($parameters, $extra));
    }

    public function tagLabelPresent($label, $exclude_id=null) {
        $tagDB = $this->find("first", 
            array("conditions" => "object_type_id IS NULL AND name='".addslashes($label)."' " . $this->collateStatment() ) );
        
        if (!empty($exclude_id) && $exclude_id == $tagDB["id"])
            return false;
        
        return !empty($tagDB);
    }

    /**
     * Get tag label from unique name
     * 
     * @param string $name
     */
    public function tagLabelFromName($name) {
        $tagDB = $this->find("first", 
            array("conditions" => "object_type_id IS NULL AND name='$name'"));
        return !empty($tagDB) ? $tagDB['label'] : "";
    }
    
    
    /**
     * Define a unique name from label: lowercase, trimmed, etc...
     * 
     * @param string $label
     */
    public function uniqueLabelName($label) {
        $baseName = $name = BeLib::getInstance()->friendlyUrlString($label);

        // search for already used label
        
        // suffix counter
        $i = 1;
        
        // if it's a category
        if (!empty($this->data[$this->alias]["object_type_id"])) {

            // if name is in mediaTypes
            if (in_array($name, Configure::read("mediaTypes"))) {
                // if multimedia object return baseName
                if (in_array($this->data[$this->alias]["object_type_id"], Configure::read("objectTypes.multimedia.id"))) {
                    return $baseName;
                } else {
                    $name = $baseName . "-" . $i++;
                }
            }

            $conditions[] = "object_type_id IS NOT NULL";

            
        // if it's a tag
        } else {
            $conditions[] = "object_type_id IS NULL";
        }

        $conditions["name"] = $name;
        // exclude itself if already present
        if (!empty($this->data[$this->alias]["id"])) {
            $conditions["NOT"]["id"] = $this->data[$this->alias]["id"];
        }

        $count = $this->find("count", array("conditions" => $conditions));
        
        if ($count > 0) {
            $freeName = false;
            while (!$freeName) {
                $conditions["name"] = $baseName . "-" . $i++;
                $count = $this->find("count", array("conditions" => $conditions));
                if ($count == 0) {
                    $freeName = true;
                    $name = $conditions["name"];
                }
            }
        }

        return $name;
    }
    
    /**
     * Define default values
     */     
    function beforeValidate() {
        $data = &$this->data[$this->name];
        $name = '';
        // if new tag/category
        if (empty($data['id'])) {
            if (!empty($data['label'])) {
                $name = $this->uniqueLabelName($data["label"]);
            }
        // if it's an existing tag/category
        } else {
            if (isset($data['name'])) {
                $data['name'] = trim($data['name']);
                if (!empty($data['name'])) {
                    $name = $data['name'];
                } elseif (!empty($data['label'])) {
                    $name = $data['label'];
                }
            }
        }

        if (!empty($name)) {
            $data['name'] = $this->uniqueLabelName($name);
        }

        return true;
    }
    
    /**
     * Get all categories of some object type and order them by area
     *
     * @param int $objectType
     * @return array(
     *              "area" => array(
     *                              nomearea => array(categories in that area)),
     *               "noarea" => array(categories aren't in any area)
     *              )
     */
    public function getCategoriesByArea($objectType) {
        
        $categories = $this->find("all", array(
            "conditions" => array("Category.object_type_id" => $objectType), "order" => "label"
        ));
        
        $objModel = ClassRegistry::init("BEObject");
        $areaList = $objModel->find('list', array(
                                        "conditions" => "object_type_id=" . Configure::read("objectTypes.area.id"), 
                                        "order" => "title", 
                                        "fields" => "BEObject.title"
                                        )
                                    );
        
        $areaCategory = array();
        
        foreach ($categories as $cat) {
            if (array_key_exists($cat["area_id"],$areaList)) {
                $areaCategory["area"][$areaList[$cat["area_id"]]][] = $cat; 
            } else {
                $areaCategory["noarea"][] = $cat;
            }
        }
        
        return $areaCategory;
    }
    
    /**
     * Get all categories defined for object type id
     *
     * @param int $objectType
     * @return array of (
     *              "area" => array(
     *                              nomearea => array(categories in that area)),
     *               "noarea" => array(categories aren't in any area)
     *              )
     */
    public function objectCategories($objectTypeId) {
        $categories = $this->find("all", array(
            "conditions" => array("Category.object_type_id" => $objectTypeId),
            "order" => "label"));
        return $categories;
    }
    
    private function collateStatment() {
        $res = "";
        // #MYSQL
        if($this->getDriver() == "mysql") {
            $res = "collate utf8_bin";
        }
        return $res;
    }
    
    /**
     * save a list of comma separated tag
     *
     * @param comma separated string $tagList 
     * @return array of tags' id
     */
    public function saveTagList($tagList) {
        $arrIdTag = array();
        if (!empty($tagList)) {
            $tags = explode(",", $tagList);
            
            foreach ($tags as $tag) {
                $tag = trim($tag);
                
                if (!empty($tag))  {
                    
                    $tagDB = $this->find("first", array(
                                                    "conditions" => "object_type_id IS NULL AND label='".addslashes($tag)."' " .
                                                        $this->collateStatment()
                                                    )
                                    );
                    if (empty($tagDB)) {
                        $tagDB["label"] = $tag;
                        $tagDB["status"] = "on";
                        $this->create();
                        if (!$this->save($tagDB)) {
                            throw new BeditaException(__("Error saving tags", true));
                        }
                    }
                    $id_tag = (!empty($tagDB["id"]))? $tagDB["id"] : $this->getLastInsertID();
                    if (!in_array($id_tag,$arrIdTag)) {
                        $arrIdTag[$id_tag] = $id_tag;
                    }
                }  
            }
        }
        return $arrIdTag;
    }
    
    /**
     * return list of tags with their weight
     *
     * @param array $options
     *              "showOrphans" => true,  show all tags also not associated
     *              "status" => null,       string or array (on, off, draft). if area_id is setted "status" is used also to related objects
     *              "cloud" => false,       true to set a css class for cloud view
     *              "coeff" => 12,          coeffiecient for calculate the distribution
     *              "order" => "label",     order by field
     *              "dir" => 1,             asc(1), desc(0)
     *              "area_id"=> null        get tags only associated to objects that are in "area_id" publication
     * 
     * @return array
     */
    public function getTags(array $options = array()) {

        $options = array_merge(
            array("showOrphans" => true, "status" => null, "cloud" => false, 
                "coeff" => 12, "order" => "label", "dir" => 1, "area_id"=> null, "section_id" => null),
            (array)$options
        );
        
        $conditions = array();
        $conditions[] = "Category.object_type_id IS NULL";
        if(!empty($options["status"])) {
            $conditions["Category.status"] = $options["status"];
        }
        
        $orderSql = ($options["order"] != "weight")? $options["order"] : "label";
        $dirSql = ($options["dir"])? "ASC" : "DESC";
        $limitSql = !empty($options['limit']) ? $options['limit'] : null;

        $joinsBEObject = array();
        $joins = array();

        // get tags associated to objects that are in $area_id publication or $section_id section
        if (!empty($options["area_id"]) || !empty($options["section_id"])) {
            $joinsBEObject = array(
                    'table' => 'objects',
                    'alias' => 'BEObject',
                    'type' => 'inner',
                    'conditions'=> array(
                        'BEObject.id = ObjectCategory.object_id'
                    )
                );
            if (!empty($options["status"])) {
                $joinsBEObject["conditions"]['BEObject.status'] = $options["status"];
            }

            $treeCondition = array('Tree.id = BEObject.id');
            if(!empty($options["section_id"])) {
                $treeCondition['Tree.parent_id'] = $options["section_id"];
            } else {
                $treeCondition['Tree.area_id'] = $options["area_id"];
            }
            
            $joinsTree = array(
                'table' => 'trees',
                'alias' => 'Tree',
                'type' => 'inner',
                'conditions'=> $treeCondition
            );

            $joins = array(
                array(
                    'table' => 'object_categories',
                    'alias' => 'ObjectCategory',
                    'type' => 'inner',
                    'conditions'=> array('ObjectCategory.category_id = Category.id')
                ),
                $joinsBEObject,
                $joinsTree
            );
        }

        $allTags = $this->find('all', array(
            'conditions'=> $conditions,
            'order' => array('Category.' . $orderSql => $dirSql),
            'group' => $this->fieldsString('Category'),
            'joins' => $joins,
            'limit' => $limitSql,
        ));
        
        $tags = array();
        foreach ($allTags as $t) {
            $tags[$t['id']] = $t;
        }

        $category_ids = Set::extract('/id', $allTags);
        
        $objCatModel = ClassRegistry::init("ObjectCategory");
        $joins = (empty($joinsBEObject))? array() : array($joinsBEObject, $joinsTree);
        $res = $objCatModel->find("all", array(
            'fields' => array("DISTINCT ObjectCategory.category_id", "ObjectCategory.object_id"),
            'conditions' => array("ObjectCategory.category_id" => $category_ids),
            'joins' => $joins
        ));
        
        // calculate weights
        $weights = array(0);
        foreach ($res as $val) {
            if (empty($weights[$val["ObjectCategory"]["category_id"]])) {
                $weights[$val["ObjectCategory"]["category_id"]] = 1;
            } else {
                $weights[$val["ObjectCategory"]["category_id"]]++;
            }
        }
        
        if ($options["cloud"]) {
            $max = max($weights);
            $min = min($weights);
            $distribution = ($max - $min) / $options["coeff"];
        }
        
        foreach ($res as $r) {
            $key = !empty($r['ObjectCategory']['category_id']) ? $r['ObjectCategory']['category_id'] : $r[0]['category_id'] ;
            $w = $weights[$r["ObjectCategory"]["category_id"]];
            $tags[$key]['weight'] = $w;
            if ($options["cloud"]) {
                if ($w == $min)
                    $tags[$key]['class'] = "smallestTag";
                elseif ($w == $max)
                    $tags[$key]['class']  = "largestTag";
                elseif ($w > ($min + ($distribution * 2)))
                    $tags[$key]['class']  = "largeTag";
                elseif ($w > ($min + $distribution))
                    $tags[$key]['class']  = "mediumTag";
                else
                    $tags[$key]['class']  = "smallTag";
            }
        }
        
        // remove orphans or set weight = 0, create the non-associative array
        $tagsArray = array();
        foreach ($tags as $k => $t) {
            $tags[$k]['url_label'] = $t['name'];
            if(!isset($t['weight'])) {
                if($options["showOrphans"] === false) {
                    unset($tags[$k]);       
                } else {
                    $tags[$k]['weight'] = 0;        
                    $tagsArray[]= $tags[$k];
                }
            } else {
                $tagsArray[]= $tags[$k];
            }
        }
        
        // if order by weight reorder tags
        if ($options["order"] == "weight") {
            Category::$orderTag = $options["order"];
            Category::$dirTag = $options["dir"];
            usort($tagsArray, array('Category', 'reorderTag'));
        }
//      pr($tagsArray);exit;
        return $tagsArray;
    }
    
    
    public function getContentsByTag($name) {
        // bind association on the fly
        $hasAndBelongsToMany = array(
            'BEObject' =>
                array(
                    'className'             => 'BEObject',
                    'joinTable'             => 'object_categories',
                    'foreignKey'            => 'category_id',
                    'associationForeignKey' => 'object_id',
                    'unique'                => true
                        )
                );
                
        $this->bindModel( array(
                'hasAndBelongsToMany'   => $hasAndBelongsToMany
                ) 
            );
        
        // don't compact find result
        $this->bviorCompactResults = false;
        $tag = $this->find("first", array(
                                        "conditions" => "object_type_id IS NULL AND name='".addslashes($name)."' ". 
                                                $this->collateStatment(), 
                                        "contain" => array("BEObject" => array("ObjectType"))
                                    )
                        );
        
        // reset to default compact result
        $this->bviorCompactResults = true;
        
        return empty($tag["BEObject"]) ? array() : $tag["BEObject"];
    }

    /**
     * USED for multimedia objects
     * check if exists $mediatype in categories for an object type. If not, create the category
     *
     * @param int $object_type_id
     * @return mixed, false if not mediatype in the form else return array of Category
     */
    public function checkMediaType($object_type_id, $mediatype) {
        
        if (empty($mediatype)) {
            return false;
        }
        
        $category = $this->find("first",
            array(
                "conditions" => array(
                    "name" => $mediatype, 
                    "object_type_id" => $object_type_id
                )
            )
        );
        if(empty($category)) { // if media category doesn't exists, create it
            $data = array(
                "name"=>$mediatype,
                "label"=>ucfirst($mediatype),
                "object_type_id"=>$object_type_id,
                "status"=>"on"
            );
            $this->create();
            if(!$this->save($data)) {
                throw new BeditaException(__("Error saving category", true), $this->validationErrors);
            }
            $category['id']=$this->id;
        }
        $categoryArr = array($category['id']=>$category['id']);
        return $categoryArr;
    }
    
    /**
     * compare two array elements defined by $orderTag var and return -1,0,1 
     *  $dirTag is used for define order of comparison 
     * 
     * @param array $e1
     * @param array $e2
     * @return int (-1,0,1)
     */
    private static function reorderTag($e1, $e2) {
        $d1 = $e1[Category::$orderTag];
        $d2 = $e2[Category::$orderTag];
        return (Category::$dirTag)? strcmp($d1,$d2) : strcmp($d2,$d1);
    }
    
    
    /**
     * Search for category names, create if not already present, and
     * return array of corresponding id
     *
     * @param array $names, category names to search/create
     * @param int $objTypeId, category object type id
     * @return array of corresponding id-category
     */
    public function findCreateCategories(array &$names, $objTypeId) {
        $res = array();
        // if not exists create
        foreach ($names as $n) {
            $this->create();
            $n = trim($n);
            $this->bviorCompactResults = false;
            $idCat = $this->field('id', array('name' => $n, 'object_type_id' => $objTypeId));
            $this->bviorCompactResults = true;
            if(empty($idCat)) {
                $dataCat = array('name'=> $n,'label' => $n,
                    'object_type_id' => $objTypeId, 'status'=>'on');
                if(!$this->save($dataCat)) {
                    throw new BeditaException(__("Error saving category") . ": " . print_r($dataCat, true));
                }
                $idCat = $this->id;
            }
            $res[] = $idCat;
        }
        return $res;        
    }
    
    /**
     * Add category to object usgin both category and object id
     * 
     * @return true on success, false on failure
     */
    public function addObjectCategory($categoryId, $objectId) {
        $res = true;
        $objCatModel = ClassRegistry::init("ObjectCategory");
        $data = $objCatModel->find("all", array(
                'fields' => array("DISTINCT ObjectCategory.category_id", "ObjectCategory.object_id"),
                'conditions' => array(
                    "ObjectCategory.category_id" => $categoryId, 
                    "ObjectCategory.object_id" => $objectId)
        ));
        if(empty($data)) {
            // #CUSTOM QUERY
            $q = "INSERT INTO object_categories (category_id, object_id)" .
                " VALUES ({$categoryId}, {$objectId})";
            $res = $this->query($q);
        }
        return $res;
    }

    /**
     * append mediatype to objects array
     *
     * @param array $objects
     * @param array $options
     */
    public function appendMediatype(array $objects, $options = array()) {
        $this->Behaviors->disable('CompactResult');
        $objectCategory = ClassRegistry::init('ObjectCategory');
        foreach ($objects as &$obj) {
            $categoryId = $objectCategory->field('category_id', array('object_id' => $obj['id']));
            if (!empty($categoryId)) {
                $obj['mediatype'] = $this->field('name', array('id' => $categoryId));
            }
        }
        $this->Behaviors->enable('CompactResult');
        return $objects;
    }

    /**
     * Get category id from name and object type id
     * 
     * @param $name, string unique name of category
     * @param $objectTypeId, int object type id
     * @return proerty id on success, null if no proerty id was found
     */
    public function categoryId($name, $objectTypeId) {
        $this->Behaviors->disable('CompactResult');
        $res = $this->field('id', array(
                'object_type_id' => $objectTypeId,
                'name' => $name));
        $this->Behaviors->enable('CompactResult');
        return $res;
    }

}
BEdita API doc | 4-cactus API documentation generated by ApiGen