Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 504 lines (444 sloc) 17.061 kb
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
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/



/*********************************************************************************

* Description: Represents a relationship from a single beans perspective.
* Does not activly do work but is used by sugarbean to manipulate relationships.
* Work is defered to the relationship classes.
*
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
global $dictionary;
require_once("data/Relationships/RelationshipFactory.php");

class Link2 {

protected $relationship; //relationship object this link is tied to.
protected $focus; //SugarBean this link uses as the context for its calls.
    protected $def; //Field def for this link
    protected $name; //Field name for this link
    protected $beans; //beans on the other side of the link
    protected $rows; //any additional fields on the relationship
    protected $loaded; //true if this link has been loaded from the database
    protected $relationship_fields = array();

/**
* @param $linkName String name of a link field in the module's vardefs
* @param $bean SugarBean focus bean for this link (one half of a relationship)
* @return void
*
*/
function __construct($linkName, $bean, $linkDef = false){
        $this->focus = $bean;
        if (empty($bean->field_defs) || empty($bean->field_defs[$linkName]) || empty($bean->field_defs[$linkName]['relationship']))
        {
            if (empty($linkDef))
            {
                //Assume $linkName is really relationship_name, and find the link name with the vardef manager
                $this->def = VardefManager::getLinkFieldForRelationship($bean->module_dir, $bean->object_name, $linkName);
            }
            else {
                $this->def = $linkDef;
            }
            if (is_array($this->def) && !isset($this->def['name']))
            {
                //More than one link found, we need to figure out if we are currently on the LHS or RHS
                //assume lhs for now
                if (isset($this->def[0]['side']) && $this->def[0]['side'] == 'left')
                {
                    $this->def = $this->def[0];
                }else if (isset($this->def[1]['side']) && $this->def[1]['side'] == 'left')
                {
                    $this->def = $this->def[1];
                }
                else {
                    $this->def = $this->def[0];
                }
            }
            if (empty($this->def['name']))
            {
                $GLOBALS['log']->fatal("failed to find link for $linkName");
                return false;
            }

            $this->name = $this->def['name'];
        } else {
            $this->def = $bean->field_defs[$linkName];
            $this->name = $linkName;
        }
        $this->relationship = SugarRelationshipFactory::getInstance()->getRelationship($this->def['relationship']);

       if (!$this->loadedSuccesfully()) {
           $GLOBALS['log']->fatal("{$this->name} for {$this->def['relationship']} failed to load\n");
       }
        //Following behavior is tied to a property(ignore_role) value in the vardef. It alters the values of 2 properties, ignore_role_filter and add_distinct.
//the property values can be altered again before any requests are made.
if (!empty($this->def) && is_array($this->def)) {
if (array_key_exists('ignore_role', $this->def)) {
if ($this->def['ignore_role']) {
$this->ignore_role_filter=true;
$this->add_distinct=true;
}
}
}
}

    public function loadedSuccesfully()
    {
        return !empty($this->relationship);
    }

    public function load()
    {
        $data = $this->relationship->load($this);
        $this->rows = $data['rows'];
        $this->beans = null;
        $this->loaded = true;
    }

/* This method will return the following based on cardinality of the relationship.
* # one-to-many, many-to-many: empty array if not data is found else array of keys.
* # if many-to-many and $role set to true : empty array if not data is found else
* array of array which contain id+other fields.
* # many-to-one, one-to-one: null if no linked data is found, else key value.
*
* For a self referencing relationship the function will behave as if the user is trying
* to access the child records. To get to the parent records use the getParent() method.
*/
    public function get($role = false) {
        if (!$this->loaded)
            $this->load();

        return array_keys($this->rows);
    }

    /**
* @deprecated
*
* @return null
*/
public function getRelatedTableName() {
        return BeanFactory::getBean($this->getRelatedModuleName())->table_name;
}

public function getRelatedModuleName() {
if (!$this->relationship) return false;

        if ($this->getSide() == REL_LHS) {
            return $this->relationship->getRHSModule();
} else {
            return $this->relationship->getLHSModule();
}
}

    public function getType()
    {
        switch ($this->relationship->type)
        {
            case REL_MANY_MANY:
                return "many";
            case REL_ONE_ONE:
                return "one";
            case REL_ONE_MANY:
                return $this->getSide() == REL_LHS ? "many" : "one";
        }
        return "many";
    }

    public function getFocus()
    {
        return $this->focus;
    }



    /**
* @deprecated
* @return
*/
public function getRelatedFields(){
return $this->relationship_fields;
}

public function getRelatedField($name){
        if (!empty($this->relationship_fields) && !empty($this->relationship_fields[$name]))
            return $this->relationship_fields[$name];
        else
            return null; //For now return null. Later try the relationship object directly.
}

public function getRelationshipObject() {
return $this->relationship;
}

public function getSide() {
//First try the relationship
        if ($this->relationship->getLHSLink() == $this->name &&
            ($this->relationship->getLHSModule() == $this->focus->module_name)
        ){
            return REL_LHS;
        }

        if ($this->relationship->getRHSLink() == $this->name &&
            ($this->relationship->getRHSModule() == $this->focus->module_name)
        ){
            return REL_RHS;
        }

        //Next try the vardef
        if (!empty($this->def['side']))
        {
            if ((strtolower($this->def['side']) == 'left' || $this->def['side'] == REL_LHS)
                //Some relationships make have left in the vardef errorneously if generated by module builder
                && $this->name != $this->relationship->def['join_key_lhs'])
            {
                return REL_LHS ;
            }
            else {
                return REL_RHS;
            }
        }
}

protected function is_self_relationship() {
return $this->relationship->isSelfReferencing();
}

    public function isParentRelationship(){
        return $this->relationship->isParentRelationship();
    }

function getJoin($params, $return_array =false)
{
        return $this->relationship->getJoin($this, $params, $return_array);
}

function getQuery($params)
    {
     return $this->relationship->getQuery($this, $params);
}

    public function getSubpanelQuery($params = array(), $return_array = false)
    {
        return $this->relationship->getSubpanelQuery($this, $params, $return_array);
    }

function getBeans() {
        if (!$this->loaded) {
            $this->load();
        }
        if(!is_array($this->beans))
        {
            $this->beans = array();
            $rel_module = $this->getRelatedModuleName();
            foreach ($this->rows as $id => $vals)
            {
                $this->beans[$id] = BeanFactory::getBean($rel_module, $id);
            }
        }

        return $this->beans;
}

/**
* use this function to create link between 2 objects
* 1:1 will be treated like 1 to many.
*
* todo handle self referencing relationships
*
* the function also allows for setting of values for additional field in the table being
* updated to save the relationship, in case of many-to-many relationships this would be the join table.
*
* @param array $rel_keys array of ids or SugarBean objects
* @param array $additional_values the values should be passed as key value pairs with column name as the key name and column value as key value.
*
* @return void
*/
    function add($rel_keys,$additional_values=array()) {
        if (!is_array($rel_keys))
            $rel_keys = array($rel_keys);

        foreach($rel_keys as $key)
        {
            if (!($key instanceof SugarBean)) {
                $key = $this->getRelatedBean($key);
                if (!($key instanceof SugarBean)) {
                    $GLOBALS['log']->error("Unable to load related bean by id");
                    return false;
                }
            }

            if(empty($key->id) || empty($this->focus->id))
                return false;

            if ($this->getSide() == REL_LHS) {
                $this->relationship->add($this->focus, $key, $additional_values);
            }
            else {
                $this->relationship->add($key, $this->focus, $additional_values);
            }
        }
}



/* this method operates on all related record, takes action based on cardinality of the relationship.
* one-to-one, one-to-many: update the rhs table's parent id with null
* many-to-one: update the lhs table's parent-id with null.
* many-to-many: delete rows from the link table. related table must have delted and date_modified column.
* if related_is is null, the methods assumes that the parent bean (whose id is passed) is being deleted.
* if both id and related_id are passed the metod unlinks a single relationship.
* parameters: id of the bean being deleted.
*
*/
function delete($id, $related_id='') {
        if (empty($this->focus->id))
            $this->focus = BeanFactory::getBean($this->focus->module_name, $id);
        if (!empty($related_id))
        {
            if (!($related_id instanceof SugarBean)) {
                $related_id = $this->getRelatedBean($related_id);
            }
            if ($this->getSide() == REL_LHS) {
                $this->relationship->remove($this->focus, $related_id);
            }
            else {
                $this->relationship->remove($related_id, $this->focus);
            }
        }
        else
        {
            $this->relationship->removeAll($this);
        }
}

    protected function getRelatedBean($id = false)
    {
        return BeanFactory::getBean($this->getRelatedModuleName(), $id);
    }

function relationship_exists($table_name, $join_key_values) {

//find the key values for the table.
$dup_keys=$this->_get_alternate_key_fields($table_name);
if (empty($dup_keys)) {
$GLOBALS['log']->debug("No alternate key define, skipping duplicate check..");
return false;
}

$delimiter='';
$this->_duplicate_where=' WHERE ';
foreach ($dup_keys as $field) {
//look for key in $join_key_values, if found add to filter criteria else abort duplicate checking.
if (isset($join_key_values[$field])) {

$this->_duplicate_where .= $delimiter.' '.$field."='".$join_key_values[$field]."'";
$delimiter='AND';
} else {
$GLOBALS['log']->error('Duplicate checking aborted, Please supply a value for this column '.$field);
return false;
}
}
//add deleted check.
$this->_duplicate_where .= $delimiter.' deleted=0';

$query='SELECT id FROM '.$table_name.$this->_duplicate_where;

$GLOBALS['log']->debug("relationship_exists query(".$query.')');

$result=$this->_db->query($query, true);
$row = $this->_db->fetchByAssoc($result);

if ($row == null) {
return false;
}
else {
$this->_duplicate_key=$row['id'];
return true;
}
}

/* returns array of keys for duplicate checking, first check for an index of type alternate_key, if not found searches for
* primary key.
*
*/
protected function _get_alternate_key_fields($table_name) {
$indices=Link::_get_link_table_definition($table_name,'indices');
if (!empty($indices)) {
foreach ($indices as $index) {
                if ( isset($index['type']) && $index['type'] == 'alternate_key' ) {
                    return $index['fields'];
                }
}
}
        //bug 32623, when the relationship is built in old version, there is no alternate_key. we have to use join_key_lhs and join_key_lhs.
        $relDef = $this->relationship->def;
        if (!empty($relDef['join_key_lhs']) && !empty($relDef['join_key_rhs']))
return array($relDef['join_key_lhs'], $relDef['join_key_rhs']);
}

/*
*/
protected function _get_link_table_definition($table_name, $def_name) {
global $dictionary;

        if (isset($this->relationship->def[$def_name]))
            return $this->relationship->def[$def_name];

        return null;
    }
    /*
* Return the name of the role field for the passed many to many table.
* if there is no role filed : return false
*/
    protected function _get_link_table_role_field($table_name) {
        $varDefs = $this->_get_link_table_definition($table_name, 'fields');
        $role_field = false;
        if(!empty($varDefs)){
            $role_field = '';
            foreach($varDefs as $v){
                if(strpos($v['name'], '_role') !== false){
                    $role_field = $v['name'];
                }
            }
        }
        return $role_field;
    }

    /**
* @deprecated
*
* @return boolean returns true if this link is LHS
*/
    public function _get_bean_position()
    {
        return $this->getSide() == REL_LHS;
    }


    public function &__get($name)
    {
        switch($name)
        {
            case "relationship_type":
                return $this->relationship->type;
            case "_relationship":
                return $this->relationship;
            case "beans":
                if (!is_array($this->beans))
                    $this->getBeans();
                return $this->beans;
        }
        return $this->$name;
    }

    public function __set($name, $val)
    {
        if($name == "beans")
            $this->beans = $val;

    }

    /**
* @param SugarBean $bean
* @return void
*/
    public function addBean($bean)
    {
        if (!is_array($this->beans))
            $this->getBeans();
        $this->beans[$bean->id] = $bean;
    }

    /**
* @param SugarBean $bean
* @return void
*/
    public function removeBean($bean)
    {
        if (!is_array($this->beans))
            $this->getBeans();
        unset($this->beans[$bean->id]);
        unset($this->rows[$bean->id]);
    }
}
?>
Something went wrong with that request. Please try again.