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

/**
 * BEObject class
 *
 */
class BEObject extends BEAppModel {

    public $actsAs = array('Cacheable');

    var $name = 'BEObject';
    var $useTable   = "objects" ;

    private $defaultIp = "::1"; // default IP addr for saved objects

    var $validate = array(
//      'title' => array(
//          'rule' => 'notEmpty'
//      ),
        'object_type_id' => array(
            'rule' => 'notEmpty'
        ),
        'nickname' => array(
            'rule' => 'notEmpty'
        ),
        'lang' => array(
            'rule' => 'notEmpty'
        ),
        'ip_created' => array(
            'rule' => 'ip'
        ),
        'status' => array(
            'rule' => array('inList', array('on', 'off', 'draft'))
        ),
    ) ;

    var $belongsTo = array(
        'ObjectType' =>
            array(
                'className'     => 'ObjectType',
                'foreignKey'    => 'object_type_id',
                'conditions'    => ''
            ),
        'UserCreated' =>
            array(
                'className'     => 'User',
                'fields'        => 'id, userid, realname',
                'foreignKey'    => 'user_created',
            ),
        'UserModified' =>
            array(
                'className'     => 'User',
                'fields'        => 'id, userid, realname',
                'foreignKey'    => 'user_modified',
            ),
    ) ;

    var $hasMany = array(
        'Permission',

        'Version' =>
            array(
                'className'     => 'Version',
                'foreignKey'    => 'object_id',
                'dependent'     => true
            ),

        'ObjectProperty' =>
            array(
                'className'     => 'ObjectProperty',
                'foreignKey'    => 'object_id',
                'dependent'     => true
            ),
        'SearchText' =>
            array(
                'foreignKey'    => 'object_id',
                'dependent'     => true
            ),
        'LangText' =>
            array(
                'className'     => 'LangText',
                'foreignKey'    => 'object_id',
                'dependent'     => true
            ),
        'Annotation' =>
            array(
                'foreignKey'    => 'object_id',
                'dependent'     => true
            ),
        'RelatedObject' =>
            array(
                'className'             => 'ObjectRelation',
                'joinTable'             => 'object_relations',
                'foreignKey'            => 'id',
                'associationForeignKey' => 'object_id',
                'order'                 => 'priority'
            ),
        'Alias',
        'GeoTag' =>
            array(
                'foreignKey'    => 'object_id',
                'dependent'     => true
            )

        );

    var $hasAndBelongsToMany = array(
        'Category' =>
            array(
                'className'             => 'Category',
                'joinTable'             => 'object_categories',
                'foreignKey'            => 'object_id',
                'associationForeignKey' => 'category_id',
                'unique'                => true
            ),
        'User' =>
               array(
                'className'             => 'User',
                'joinTable'             => 'object_users',
                'foreignKey'            => 'object_id',
                'associationForeignKey' => 'user_id',
                'unique'                => true,
                   'with'                   => 'ObjectUser'
               )
    );

    /**
     * Format object data (ObjectProperty, Tag, Category, LangText, Permission)
     *
     * If ObjectProperty is populated a simplified customProperties array (useful in frontend apps) is built as
     *
     *  "customProperties" => array(
     *      "prop_name" => "prop_val",
     *      "prop_name_multiple_choice" => array("prop_val_1", "prop_val_2")
     *  )
     */
    function afterFind($result) {

        // format object properties
        if(!empty($result['ObjectProperty'])) {
            $result["customProperties"] = array();
            $propertyModel = ClassRegistry::init("Property");
            $property = $propertyModel->find("all", array(
                                "conditions" => array("object_type_id" => $result["object_type_id"]),
                                "contain" => array("PropertyOption")
                            )
                        );

            foreach ($property as $keyProp => $prop) {

                foreach ($result["ObjectProperty"] as $k => $value) {
                    if ($value["property_id"] == $prop["id"]) {
                        if ($prop["multiple_choice"] != 0) {
                            $property[$keyProp]["value"][] = $value;
                            $result["customProperties"][$prop["name"]][] = $value["property_value"];
                        } else {
                            $property[$keyProp]["value"] = $value;
                            $result["customProperties"][$prop["name"]] = $value["property_value"];
                        }

                        // set selected to true in PropertyOption array
                        if (!empty($prop["PropertyOption"])) {
                            foreach ($prop["PropertyOption"] as $n => $option) {
                                if ($option["property_option"] == $value["property_value"]) {
                                    $property[$keyProp]["PropertyOption"][$n]["selected"] = true;
                                }
                            }
                        }

                        unset($result["ObjectProperty"][$k]);
                    }
                }

            }
            $result["ObjectProperty"] = $property;
            unset($property);
        }

        // set up LangText for view
        if (!empty($result['LangText'])) {
            $langText = array();
            foreach ($result['LangText'] as $lang) {
                if (!empty($lang["name"]) && !empty($lang["lang"])) {
                    $langText[$lang["name"]][$lang["lang"]] = $lang["text"];
                    $langText[$lang["object_id"]][$lang["lang"]][$lang["name"]] = $lang["id"];
                }
            }
            $result['LangText'] = $langText;
        }

        // divide tags from categories
        if (!empty($result["Category"])) {

            $tag = array();
            $category = array();

            foreach ($result["Category"] as $ot) {
                if (!empty($ot["object_type_id"])) {
                    $category[] = $ot;
                } else {
                    $tag[] = $ot;
                }
            }

            $result["Category"] = $category;
            $result["Tag"] = $tag;
        }

        if (!empty($result["Permission"])) {
            foreach ($result["Permission"] as &$perm) {
                if ($perm["switch"] == "group") {
                    $perm["name"] = $this->Permission->Group->field("name", array("id" => $perm["ugid"]));
                } elseif ($perm["switch"] == "user") {
                    $perm["name"] = $this->Permission->User->field("name", array("id" => $perm["ugid"]));
                }
            }
        }

        return $result ;
    }

    function beforeSave() {
        $data;
        if(isset($this->data[$this->name]))
            $data = &$this->data[$this->name] ;
        else
            $data = &$this->data ;

        // format custom properties and searchable text fields
        $labels = array('SearchText');
        foreach ($labels as $label) {
            if(!isset($data[$label]))
                continue;

            if(is_array($data[$label]) && count($data[$label])) {
                $tmps = array();
                foreach($data[$label]  as $k => $v) {
                    $this->_value2array($k, $v, $arr);
                    array_push($tmps, $arr);
                }
                $data[$label] = $tmps;
            }
        }

        // empty GeoTag array if no value is in
        if (!empty($data['GeoTag'])) {
            foreach ($data['GeoTag'] as $key => $geotag) {
                $concat = '';
                $geoTagFields = array('title', 'address', 'latitude', 'longitude');
                foreach ($geoTagFields as $field) {
                    if (isset($geotag[$field])) {
                        $concat .= trim($geotag[$field]);
                    }
                }
                if (strlen($concat) == 0) {
                    unset($data['GeoTag'][$key]);
                }
            }
        }

        $this->unbindModel(array("hasMany"=>array("LangText","Version")));
        $this->unbindModel(array("hasAndBelongsToMany"=>array("User")));

        return true;
    }

    /**
     * Save hasMany relations data
     */
    function afterSave() {

        // hasMany relations
        foreach ($this->hasMany as $name => $assoc) {
            // skip specific manage
            if ($name == 'Permission' || $name == 'RelatedObject' || $name == 'Annotation') {
                continue;
            }

            // if not set data array do nothing
            if (!isset($this->data[$this->name][$name])) {
                continue;
            }

            $db =& ConnectionManager::getDataSource($this->useDbConfig);
            $model = new $assoc['className']();

            // delete previous associations
            $table = (isset($model->useTable))? $model->useTable : ($db->name($db->fullTableName($assoc->className)));
            $id = (isset($this->data[$this->name]['id']))? $this->data[$this->name]['id'] : $this->getInsertID();
            $foreignK = $assoc['foreignKey'];
            // #CUSTOM QUERY
            $db->query("DELETE FROM {$table} WHERE {$foreignK} = '{$id}'");

            if (!(is_array($this->data[$this->name][$name]) && count($this->data[$this->name][$name]))) {
                continue;
            }

            // save associations
            foreach ($this->data[$this->name][$name] as &$datum) {
                $modelTmp = new $assoc['className']();
                $datum[$foreignK] = $id;
                if (!$modelTmp->save($datum)) {
                    throw new BeditaException(__("Error saving object", true), "Error saving hasMany relation in BEObject for model " . $assoc['className']);
                }

                unset($modelTmp);
            }
            unset($datum);
        }

        // build ObjectUser Relation
        if (isset($this->data['BEObject']["ObjectUser"])) {
            $objectUserModel = ClassRegistry::init("ObjectUser");
            if (empty($this->data['BEObject']["ObjectUser"])) {
                $objectUserModel->deleteAll(array(
                        "object_id" => $this->id
                    )
                );
            } else {
                foreach ($this->data['BEObject']["ObjectUser"] as $switch => $objUserArr) {
                    $objectUserModel->deleteAll(array(
                            "object_id" => $this->id,
                            "switch" => $switch
                        )
                    );
                    if (is_array($objUserArr)) {
                        foreach ($objUserArr as $objUserData) {
                            if (!empty($objUserData["user_id"])) {
                                if (empty($objUserData["object_id"])) {
                                    $objUserData["object_id"] = $this->id;
                                }
                                $objectUserModel->create();
                                if (!$objectUserModel->save($objUserData)) {
                                    throw new BeditaException(__("error saving object_users relations",true));
                                }
                            }
                        }
                    }
                }
            }
        }

        $permissions = false;
        if (isset($this->data["Permission"])) {
            $permissions = $this->data["Permission"] ;
        } elseif (isset($this->data[$this->name]["Permission"])) {
            $permissions = $this->data[$this->name]["Permission"];
        }

        if (is_array($permissions)) {
            $this->Permission->replace($this->{$this->primaryKey}, $permissions);
        }
        // save relations between objects
        if (!empty($this->data['BEObject']['RelatedObject'])) {
            $db = &ConnectionManager::getDataSource($this->useDbConfig);
            $queriesDelete = array();
            $queriesInsert = array();
            $queriesModified = array();
            $lang = (isset($this->data['BEObject']['lang']))? $this->data['BEObject']['lang'] : null;

            $allRelations = BeLib::getObject("BeConfigure")->mergeAllRelations();
            $inverseRelations = array();
            foreach ($allRelations as $n => $r) {
                if (!empty($r["inverse"])) {
                    $inverseRelations[$r["inverse"]] = $n;
                }
            }

            $assoc = $this->hasMany['RelatedObject'] ;
            $table = $db->name($db->fullTableName($assoc['joinTable']));
            $fields = $assoc['foreignKey'] . "," . $assoc['associationForeignKey'] . ", switch, priority, params";

            foreach ($this->data['BEObject']['RelatedObject'] as $switch => $values) {

                foreach ($values as $key => $val) {
                    $obj_id = isset($val['id'])? Sanitize::escape(trim($val['id'])) : false;
                    $priority = isset($val['priority'])? Sanitize::escape(trim($val['priority'])) : 'NULL';
                    $params = isset($val['params'])? "'" . Sanitize::escape(json_encode($val['params'])) . "'" : 'NULL';

                    if (empty($priority)) {
                        $priority = 'NULL';
                    }

                    $inverseSwitch = $switch;
                    if (!empty($allRelations[$switch]) && !empty($allRelations[$switch]["inverse"])) {
                        $inverseSwitch = $allRelations[$switch]["inverse"];
                    } elseif (!empty($inverseRelations[$switch])) {
                        $inverseSwitch = $inverseRelations[$switch];
                    }
                    $switch = Sanitize::escape($switch);
                    $inverseSwitch = Sanitize::escape($inverseSwitch);

                    // Delete old associations
                    // #CUSTOM QUERY
                    $queriesDelete[] = "DELETE FROM {$table} WHERE {$assoc['foreignKey']} = '{$this->id}' AND switch = '{$switch}' ";
                    $queriesDelete[] = "DELETE FROM {$table} WHERE {$assoc['associationForeignKey']} = '{$this->id}'
                                        AND switch = '{$inverseSwitch}' ";

                    if (!empty($obj_id)) {
                        // #CUSTOM QUERY
                        $queriesInsert[] = "INSERT INTO {$table} ({$fields}) VALUES ({$this->id}, {$obj_id}, '{$switch}', {$priority}, {$params})" ;

                        // find priority of inverse relation
                        // #CUSTOM QUERY
                        $inverseRel = $this->query("SELECT priority
                                                      FROM {$table}
                                                      WHERE id={$obj_id}
                                                      AND object_id={$this->id}
                                                      AND switch='{$inverseSwitch}'");

                        if (empty($inverseRel[0]["object_relations"]["priority"])) {
                            // #CUSTOM QUERY
                            $inverseRel = $this->query("SELECT MAX(priority)+1 AS priority FROM {$table} WHERE id={$obj_id} AND switch='{$inverseSwitch}'");
                            $inversePriority = (empty($inverseRel[0][0]["priority"]))? 1 : $inverseRel[0][0]["priority"];
                        } else {
                            $inversePriority = $inverseRel[0]["object_relations"]["priority"];
                        }
                        // #CUSTOM QUERY
                        $queriesInsert[] = "INSERT INTO {$table} ({$fields}) VALUES ({$obj_id}, {$this->id}, '{$inverseSwitch}', ". $inversePriority  .", {$params})" ;
                    }

                    $modified = (isset($val['modified']))? ((boolean)$val['modified']) : false;
                    if ($modified && $obj_id) {
                        // Save tmp data.
                        $tmp_id = $this->id;
                        $tmp_data = $this->data;

                        // Update related models.
                        $this->data = array();
                        $title = isset($val['title']) ? $val['title'] : null;
                        $description = isset($val['description']) ? $val['description'] : null;
                        if ($switch == 'link') {
                            ClassRegistry::init('Link')->save(array(
                                'id' => $obj_id,
                                'title' => $title,
                                'url' => $val['url'],
                            ));
                        } else {
                            $this->updateTitleDescription($obj_id, $title, $description);
                        }

                        // Restore tmp data.
                        $this->id = $tmp_id;
                        $this->data = $tmp_data;
                    }
                }
            }

            $queriesDelete = array_unique($queriesDelete);
            foreach ($queriesDelete as $qDel) {
                if ($db->query($qDel) === false) {
                    throw new BeditaException(__("Error deleting associations", true), $qDel);
                }
            }
            foreach ($queriesInsert as $qIns) {
                if ($db->query($qIns)  === false) {
                    throw new BeditaException(__("Error inserting associations", true), $qIns);
                }
            }
            foreach ($queriesModified as $qMod) {
                if ($db->query($qMod)  === false) {
                    throw new BeditaException(__("Error modifying title and description", true), $qMod);
                }
            }
        }

        return true;
    }

    /**
     * Define default values.
     */
    function beforeValidate() {
        if(isset($this->data[$this->name]))
            $data = &$this->data[$this->name] ;
        else
            $data = &$this->data ;

        if(isset($data['title'])) {
            $data['title'] = trim($data['title']);
        }

        if (isset($data['fixed']) && !$this->_isCurrentUserAdmin()) {
            // #590 - Prevent non-admin Users to be able to change fixed property.
            unset($data['fixed']);
        }

        // set language -- disable for comments?
        if(!isset($data['lang'])) {
            $data['lang'] = $this->_getDefaultLang();
        }
        // check/set IP
        if(!isset($data['ip_created']) && !isset($data['id'])) {
            $data['ip_created'] = $this->_getDefaultIP();
        }

        // #650 set always user_modified = current user, set user_created only on new objects.
        // Because of cakephp populate fields with default value on db
        // user_created and user_modified are always set to 1 (systemUserId) if no value was set in $this->data array so
        // 1. user_created will be populated if no 'id' is set and is empty $data['user_created'] or it's equal to $systemUserId.
        //    In that case it will try to use session user
        //    If 'id' isset then it unset $data['user_created'] if exists.
        // 2. user_modified will be populated if is empty $data['user_modified'] or it's equal to $systemUserId.
        //    In that case it will try to use session user
        $systemUserId = BeLib::getObject('BeSystem')->systemUserId();
        if (empty($data['user_modified']) || $data['user_modified'] == $systemUserId) {
            $data['user_modified'] = $this->_getIDCurrentUser();
        }
        if (!isset($data['id'])) {
            if (empty($data['user_created']) || $data['user_created'] == $systemUserId) {
                $data['user_created'] = $this->_getIDCurrentUser();
            }
        } elseif (isset($data['user_created'])) {
            unset($data['user_created']);
        }

        $this->setPublisher();

        // nickname: verify nick and status change, object not fixed
        if(isset($data['id'])) {
            $currObj = $this->find("first", array(
                                            "conditions"=>array("BEObject.id" => $data['id']),
                                            "fields" =>array("status", "nickname", "fixed"),
                                            "contain" => array()
                                            ));
            if($currObj['BEObject']['fixed'] == 1) {  // don't change nickname & status
                // throws exceptions if status/nicknames are changed
                if((!empty($data['status']) && $data['status'] != $currObj['BEObject']['status']) ||
                    (!empty($data['nickname']) && $data['nickname'] != $currObj['BEObject']['nickname'])) {
                    throw new BeditaException(__("Error: modifying fixed object!", true));
                }
                $data['nickname'] = $currObj['BEObject']['nickname'];
                $data['status'] = $currObj['BEObject']['status'];
            } else {
                // Check if nickname has changed.
                if (empty($data['nickname']) && !empty($currObj['BEObject']['nickname'])) {
                    $data['nickname'] = $currObj['BEObject']['nickname'];
                } else {
                    $data['nickname'] = $this->_getDefaultNickname($data['nickname']);
                }

                // Check if status has changed.
                if (empty($data['status']) && !empty($currObj['BEObject']['status'])) {
                    $data['status'] = $currObj['BEObject']['status'];
                }
            }
        } else {
            $title = isset($data['title']) ? $data['title'] : null;
            $tmpName = !empty($data['nickname']) ? $data['nickname'] : $title;
            $data['nickname'] = $this->_getDefaultNickname($tmpName);
        }

        if(empty($data["user_created"])) unset($data["user_created"]) ;

        // format custom properties data type
        if (!empty($data["ObjectProperty"])) {
            foreach ($data["ObjectProperty"] as $key => $val) {
                if (!empty($val["property_type"]) && $val["property_type"] == "date")
                    $data["ObjectProperty"][$key]["property_value"] = $this->getDefaultDateFormat($val["property_value"]);
            }
        }

        // Se c'e' la chiave primaria vuota la toglie
        if(isset($data[$this->primaryKey]) && empty($data[$this->primaryKey]))
            unset($data[$this->primaryKey]) ;

        return true ;
    }

    public function findObjectTypeId($id) {
        $object_type_id = $this->field("object_type_id", array("BEObject.id" => $id));
        return $object_type_id;
    }

    /**
     * Is object fixed??
     *
     * @param int $id
     * @return boolean
     */
    public function isFixed($id) {
        $fixed = $this->field("fixed", array("BEObject.id" => $id));
        return ($fixed == 1);
    }

    /**
     * Model name/type from id
     *
     * @param unknown_type $id
     */
    public function getType($id) {
        $type_id = $this->findObjectTypeId($id);
        if($type_id === false) {
            throw new BeditaException(__("Error: object type not found", true));
        }
        return Configure::getInstance()->objectTypes[$type_id]["model"] ;
    }

    /**
     * Update title and description only.
     *
     * @param int $id
     * @param string|null $title
     * @param string|null $description
     * @return bool
     **/
    public function updateTitleDescription($id, $title, $description) {
        if (empty($id)) {
            return false;
        }

        $model = Configure::read('objectTypes.' . $this->findObjectTypeId($id) . '.model');
        $reg = ClassRegistry::getInstance();
        $reg->removeObject($model);  // #292 - Avoid loop in some cases, if related object is of the same model as the parent.

        // #722 - Avoid emptying title or description if field not submitted.
        $data = array(
            'id' => $id,
            'title' => $title,
            'description' => $description,
        );
        return $reg->init($model)->save(array_filter($data, function ($val) {
            return !is_null($val);
        }));
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * build object unique name
     *
     * @param string $value
     * @return string
     */
    private function _getDefaultNickname($value) {
        $nickname = $nickname_base = BeLib::getInstance()->friendlyUrlString($value);
        $conf = Configure::getInstance() ;
        $nickOk = false;
        $countNick = 1;
        $reservedWords = array_merge ( $conf->defaultReservedWords, $conf->cfgReservedWords );
        if(empty($nickname)) {
            $objTypeId = $this->data['BEObject']['object_type_id'];
            $nickname_base = $conf->objectTypes[$objTypeId]["name"] . "-" . time(); // default name - model type name - timestamp
            $nickname = $nickname_base ;
        };


        $aliasModel = ClassRegistry::init("Alias");
        while (!$nickOk) {

            $cond = "WHERE BEObject.nickname = '{$nickname}'";
            if ($this->id) {
                $cond .= " AND BEObject.id<>".$this->id;
            }
            $numNickDb = $this->find("count", array("conditions" => $cond, "contain" => array()));

            // check nickname in db and in reservedWords
            if ($numNickDb == 0 && !in_array($nickname, $reservedWords)) {
                // check aliases
                $object_id = $aliasModel->field("object_id", array("nickname_alias" => $nickname));
                if(empty($object_id)) {
                    $nickOk = true;
                }
            }
            if(!$nickOk) {
                $nickname = $nickname_base . "-" . $countNick++;
            }
        }

        return $nickname ;
    }

    private function _getDefaultLang() {
        $conf = Configure::getInstance() ;
        return ((isset($conf->defaultLang))?$conf->defaultLang:'') ;
    }

//  private function _getDefaultPermission($value, $object_type_id) {
//      if(isset($value) && is_array($value)) return $value ;
//
//      $conf = Configure::getInstance() ;
//      $permissions = &$conf->permissions ;
//
//      // Aggiunge i permessi di default solo se sta creando un nuovo oggetto
//      if(isset($this->data[$this->name][$this->primaryKey])) return null ;
//
//      // Seleziona i permessi in base al tipo di oggetti
//      if(isset($permissions[$object_type_id]))    return $permissions[$object_type_id] ;
//      else if (isset($permissions['all']))        return $permissions['all'] ;
//
//      return null ;
//  }

    private function _getDefaultIP() {
        if(!empty($_SERVER['REMOTE_ADDR'])) {
            $IP = $_SERVER['REMOTE_ADDR'];
        } else {
            $IP = $this->defaultIp;
        }
        return $IP ;
    }

    /**
     * Returns the current user ID. If a unit test is running, the test user ID is returned instead.
     *
     * @return int Current User's ID, or test User's ID. Defaults to system User's ID.
     * @see BeSystem::systemUserId()
     */
    private function _getIDCurrentUser() {
        $conf = Configure::getInstance();
        $systemUserId = BeLib::getObject('BeSystem')->systemUserId();

        if (isset($conf->beditaTestUserId)) {
            // Unit tests.
            return $conf->beditaTestUserId;
        } elseif (class_exists('CakeSession')) {
            $session = new CakeSession();
            if (!$session->started() || $session->valid() === false) {
                return $systemUserId;
            }

            $user = $session->read($conf->session['sessionUserKey']);
            if (!isset($user['id'])) {
                return $systemUserId;
            }

            return $user['id'];
        }

        return $systemUserId;
    }

    /**
     * Checks whether current User is in Group `administrator` or not.
     *
     * @return bool Current User's administrator permissions.
     */
    private function _isCurrentUserAdmin() {
        return !is_null(Configure::read('beditaTestUserId')) || in_array('administrator', ClassRegistry::init('User')->getGroups($this->_getIDCurrentUser()));
    }

    /**
     * Set the publisher to use in object creation.
     *
     * In editing mode (id not empty) no takes action.
     * In frontend no takes action.
     * In backend set `editorialContents.defaultPublisher` if configured and publisher in data is empty
     *
     * @return void
     */
    private function setPublisher() {
        if (isset($this->data[$this->name])) {
            $data = &$this->data[$this->name];
        } else {
            $data = &$this->data;
        }

        if (!empty($data['id']) || !BACKEND_APP) {
            if (isset($data['publisher']) && empty($data['publisher'])) {
                $data['publisher'] = null;
            }
            return;
        }

        $defaultPublisher = Configure::read('editorialContents.defaultPublisher');

        if (!empty($defaultPublisher) && empty($data['publisher'])) {
            $data['publisher'] = $defaultPublisher;
        }
    }

    /**
     * torna un array con la variabile archiviata in un array
     */
    private function _value2array($name, &$val, &$arr) {
        $type = null ;
        switch(gettype($val)) {
            case "integer" :    { $type = "integer" ; } break ;
            case "boolean" :    { $type = "bool" ; } break ;
            case "double" :     { $type = "float" ; } break ;
            case "string" :     { $type = "string" ; } break ;

            default: {
                $type = "stream" ;
                $val = serialize($val) ;
             }
        }
        $arr = array(
            'name'      => $name,
            'type'      => $type,
            $type       => $val
        ) ;
    }

    /**
     * Get object id from an identifier that could be an id or nickname
     * @param mixed $val
     */
    public function objectId($val) {
        $res = 0;
        if(is_numeric($val)) {
            $res = $val;
        } else {
            $res = $this->getIdFromNickname(strtolower($val));
        }
        return $res;
    }

    /**
     * Get object id from unique name
     * @param string $nickname
     */
    function getIdFromNickname($nickname, $status = null) {
        $id = null;
        if($status != null) {
            $id = $this->field("id", array("nickname" => $nickname, "status" => $status));
        } else {
            $id = $this->field("id", array("nickname" => $nickname));
        }
        if(empty($id)) { // if nickname not found lookup aliases
            $aliasModel = ClassRegistry::init("Alias");
            $id = $aliasModel->field("object_id", array("nickname_alias" => $nickname));
        }
        return $id;
    }

    /**
     * Get object nickname from id
     * @param integer $id
     */
    function getNicknameFromId($id) {
        return $this->field("nickname", array("id" => $id));
    }

    /**
     * Get an image id and uri that can be used as a poster of the one represented by the $id
     * Search in the relations expressed by $relations
     * @param int|string $id
     * @param array
     * @return array
     */
    public function getPoster($id = null, $relations = array('attach')) {
        if (empty($id) && !empty($this->id)) {
            $id = $this->id;
        }
        if (empty($id)) {
            return false;
        }
        if (!is_numeric($id)) {
            $id = $this->getIdFromNickname($id);
        }

        $Stream = ClassRegistry::init('Stream');

        /** Use `poster` relation, if present. */
        $poster = $Stream->find('first', array(
            'contain' => array(),
            'fields' => array(
                'RelatedObject.object_id',
                'Stream.uri',
            ),
            'joins' => array(
                array(
                    'table' => 'object_relations',
                    'alias' => 'RelatedObject',
                    'type' => 'INNER',
                    'conditions' => array(
                        'RelatedObject.object_id = Stream.id',
                        'RelatedObject.switch' => 'poster',
                        'RelatedObject.id' => $id,
                    ),
                ),
            ),
            'conditions' => array(
                'Stream.mime_type LIKE' => 'image%',
            ),
            'order' => array('RelatedObject.priority ASC'),
        ));
        if (!empty($poster)) {
            return array(
                'id' => $poster['RelatedObject']['object_id'],
                'uri' => $poster['Stream']['uri'],
            );
        }

        /** Use current object, if it is an image. */
        if ($this->findObjectTypeId($id) == Configure::read('objectTypes.image.id')) {
            $uri = $Stream->field('uri', array('Stream.id' => $id));
            return compact('id', 'uri');
        }

        /** Use attachments and other configured relations, as a last resort. */
        $related = $Stream->find('first', array(
            'contain' => array(),
            'fields' => array(
                'RelatedObject.object_id',
                'Stream.uri',
            ),
            'joins' => array(
                array(
                    'table' => 'object_relations',
                    'alias' => 'RelatedObject',
                    'type' => 'INNER',
                    'conditions' => array(
                        'RelatedObject.object_id = Stream.id',
                        'RelatedObject.switch' => $relations,
                        'RelatedObject.id' => $id,
                    ),
                ),
            ),
            'conditions' => array(
                'Stream.mime_type LIKE' => 'image%',
            ),
            'order' => array('RelatedObject.priority ASC'),
        ));
        if (!empty($related)) {
            return array(
                'id' => $related['RelatedObject']['object_id'],
                'uri' => $related['Stream']['uri'],
            );
        }

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