2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
38 /*********************************************************************************
40 * Description: Defines the base class for all data entities used throughout the
41 * application. The base class including its methods and variables is designed to
42 * be overloaded with module-specific methods and variables particular to the
43 * module's base entity class.
44 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
45 * All Rights Reserved.
46 *******************************************************************************/
48 require_once('modules/DynamicFields/DynamicField.php');
49 require_once("data/Relationships/RelationshipFactory.php");
56 * SugarBean is the base class for all business objects in Sugar. It implements
57 * the primary functionality needed for manipulating business objects: create,
58 * retrieve, update, delete. It allows for searching and retrieving list of records.
59 * It allows for retrieving related objects (e.g. contacts related to a specific account).
61 * In the current implementation, there can only be one bean per folder.
62 * Naming convention has the bean name be the same as the module and folder name.
63 * All bean names should be singular (e.g. Contact). The primary table name for
64 * a bean should be plural (e.g. contacts).
70 * A pointer to the database object
77 * Unique object identifier
84 * When createing a bean, you can specify a value in the id column as
85 * long as that value is unique. During save, if the system finds an
86 * id, it assumes it is an update. Setting new_with_id to true will
87 * make sure the system performs an insert instead of an update.
89 * @var BOOL -- default false
91 var $new_with_id = false;
95 * How deep logic hooks can go
98 protected $max_logic_depth = 10;
101 * Disble vardefs. This should be set to true only for beans that do not have varders. Tracker is an example
103 * @var BOOL -- default false
105 var $disable_vardefs = false;
109 * holds the full name of the user that an item is assigned to. Only used if notifications
110 * are turned on and going to be sent out.
114 var $new_assigned_user_name;
117 * An array of booleans. This array is cleared out when data is loaded.
118 * As date/times are converted, a "1" is placed under the key, the field is converted.
120 * @var Array of booleans
122 var $processed_dates_times = array();
125 * Whether to process date/time fields for storage in the database in GMT
129 var $process_save_dates =true;
132 * This signals to the bean that it is being saved in a mass mode.
133 * Examples of this kind of save are import and mass update.
134 * We turn off notificaitons of this is the case to make things more efficient.
138 var $save_from_post = true;
141 * When running a query on related items using the method: retrieve_by_string_fields
142 * this value will be set to true if more than one item matches the search criteria.
146 var $duplicates_found = false;
149 * true if this bean has been deleted, false otherwise.
156 * Should the date modified column of the bean be updated during save?
157 * This is used for admin level functionality that should not be updating
158 * the date modified. This is only used by sync to allow for updates to be
159 * replicated in a way that will not cause them to be replicated back.
163 var $update_date_modified = true;
166 * Should the modified by column of the bean be updated during save?
167 * This is used for admin level functionality that should not be updating
168 * the modified by column. This is only used by sync to allow for updates to be
169 * replicated in a way that will not cause them to be replicated back.
173 var $update_modified_by = true;
176 * Setting this to true allows for updates to overwrite the date_entered
180 var $update_date_entered = false;
183 * This allows for seed data to be created without using the current uesr to set the id.
184 * This should be replaced by altering the current user before the call to save.
188 //TODO This should be replaced by altering the current user before the call to save.
189 var $set_created_by = true;
194 * The database table where records of this Bean are stored.
198 var $table_name = '';
201 * This is the singular name of the bean. (i.e. Contact).
205 var $object_name = '';
207 /** Set this to true if you query contains a sub-select and bean is converting both select statements
208 * into count queries.
210 var $ungreedy_count=false;
213 * The name of the module folder for this type of bean.
217 var $module_dir = '';
218 var $module_name = '';
222 var $column_fields = array();
223 var $list_fields = array();
224 var $additional_column_fields = array();
225 var $relationship_fields = array();
226 var $current_notify_user;
227 var $fetched_row=false;
228 var $fetched_rel_row = array();
230 var $force_load_details = false;
231 var $optimistic_lock = false;
232 var $disable_custom_fields = false;
233 var $number_formatting_done = false;
234 var $process_field_encrypted=false;
236 * The default ACL type
238 var $acltype = 'module';
241 var $additional_meta_fields = array();
244 * Set to true in the child beans if the module supports importing
246 var $importable = false;
249 * Set to true in the child beans if the module use the special notification template
251 var $special_notification = false;
254 * Set to true if the bean is being dealt with in a workflow
256 var $in_workflow = false;
260 * By default it will be true but if any module is to be kept non visible
261 * to tracker, then its value needs to be overriden in that particular module to false.
264 var $tracker_visibility = true;
267 * Used to pass inner join string to ListView Data.
269 var $listview_inner_join = array();
272 * Set to true in <modules>/Import/views/view.step4.php if a module is being imported
274 var $in_import = false;
276 * A way to keep track of the loaded relationships so when we clone the object we can unset them.
280 protected $loaded_relationships = array();
283 * set to true if dependent fields updated
285 protected $is_updated_dependent_fields = false;
288 * Blowfish encryption key
291 static protected $field_key;
294 * Constructor for the bean, it performs following tasks:
296 * 1. Initalized a database connections
297 * 2. Load the vardefs for the module implemeting the class. cache the entries
299 * 3. Setup row-level security preference
300 * All implementing classes must call this constructor using the parent::SugarBean() class.
305 global $dictionary, $current_user;
306 static $loaded_defs = array();
307 $this->db = DBManagerFactory::getInstance();
308 if (empty($this->module_name))
309 $this->module_name = $this->module_dir;
310 if((false == $this->disable_vardefs && empty($loaded_defs[$this->object_name])) || !empty($GLOBALS['reload_vardefs']))
312 VardefManager::loadVardef($this->module_dir, $this->object_name);
314 // build $this->column_fields from the field_defs if they exist
315 if (!empty($dictionary[$this->object_name]['fields'])) {
316 foreach ($dictionary[$this->object_name]['fields'] as $key=>$value_array) {
317 $column_fields[] = $key;
318 if(!empty($value_array['required']) && !empty($value_array['name'])) {
319 $this->required_fields[$value_array['name']] = 1;
322 $this->column_fields = $column_fields;
325 //setup custom fields
326 if(!isset($this->custom_fields) &&
327 empty($this->disable_custom_fields))
329 $this->setupCustomFields($this->module_dir);
331 //load up field_arrays from CacheHandler;
332 if(empty($this->list_fields))
333 $this->list_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'list_fields');
334 if(empty($this->column_fields))
335 $this->column_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'column_fields');
336 if(empty($this->required_fields))
337 $this->required_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'required_fields');
339 if(isset($GLOBALS['dictionary'][$this->object_name]) && !$this->disable_vardefs)
341 $this->field_name_map = $dictionary[$this->object_name]['fields'];
342 $this->field_defs = $dictionary[$this->object_name]['fields'];
344 if(!empty($dictionary[$this->object_name]['optimistic_locking']))
346 $this->optimistic_lock=true;
349 $loaded_defs[$this->object_name]['column_fields'] =& $this->column_fields;
350 $loaded_defs[$this->object_name]['list_fields'] =& $this->list_fields;
351 $loaded_defs[$this->object_name]['required_fields'] =& $this->required_fields;
352 $loaded_defs[$this->object_name]['field_name_map'] =& $this->field_name_map;
353 $loaded_defs[$this->object_name]['field_defs'] =& $this->field_defs;
357 $this->column_fields =& $loaded_defs[$this->object_name]['column_fields'] ;
358 $this->list_fields =& $loaded_defs[$this->object_name]['list_fields'];
359 $this->required_fields =& $loaded_defs[$this->object_name]['required_fields'];
360 $this->field_name_map =& $loaded_defs[$this->object_name]['field_name_map'];
361 $this->field_defs =& $loaded_defs[$this->object_name]['field_defs'];
362 $this->added_custom_field_defs = true;
364 if(!isset($this->custom_fields) &&
365 empty($this->disable_custom_fields))
367 $this->setupCustomFields($this->module_dir, false);
369 if(!empty($dictionary[$this->object_name]['optimistic_locking']))
371 $this->optimistic_lock=true;
375 if($this->bean_implements('ACL') && !empty($GLOBALS['current_user'])){
376 $this->acl_fields = (isset($dictionary[$this->object_name]['acl_fields']) && $dictionary[$this->object_name]['acl_fields'] === false)?false:true;
378 $this->populateDefaultValues();
383 * Returns the object name. If object_name is not set, table_name is returned.
385 * All implementing classes must set a value for the object_name variable.
387 * @param array $arr row of data fetched from the database.
391 function getObjectName()
393 if ($this->object_name)
394 return $this->object_name;
396 // This is a quick way out. The generated metadata files have the table name
397 // as the key. The correct way to do this is to override this function
398 // in bean and return the object name. That requires changing all the beans
399 // as well as put the object name in the generator.
400 return $this->table_name;
404 * Returns a list of fields with their definitions that have the audited property set to true.
405 * Before calling this function, check whether audit has been enabled for the table/module or not.
406 * You would set the audit flag in the implemting module's vardef file.
408 * @return an array of
409 * @see is_AuditEnabled
411 * Internal function, do not override.
413 function getAuditEnabledFieldDefinitions()
415 $aclcheck = $this->bean_implements('ACL');
416 $is_owner = $this->isOwner($GLOBALS['current_user']->id);
417 if (!isset($this->audit_enabled_fields))
420 $this->audit_enabled_fields=array();
421 foreach ($this->field_defs as $field => $properties)
426 !empty($properties['Audited']) || !empty($properties['audited']))
430 $this->audit_enabled_fields[$field]=$properties;
435 return $this->audit_enabled_fields;
439 * Return true if auditing is enabled for this object
440 * You would set the audit flag in the implemting module's vardef file.
444 * Internal function, do not override.
446 function is_AuditEnabled()
449 if (isset($dictionary[$this->getObjectName()]['audited']))
451 return $dictionary[$this->getObjectName()]['audited'];
462 * Returns the name of the audit table.
463 * Audit table's name is based on implementing class' table name.
465 * @return String Audit table name.
467 * Internal function, do not override.
469 function get_audit_table_name()
471 return $this->getTableName().'_audit';
475 * Returns the name of the custom table.
476 * Custom table's name is based on implementing class' table name.
478 * @return String Custom table name.
480 * Internal function, do not override.
482 public function get_custom_table_name()
484 return $this->getTableName().'_cstm';
488 * If auditing is enabled, create the audit table.
490 * Function is used by the install scripts and a repair utility in the admin panel.
492 * Internal function, do not override.
494 function create_audit_table()
497 $table_name=$this->get_audit_table_name();
499 require('metadata/audit_templateMetaData.php');
501 // Bug: 52583 Need ability to customize template for audit tables
502 $custom = 'custom/metadata/audit_templateMetaData_' . $this->getTableName() . '.php';
503 if (file_exists($custom))
508 $fieldDefs = $dictionary['audit']['fields'];
509 $indices = $dictionary['audit']['indices'];
511 // Renaming template indexes to fit the particular audit table (removed the brittle hard coding)
512 foreach($indices as $nr => $properties){
513 $indices[$nr]['name'] = 'idx_' . strtolower($this->getTableName()) . '_' . $properties['name'];
517 if(isset($dictionary['audit']['engine'])) {
518 $engine = $dictionary['audit']['engine'];
519 } else if(isset($dictionary[$this->getObjectName()]['engine'])) {
520 $engine = $dictionary[$this->getObjectName()]['engine'];
523 $this->db->createTableParams($table_name, $fieldDefs, $indices, $engine);
527 * Returns the implementing class' table name.
529 * All implementing classes set a value for the table_name variable. This value is returned as the
530 * table name. If not set, table name is extracted from the implementing module's vardef.
532 * @return String Table name.
534 * Internal function, do not override.
536 public function getTableName()
538 if(isset($this->table_name))
540 return $this->table_name;
543 return $dictionary[$this->getObjectName()]['table'];
547 * Returns field definitions for the implementing module.
549 * The definitions were loaded in the constructor.
551 * @return Array Field definitions.
553 * Internal function, do not override.
555 function getFieldDefinitions()
557 return $this->field_defs;
561 * Returns index definitions for the implementing module.
563 * The definitions were loaded in the constructor.
565 * @return Array Index definitions.
567 * Internal function, do not override.
569 function getIndices()
572 if(isset($dictionary[$this->getObjectName()]['indices']))
574 return $dictionary[$this->getObjectName()]['indices'];
580 * Returns field definition for the requested field name.
582 * The definitions were loaded in the constructor.
584 * @param string field name,
585 * @return Array Field properties or boolean false if the field doesn't exist
587 * Internal function, do not override.
589 function getFieldDefinition($name)
591 if ( !isset($this->field_defs[$name]) )
594 return $this->field_defs[$name];
598 * Returnss definition for the id field name.
600 * The definitions were loaded in the constructor.
602 * @return Array Field properties.
604 * Internal function, do not override.
606 function getPrimaryFieldDefinition()
608 $def = $this->getFieldDefinition("id");
610 $def = $this->getFieldDefinition(0);
613 $defs = $this->field_defs;
615 $def = current($defs);
620 * Returns the value for the requested field.
622 * When a row of data is fetched using the bean, all fields are created as variables in the context
623 * of the bean and then fetched values are set in these variables.
625 * @param string field name,
626 * @return varies Field value.
628 * Internal function, do not override.
630 function getFieldValue($name)
632 if (!isset($this->$name)){
635 if($this->$name === TRUE){
638 if($this->$name === FALSE){
645 * Basically undoes the effects of SugarBean::populateDefaultValues(); this method is best called right after object
648 public function unPopulateDefaultValues()
650 if ( !is_array($this->field_defs) )
653 foreach ($this->field_defs as $field => $value) {
654 if( !empty($this->$field)
655 && ((isset($value['default']) && $this->$field == $value['default']) || (!empty($value['display_default']) && $this->$field == $value['display_default']))
657 $this->$field = null;
660 if(!empty($this->$field) && !empty($value['display_default']) && in_array($value['type'], array('date', 'datetime', 'datetimecombo')) &&
661 $this->$field == $this->parseDateDefault($value['display_default'], ($value['type'] != 'date'))) {
662 $this->$field = null;
668 * Create date string from default value
670 * @param string $value
671 * @param bool $time Should be expect time set too?
674 protected function parseDateDefault($value, $time = false)
678 $dtAry = explode('&', $value, 2);
679 $dateValue = $timedate->getNow(true)->modify($dtAry[0]);
680 if(!empty($dtAry[1])) {
681 $timeValue = $timedate->fromString($dtAry[1]);
682 $dateValue->setTime($timeValue->hour, $timeValue->min, $timeValue->sec);
684 return $timedate->asUser($dateValue);
686 return $timedate->asUserDate($timedate->getNow(true)->modify($value));
690 function populateDefaultValues($force=false){
691 if ( !is_array($this->field_defs) )
693 foreach($this->field_defs as $field=>$value){
694 if((isset($value['default']) || !empty($value['display_default'])) && ($force || empty($this->$field))){
695 $type = $value['type'];
699 if(!empty($value['display_default'])){
700 $this->$field = $this->parseDateDefault($value['display_default']);
704 case 'datetimecombo':
705 if(!empty($value['display_default'])){
706 $this->$field = $this->parseDateDefault($value['display_default'], true);
710 if(empty($value['default']) && !empty($value['display_default']))
711 $this->$field = $value['display_default'];
713 $this->$field = $value['default'];
716 if(isset($this->$field)){
720 if ( isset($value['default']) && $value['default'] !== '' ) {
721 $this->$field = htmlentities($value['default'], ENT_QUOTES, 'UTF-8');
732 * Removes relationship metadata cache.
734 * Every module that has relationships defined with other modules, has this meta data cached. The cache is
735 * stores in 2 locations: relationships table and file system. This method clears the cache from both locations.
737 * @param string $key module whose meta cache is to be cleared.
738 * @param string $db database handle.
739 * @param string $tablename table name
740 * @param string $dictionary vardef for the module
741 * @param string $module_dir name of subdirectory where module is installed.
746 * Internal function, do not override.
748 function removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir)
750 //load the module dictionary if not supplied.
751 if ((!isset($dictionary) or empty($dictionary)) && !empty($module_dir))
753 $filename='modules/'. $module_dir . '/vardefs.php';
754 if(file_exists($filename))
759 if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
761 $GLOBALS['log']->fatal("removeRelationshipMeta: Metadata for table ".$tablename. " does not exist");
762 display_notice("meta data absent for table ".$tablename." keyed to $key ");
766 if (isset($dictionary[$key]['relationships']))
768 $RelationshipDefs = $dictionary[$key]['relationships'];
769 foreach ($RelationshipDefs as $rel_name)
771 Relationship::delete($rel_name,$db);
779 * This method has been deprecated.
781 * @see removeRelationshipMeta()
782 * @deprecated 4.5.1 - Nov 14, 2006
785 function remove_relationship_meta($key,$db,$log,$tablename,$dictionary,$module_dir)
787 SugarBean::removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
792 * Populates the relationship meta for a module.
794 * It is called during setup/install. It is used statically to create relationship meta data for many-to-many tables.
796 * @param string $key name of the object.
797 * @param object $db database handle.
798 * @param string $tablename table, meta data is being populated for.
799 * @param array dictionary vardef dictionary for the object. *
800 * @param string module_dir name of subdirectory where module is installed.
801 * @param boolean $iscustom Optional,set to true if module is installed in a custom directory. Default value is false.
804 * Internal function, do not override.
806 function createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir,$iscustom=false)
808 //load the module dictionary if not supplied.
809 if (empty($dictionary) && !empty($module_dir))
813 $filename='custom/modules/' . $module_dir . '/Ext/Vardefs/vardefs.ext.php';
819 // a very special case for the Employees module
820 // this must be done because the Employees/vardefs.php does an include_once on
822 $filename='modules/Users/vardefs.php';
826 $filename='modules/'. $module_dir . '/vardefs.php';
830 if(file_exists($filename))
833 // cn: bug 7679 - dictionary entries defined as $GLOBALS['name'] not found
834 if(empty($dictionary) || !empty($GLOBALS['dictionary'][$key]))
836 $dictionary = $GLOBALS['dictionary'];
841 $GLOBALS['log']->debug("createRelationshipMeta: no metadata file found" . $filename);
846 if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
848 $GLOBALS['log']->fatal("createRelationshipMeta: Metadata for table ".$tablename. " does not exist");
849 display_notice("meta data absent for table ".$tablename." keyed to $key ");
853 if (isset($dictionary[$key]['relationships']))
856 $RelationshipDefs = $dictionary[$key]['relationships'];
860 $beanList_ucase=array_change_key_case ( $beanList ,CASE_UPPER);
861 foreach ($RelationshipDefs as $rel_name=>$rel_def)
863 if (isset($rel_def['lhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['lhs_module'])])) {
864 $GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' lhs module is missing ' . $rel_def['lhs_module']);
867 if (isset($rel_def['rhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['rhs_module'])])) {
868 $GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' rhs module is missing ' . $rel_def['rhs_module']);
873 //check whether relationship exists or not first.
874 if (Relationship::exists($rel_name,$db))
876 $GLOBALS['log']->debug('Skipping, reltionship already exists '.$rel_name);
880 $seed = BeanFactory::getBean("Relationships");
881 $keys = array_keys($seed->field_defs);
883 foreach($keys as $key)
887 $toInsert[$key] = create_guid();
889 else if ($key == "relationship_name")
891 $toInsert[$key] = $rel_name;
893 else if (isset($rel_def[$key]))
895 $toInsert[$key] = $rel_def[$key];
897 //todo specify defaults if meta not defined.
901 $column_list = implode(",", array_keys($toInsert));
902 $value_list = "'" . implode("','", array_values($toInsert)) . "'";
904 //create the record. todo add error check.
905 $insert_string = "INSERT into relationships (" .$column_list. ") values (".$value_list.")";
906 $db->query($insert_string, true);
913 //log informational message stating no relationships meta was set for this bean.
919 * This method has been deprecated.
920 * @see createRelationshipMeta()
921 * @deprecated 4.5.1 - Nov 14, 2006
924 function create_relationship_meta($key,&$db,&$log,$tablename,$dictionary,$module_dir)
926 SugarBean::createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
931 * Handle the following when a SugarBean object is cloned
933 * Currently all this does it unset any relationships that were created prior to cloning the object
937 public function __clone()
939 if(!empty($this->loaded_relationships)) {
940 foreach($this->loaded_relationships as $rel) {
948 * Loads the request relationship. This method should be called before performing any operations on the related data.
950 * This method searches the vardef array for the requested attribute's definition. If the attribute is of the type
951 * link then it creates a similary named variable and loads the relationship definition.
953 * @param string $rel_name relationship/attribute name.
956 function load_relationship($rel_name)
958 $GLOBALS['log']->debug("SugarBean[{$this->object_name}].load_relationships, Loading relationship (".$rel_name.").");
960 if (empty($rel_name))
962 $GLOBALS['log']->error("SugarBean.load_relationships, Null relationship name passed.");
965 $fieldDefs = $this->getFieldDefinitions();
967 //find all definitions of type link.
968 if (!empty($fieldDefs[$rel_name]))
970 //initialize a variable of type Link
971 require_once('data/Link2.php');
972 $class = load_link_class($fieldDefs[$rel_name]);
973 if (isset($this->$rel_name) && $this->$rel_name instanceof $class) {
976 //if rel_name is provided, search the fieldef array keys by name.
977 if (isset($fieldDefs[$rel_name]['type']) && $fieldDefs[$rel_name]['type'] == 'link')
979 if ($class == "Link2")
980 $this->$rel_name = new $class($rel_name, $this);
982 $this->$rel_name = new $class($fieldDefs[$rel_name]['relationship'], $this, $fieldDefs[$rel_name]);
984 if (empty($this->$rel_name) ||
985 (method_exists($this->$rel_name, "loadedSuccesfully") && !$this->$rel_name->loadedSuccesfully()))
987 unset($this->$rel_name);
990 // keep track of the loaded relationships
991 $this->loaded_relationships[] = $rel_name;
995 $GLOBALS['log']->debug("SugarBean.load_relationships, Error Loading relationship (".$rel_name.")");
1000 * Loads all attributes of type link.
1002 * DO NOT CALL THIS FUNCTION IF YOU CAN AVOID IT. Please use load_relationship directly instead.
1004 * Method searches the implmenting module's vardef file for attributes of type link, and for each attribute
1005 * create a similary named variable and load the relationship definition.
1009 * Internal function, do not override.
1011 function load_relationships()
1013 $GLOBALS['log']->debug("SugarBean.load_relationships, Loading all relationships of type link.");
1014 $linked_fields=$this->get_linked_fields();
1015 foreach($linked_fields as $name=>$properties)
1017 $this->load_relationship($name);
1022 * Returns an array of beans of related data.
1024 * For instance, if an account is related to 10 contacts , this function will return an array of contacts beans (10)
1025 * with each bean representing a contact record.
1026 * Method will load the relationship if not done so already.
1028 * @param string $field_name relationship to be loaded.
1029 * @param string $bean name class name of the related bean.
1030 * @param array $sort_array optional, unused
1031 * @param int $begin_index Optional, default 0, unused.
1032 * @param int $end_index Optional, default -1
1033 * @param int $deleted Optional, Default 0, 0 adds deleted=0 filter, 1 adds deleted=1 filter.
1034 * @param string $optional_where, Optional, default empty.
1036 * Internal function, do not override.
1038 function get_linked_beans($field_name,$bean_name, $sort_array = array(), $begin_index = 0, $end_index = -1,
1039 $deleted=0, $optional_where="")
1041 //if bean_name is Case then use aCase
1042 if($bean_name=="Case")
1043 $bean_name = "aCase";
1045 if($this->load_relationship($field_name)) {
1046 if ($this->$field_name instanceof Link) {
1047 // some classes are still based on Link, e.g. TeamSetLink
1048 return array_values($this->$field_name->getBeans(new $bean_name(), $sort_array, $begin_index, $end_index, $deleted, $optional_where));
1051 if ($end_index != -1 || !empty($deleted) || !empty($optional_where))
1052 return array_values($this->$field_name->getBeans(array(
1053 'where' => $optional_where,
1054 'deleted' => $deleted,
1055 'limit' => ($end_index - $begin_index)
1058 return array_values($this->$field_name->getBeans());
1066 * Returns an array of fields that are of type link.
1068 * @return array List of fields.
1070 * Internal function, do not override.
1072 function get_linked_fields()
1075 $linked_fields=array();
1077 // require_once('data/Link.php');
1079 $fieldDefs = $this->getFieldDefinitions();
1081 //find all definitions of type link.
1082 if (!empty($fieldDefs))
1084 foreach ($fieldDefs as $name=>$properties)
1086 if (array_search('link',$properties) === 'type')
1088 $linked_fields[$name]=$properties;
1093 return $linked_fields;
1097 * Returns an array of fields that are able to be Imported into
1098 * i.e. 'importable' not set to 'false'
1100 * @return array List of fields.
1102 * Internal function, do not override.
1104 function get_importable_fields()
1106 $importableFields = array();
1108 $fieldDefs= $this->getFieldDefinitions();
1110 if (!empty($fieldDefs)) {
1111 foreach ($fieldDefs as $key=>$value_array) {
1112 if ( (isset($value_array['importable'])
1113 && (is_string($value_array['importable']) && $value_array['importable'] == 'false'
1114 || is_bool($value_array['importable']) && $value_array['importable'] == false))
1115 || (isset($value_array['type']) && $value_array['type'] == 'link')
1116 || (isset($value_array['auto_increment'])
1117 && ($value_array['type'] == true || $value_array['type'] == 'true')) ) {
1118 // only allow import if we force it
1119 if (isset($value_array['importable'])
1120 && (is_string($value_array['importable']) && $value_array['importable'] == 'true'
1121 || is_bool($value_array['importable']) && $value_array['importable'] == true)) {
1122 $importableFields[$key]=$value_array;
1126 $importableFields[$key]=$value_array;
1131 return $importableFields;
1135 * Returns an array of fields that are of type relate.
1137 * @return array List of fields.
1139 * Internal function, do not override.
1141 function get_related_fields()
1144 $related_fields=array();
1146 // require_once('data/Link.php');
1148 $fieldDefs = $this->getFieldDefinitions();
1150 //find all definitions of type link.
1151 if (!empty($fieldDefs))
1153 foreach ($fieldDefs as $name=>$properties)
1155 if (array_search('relate',$properties) === 'type')
1157 $related_fields[$name]=$properties;
1162 return $related_fields;
1166 * Returns an array of fields that are required for import
1170 function get_import_required_fields()
1172 $importable_fields = $this->get_importable_fields();
1173 $required_fields = array();
1175 foreach ( $importable_fields as $name => $properties ) {
1176 if ( isset($properties['importable']) && is_string($properties['importable']) && $properties['importable'] == 'required' ) {
1177 $required_fields[$name] = $properties;
1181 return $required_fields;
1185 * Iterates through all the relationships and deletes all records for reach relationship.
1187 * @param string $id Primary key value of the parent reocrd
1189 function delete_linked($id)
1191 $linked_fields=$this->get_linked_fields();
1192 foreach ($linked_fields as $name => $value)
1194 if ($this->load_relationship($name))
1196 $this->$name->delete($id);
1200 $GLOBALS['log']->fatal("error loading relationship $name");
1206 * Creates tables for the module implementing the class.
1207 * If you override this function make sure that your code can handles table creation.
1210 function create_tables()
1214 $key = $this->getObjectName();
1215 if (!array_key_exists($key, $dictionary))
1217 $GLOBALS['log']->fatal("create_tables: Metadata for table ".$this->table_name. " does not exist");
1218 display_notice("meta data absent for table ".$this->table_name." keyed to $key ");
1222 if(!$this->db->tableExists($this->table_name))
1224 $this->db->createTable($this);
1225 if($this->bean_implements('ACL')){
1226 if(!empty($this->acltype)){
1227 ACLAction::addActions($this->getACLCategory(), $this->acltype);
1229 ACLAction::addActions($this->getACLCategory());
1235 echo "Table already exists : $this->table_name<br>";
1237 if($this->is_AuditEnabled()){
1238 if (!$this->db->tableExists($this->get_audit_table_name())) {
1239 $this->create_audit_table();
1247 * Delete the primary table for the module implementing the class.
1248 * If custom fields were added to this table/module, the custom table will be removed too, along with the cache
1249 * entries that define the custom fields.
1252 function drop_tables()
1255 $key = $this->getObjectName();
1256 if (!array_key_exists($key, $dictionary))
1258 $GLOBALS['log']->fatal("drop_tables: Metadata for table ".$this->table_name. " does not exist");
1259 echo "meta data absent for table ".$this->table_name."<br>\n";
1261 if(empty($this->table_name))return;
1262 if ($this->db->tableExists($this->table_name))
1264 $this->db->dropTable($this);
1265 if ($this->db->tableExists($this->table_name. '_cstm'))
1267 $this->db->dropTableName($this->table_name. '_cstm');
1268 DynamicField::deleteCache();
1270 if ($this->db->tableExists($this->get_audit_table_name())) {
1271 $this->db->dropTableName($this->get_audit_table_name());
1280 * Loads the definition of custom fields defined for the module.
1281 * Local file system cache is created as needed.
1283 * @param string $module_name setting up custom fields for this module.
1284 * @param boolean $clean_load Optional, default true, rebuilds the cache if set to true.
1286 function setupCustomFields($module_name, $clean_load=true)
1288 $this->custom_fields = new DynamicField($module_name);
1289 $this->custom_fields->setup($this);
1294 * Cleans char, varchar, text, etc. fields of XSS type materials
1296 function cleanBean() {
1297 foreach($this->field_defs as $key => $def) {
1299 if (isset($def['type'])) {
1302 if(isset($def['dbType']))
1303 $type .= $def['dbType'];
1305 if($def['type'] == 'html') {
1306 $this->$key = SugarCleaner::cleanHtml($this->$key, true);
1307 } elseif((strpos($type, 'char') !== false ||
1308 strpos($type, 'text') !== false ||
1312 $this->$key = SugarCleaner::cleanHtml($this->$key);
1318 * Implements a generic insert and update logic for any SugarBean
1319 * This method only works for subclasses that implement the same variable names.
1320 * This method uses the presence of an id field that is not null to signify and update.
1321 * The id field should not be set otherwise.
1323 * @param boolean $check_notify Optional, default false, if set to true assignee of the record is notified via email.
1324 * @todo Add support for field type validation and encoding of parameters.
1326 function save($check_notify = FALSE)
1328 $this->in_save = true;
1329 // cn: SECURITY - strip XSS potential vectors
1331 // This is used so custom/3rd-party code can be upgraded with fewer issues, this will be removed in a future release
1332 $this->fixUpFormatting();
1334 global $current_user, $action;
1337 if(empty($this->id))
1342 if ( $this->new_with_id == true )
1346 if(empty($this->date_modified) || $this->update_date_modified)
1348 $this->date_modified = $GLOBALS['timedate']->nowDb();
1351 $this->_checkOptimisticLocking($action, $isUpdate);
1353 if(!empty($this->modified_by_name)) $this->old_modified_by_name = $this->modified_by_name;
1354 if($this->update_modified_by)
1356 $this->modified_user_id = 1;
1358 if (!empty($current_user))
1360 $this->modified_user_id = $current_user->id;
1361 $this->modified_by_name = $current_user->user_name;
1364 if ($this->deleted != 1)
1368 if (empty($this->date_entered))
1370 $this->date_entered = $this->date_modified;
1372 if($this->set_created_by == true)
1374 // created by should always be this user
1375 $this->created_by = (isset($current_user)) ? $current_user->id : "";
1377 if( $this->new_with_id == false)
1379 $this->id = create_guid();
1385 require_once("data/BeanFactory.php");
1386 BeanFactory::registerBean($this->module_name, $this);
1388 if (empty($GLOBALS['updating_relationships']) && empty($GLOBALS['saving_relationships']) && empty ($GLOBALS['resavingRelatedBeans']))
1390 $GLOBALS['saving_relationships'] = true;
1391 // let subclasses save related field changes
1392 $this->save_relationship_changes($isUpdate);
1393 $GLOBALS['saving_relationships'] = false;
1395 if($isUpdate && !$this->update_date_entered)
1397 unset($this->date_entered);
1399 // call the custom business logic
1400 $custom_logic_arguments['check_notify'] = $check_notify;
1403 $this->call_custom_logic("before_save", $custom_logic_arguments);
1404 unset($custom_logic_arguments);
1406 if(isset($this->custom_fields))
1408 $this->custom_fields->bean = $this;
1409 $this->custom_fields->save($isUpdate);
1412 // use the db independent query generator
1413 $this->preprocess_fields_on_save();
1415 //construct the SQL to create the audit record if auditing is enabled.
1416 $dataChanges=array();
1417 if ($this->is_AuditEnabled()) {
1418 if ($isUpdate && !isset($this->fetched_row)) {
1419 $GLOBALS['log']->debug('Auditing: Retrieve was not called, audit record will not be created.');
1421 $dataChanges=$this->db->getDataChanges($this);
1425 $this->_sendNotifications($check_notify);
1428 $this->db->update($this);
1430 $this->db->insert($this);
1433 if (!empty($dataChanges) && is_array($dataChanges))
1435 foreach ($dataChanges as $change)
1437 $this->db->save_audit_records($this,$change);
1442 if (empty($GLOBALS['resavingRelatedBeans'])){
1443 SugarRelationship::resaveRelatedBeans();
1447 //If we aren't in setup mode and we have a current user and module, then we track
1448 if(isset($GLOBALS['current_user']) && isset($this->module_dir))
1450 $this->track_view($current_user->id, $this->module_dir, 'save');
1453 $this->call_custom_logic('after_save', '');
1455 //Now that the record has been saved, we don't want to insert again on further saves
1456 $this->new_with_id = false;
1457 $this->in_save = false;
1463 * Performs a check if the record has been modified since the specified date
1465 * @param date $date Datetime for verification
1466 * @param string $modified_user_id User modified by
1468 function has_been_modified_since($date, $modified_user_id)
1470 global $current_user;
1471 $date = $this->db->convert($this->db->quoted($date), 'datetime');
1472 if (isset($current_user))
1474 $query = "SELECT date_modified FROM $this->table_name WHERE id='$this->id' AND modified_user_id != '$current_user->id'
1475 AND (modified_user_id != '$modified_user_id' OR date_modified > $date)";
1476 $result = $this->db->query($query);
1478 if($this->db->fetchByAssoc($result))
1487 * Determines which users receive a notification
1489 function get_notification_recipients() {
1490 $notify_user = new User();
1491 $notify_user->retrieve($this->assigned_user_id);
1492 $this->new_assigned_user_name = $notify_user->full_name;
1494 $GLOBALS['log']->info("Notifications: recipient is $this->new_assigned_user_name");
1496 $user_list = array($notify_user);
1499 //send notifications to followers, but ensure to not query for the assigned_user.
1500 return SugarFollowing::getFollowers($this, $notify_user);
1505 * Handles sending out email notifications when items are first assigned to users
1507 * @param string $notify_user user to notify
1508 * @param string $admin the admin user that sends out the notification
1510 function send_assignment_notifications($notify_user, $admin)
1512 global $current_user;
1514 if(($this->object_name == 'Meeting' || $this->object_name == 'Call') || $notify_user->receive_notifications)
1516 $sendToEmail = $notify_user->emailAddress->getPrimaryAddress($notify_user);
1518 if(empty($sendToEmail)) {
1519 $GLOBALS['log']->warn("Notifications: no e-mail address set for user {$notify_user->user_name}, cancelling send");
1523 $notify_mail = $this->create_notification_email($notify_user);
1524 $notify_mail->setMailerForSystem();
1526 if(empty($admin->settings['notify_send_from_assigning_user'])) {
1527 $notify_mail->From = $admin->settings['notify_fromaddress'];
1528 $notify_mail->FromName = (empty($admin->settings['notify_fromname'])) ? "" : $admin->settings['notify_fromname'];
1530 // Send notifications from the current user's e-mail (if set)
1531 $fromAddress = $current_user->emailAddress->getReplyToAddress($current_user);
1532 $fromAddress = !empty($fromAddress) ? $fromAddress : $admin->settings['notify_fromaddress'];
1533 $notify_mail->From = $fromAddress;
1534 //Use the users full name is available otherwise default to system name
1535 $from_name = !empty($admin->settings['notify_fromname']) ? $admin->settings['notify_fromname'] : "";
1536 $from_name = !empty($current_user->full_name) ? $current_user->full_name : $from_name;
1537 $notify_mail->FromName = $from_name;
1540 $oe = new OutboundEmail();
1541 $oe = $oe->getUserMailerSettings($current_user);
1542 //only send if smtp server is defined
1544 $smtpVerified = false;
1546 //first check the user settings
1547 if(!empty($oe->mail_smtpserver)){
1548 $smtpVerified = true;
1551 //if still not verified, check against the system settings
1552 if (!$smtpVerified){
1553 $oe = $oe->getSystemMailerSettings();
1554 if(!empty($oe->mail_smtpserver)){
1555 $smtpVerified = true;
1558 //if smtp was not verified against user or system, then do not send out email
1559 if (!$smtpVerified){
1560 $GLOBALS['log']->fatal("Notifications: error sending e-mail, smtp server was not found ");
1565 if(!$notify_mail->Send()) {
1566 $GLOBALS['log']->fatal("Notifications: error sending e-mail (method: {$notify_mail->Mailer}), (error: {$notify_mail->ErrorInfo})");
1568 $GLOBALS['log']->info("Notifications: e-mail successfully sent");
1576 * This function handles create the email notifications email.
1577 * @param string $notify_user the user to send the notification email to
1579 function create_notification_email($notify_user) {
1580 global $sugar_version;
1581 global $sugar_config;
1582 global $app_list_strings;
1583 global $current_user;
1586 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
1589 require_once("include/SugarPHPMailer.php");
1591 $notify_address = $notify_user->emailAddress->getPrimaryAddress($notify_user);
1592 $notify_name = $notify_user->full_name;
1593 $GLOBALS['log']->debug("Notifications: user has e-mail defined");
1595 $notify_mail = new SugarPHPMailer();
1596 $notify_mail->AddAddress($notify_address,$locale->translateCharsetMIME(trim($notify_name), 'UTF-8', $OBCharset));
1598 if(empty($_SESSION['authenticated_user_language'])) {
1599 $current_language = $sugar_config['default_language'];
1601 $current_language = $_SESSION['authenticated_user_language'];
1603 $xtpl = new XTemplate(get_notify_template_file($current_language));
1604 if($this->module_dir == "Cases") {
1605 $template_name = "Case"; //we should use Case, you can refer to the en_us.notify_template.html.
1608 $template_name = $beanList[$this->module_dir]; //bug 20637, in workflow this->object_name = strange chars.
1611 $this->current_notify_user = $notify_user;
1613 if(in_array('set_notification_body', get_class_methods($this))) {
1614 $xtpl = $this->set_notification_body($xtpl, $this);
1616 $xtpl->assign("OBJECT", translate('LBL_MODULE_NAME'));
1617 $template_name = "Default";
1619 if(!empty($_SESSION["special_notification"]) && $_SESSION["special_notification"]) {
1620 $template_name = $beanList[$this->module_dir].'Special';
1622 if($this->special_notification) {
1623 $template_name = $beanList[$this->module_dir].'Special';
1625 $xtpl->assign("ASSIGNED_USER", $this->new_assigned_user_name);
1626 $xtpl->assign("ASSIGNER", $current_user->name);
1629 if(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
1630 $port = $_SERVER['SERVER_PORT'];
1633 if (!isset($_SERVER['HTTP_HOST'])) {
1634 $_SERVER['HTTP_HOST'] = '';
1637 $httpHost = $_SERVER['HTTP_HOST'];
1639 if($colon = strpos($httpHost, ':')) {
1640 $httpHost = substr($httpHost, 0, $colon);
1643 $parsedSiteUrl = parse_url($sugar_config['site_url']);
1644 $host = $parsedSiteUrl['host'];
1645 if(!isset($parsedSiteUrl['port'])) {
1646 $parsedSiteUrl['port'] = 80;
1649 $port = ($parsedSiteUrl['port'] != 80) ? ":".$parsedSiteUrl['port'] : '';
1650 $path = !empty($parsedSiteUrl['path']) ? $parsedSiteUrl['path'] : "";
1651 $cleanUrl = "{$parsedSiteUrl['scheme']}://{$host}{$port}{$path}";
1653 $xtpl->assign("URL", $cleanUrl."/index.php?module={$this->module_dir}&action=DetailView&record={$this->id}");
1654 $xtpl->assign("SUGAR", "Sugar v{$sugar_version}");
1655 $xtpl->parse($template_name);
1656 $xtpl->parse($template_name . "_Subject");
1658 $notify_mail->Body = from_html(trim($xtpl->text($template_name)));
1659 $notify_mail->Subject = from_html($xtpl->text($template_name . "_Subject"));
1661 // cn: bug 8568 encode notify email in User's outbound email encoding
1662 $notify_mail->prepForOutbound();
1664 return $notify_mail;
1668 * This function is a good location to save changes that have been made to a relationship.
1669 * This should be overridden in subclasses that have something to save.
1671 * @param boolean $is_update true if this save is an update.
1672 * @param array $exclude a way to exclude relationships
1674 public function save_relationship_changes($is_update, $exclude = array())
1676 list($new_rel_id, $new_rel_link) = $this->set_relationship_info($exclude);
1678 $new_rel_id = $this->handle_preset_relationships($new_rel_id, $new_rel_link, $exclude);
1680 $this->handle_remaining_relate_fields($exclude);
1682 $this->handle_request_relate($new_rel_id, $new_rel_link);
1686 * Look in the bean for the new relationship_id and relationship_name if $this->not_use_rel_in_req is set to true,
1687 * otherwise check the $_REQUEST param for a relate_id and relate_to field. Once we have that make sure that it's
1688 * not excluded from the passed in array of relationships to exclude
1690 * @param array $exclude any relationship's to exclude
1691 * @return array The relationship_id and relationship_name in an array
1693 protected function set_relationship_info($exclude = array())
1696 $new_rel_id = false;
1697 $new_rel_link = false;
1698 // check incoming data
1699 if (isset($this->not_use_rel_in_req) && $this->not_use_rel_in_req == true) {
1700 // if we should use relation data from properties (for REQUEST-independent calls)
1701 $rel_id = isset($this->new_rel_id) ? $this->new_rel_id : '';
1702 $rel_link = isset($this->new_rel_relname) ? $this->new_rel_relname : '';
1706 // if we should use relation data from REQUEST
1707 $rel_id = isset($_REQUEST['relate_id']) ? $_REQUEST['relate_id'] : '';
1708 $rel_link = isset($_REQUEST['relate_to']) ? $_REQUEST['relate_to'] : '';
1711 // filter relation data
1712 if ($rel_id && $rel_link && !in_array($rel_link, $exclude) && $rel_id != $this->id) {
1713 $new_rel_id = $rel_id;
1714 $new_rel_link = $rel_link;
1715 // Bug #53223 : wrong relationship from subpanel create button
1716 // if LHSModule and RHSModule are same module use left link to add new item b/s of:
1717 // $rel_id and $rel_link are not emty - request is from subpanel
1718 // $rel_link contains relationship name - checked by call load_relationship
1719 $isRelationshipLoaded = $this->load_relationship($rel_link);
1720 if ($isRelationshipLoaded && !empty($this->$rel_link) && $this->$rel_link->getRelationshipObject() && $this->$rel_link->getRelationshipObject()->getLHSModule() == $this->$rel_link->getRelationshipObject()->getRHSModule() )
1722 $new_rel_link = $this->$rel_link->getRelationshipObject()->getLHSLink();
1726 //Try to find the link in this bean based on the relationship
1727 foreach ($this->field_defs as $key => $def)
1729 if (isset($def['type']) && $def['type'] == 'link' && isset($def['relationship']) && $def['relationship'] == $rel_link)
1731 $new_rel_link = $key;
1737 return array($new_rel_id, $new_rel_link);
1741 * Handle the preset fields listed in the fixed relationship_fields array hardcoded into the OOB beans
1743 * TODO: remove this mechanism and replace with mechanism exclusively based on the vardefs
1746 * @see save_relationship_changes
1747 * @param string|boolean $new_rel_id String of the ID to add
1748 * @param string Relationship Name
1749 * @param array $exclude any relationship's to exclude
1750 * @return string|boolean Return the new_rel_id if it was not used. False if it was used.
1752 protected function handle_preset_relationships($new_rel_id, $new_rel_link, $exclude = array())
1754 if (isset($this->relationship_fields) && is_array($this->relationship_fields)) {
1755 foreach ($this->relationship_fields as $id => $rel_name)
1758 if (in_array($id, $exclude)) continue;
1760 if(!empty($this->$id))
1762 // Bug #44930 We do not need to update main related field if it is changed from sub-panel.
1763 if ($rel_name == $new_rel_link && $this->$id != $new_rel_id)
1767 $GLOBALS['log']->debug('save_relationship_changes(): From relationship_field array - adding a relationship record: '.$rel_name . ' = ' . $this->$id);
1768 //already related the new relationship id so let's set it to false so we don't add it again using the _REQUEST['relate_i'] mechanism in a later block
1769 $this->load_relationship($rel_name);
1770 $rel_add = $this->$rel_name->add($this->$id);
1771 // move this around to only take out the id if it was save successfully
1772 if ($this->$id == $new_rel_id && $rel_add == true) {
1773 $new_rel_id = false;
1776 //if before value is not empty then attempt to delete relationship
1777 if (!empty($this->rel_fields_before_value[$id])) {
1778 $GLOBALS['log']->debug('save_relationship_changes(): From relationship_field array - attempting to remove the relationship record, using relationship attribute' . $rel_name);
1779 $this->load_relationship($rel_name);
1780 $this->$rel_name->delete($this->id, $this->rel_fields_before_value[$id]);
1790 * Next, we'll attempt to update all of the remaining relate fields in the vardefs that have 'save' set in their field_def
1791 * Only the 'save' fields should be saved as some vardef entries today are not for display only purposes and break the application if saved
1792 * If the vardef has entries for field <a> of type relate, where a->id_name = <b> and field <b> of type link
1793 * then we receive a value for b from the MVC in the _REQUEST, and it should be set in the bean as $this->$b
1796 * @see save_relationship_changes
1797 * @param array $exclude any relationship's to exclude
1798 * @return array the list of relationships that were added or removed successfully or if they were a failure
1800 protected function handle_remaining_relate_fields($exclude = array())
1803 $modified_relationships = array(
1804 'add' => array('success' => array(), 'failure' => array()),
1805 'remove' => array('success' => array(), 'failure' => array()),
1808 foreach ($this->field_defs as $def)
1810 if ($def ['type'] == 'relate' && isset ($def ['id_name']) && isset ($def ['link']) && isset ($def['save'])) {
1811 if (in_array($def['id_name'], $exclude) || in_array($def['id_name'], $this->relationship_fields))
1812 continue; // continue to honor the exclude array and exclude any relationships that will be handled by the relationship_fields mechanism
1814 $linkField = $def ['link'];
1815 if (isset($this->field_defs[$linkField])) {
1816 if ($this->load_relationship($linkField)) {
1817 $idName = $def['id_name'];
1819 if (!empty($this->rel_fields_before_value[$idName]) && empty($this->$idName)) {
1820 //if before value is not empty then attempt to delete relationship
1821 $GLOBALS['log']->debug("save_relationship_changes(): From field_defs - attempting to remove the relationship record: {$def [ 'link' ]} = {$this->rel_fields_before_value[$def [ 'id_name' ]]}");
1822 $success = $this->$def ['link']->delete($this->id, $this->rel_fields_before_value[$def ['id_name']]);
1823 // just need to make sure it's true and not an array as it's possible to return an array
1824 if($success == true) {
1825 $modified_relationships['remove']['success'][] = $def['link'];
1827 $modified_relationships['remove']['failure'][] = $def['link'];
1829 $GLOBALS['log']->debug("save_relationship_changes(): From field_defs - attempting to remove the relationship record returned " . var_export($success, true));
1832 if (!empty($this->$idName) && is_string($this->$idName)) {
1833 $GLOBALS['log']->debug("save_relationship_changes(): From field_defs - attempting to add a relationship record - {$def [ 'link' ]} = {$this->$def [ 'id_name' ]}");
1835 $success = $this->$linkField->add($this->$idName);
1837 // just need to make sure it's true and not an array as it's possible to return an array
1838 if($success == true) {
1839 $modified_relationships['add']['success'][] = $linkField;
1841 $modified_relationships['add']['failure'][] = $linkField;
1844 $GLOBALS['log']->debug("save_relationship_changes(): From field_defs - add a relationship record returned " . var_export($success, true));
1847 $GLOBALS['log']->fatal("Failed to load relationship {$linkField} while saving {$this->module_dir}");
1853 return $modified_relationships;
1857 * Finally, we update a field listed in the _REQUEST['%/relate_id']/_REQUEST['relate_to'] mechanism (if it has not already been updated)
1860 * @see save_relationship_changes
1861 * @param string|boolean $new_rel_id
1862 * @param string $new_rel_link
1865 protected function handle_request_relate($new_rel_id, $new_rel_link)
1867 if (!empty($new_rel_id)) {
1869 if ($this->load_relationship($new_rel_link)) {
1870 return $this->$new_rel_link->add($new_rel_id);
1872 $lower_link = strtolower($new_rel_link);
1873 if ($this->load_relationship($lower_link)) {
1874 return $this->$lower_link->add($new_rel_id);
1877 require_once('data/Link2.php');
1878 $rel = Relationship::retrieve_by_modules($new_rel_link, $this->module_dir, $this->db, 'many-to-many');
1881 foreach ($this->field_defs as $field => $def) {
1882 if ($def['type'] == 'link' && !empty($def['relationship']) && $def['relationship'] == $rel) {
1883 $this->load_relationship($field);
1884 return $this->$field->add($new_rel_id);
1888 //ok so we didn't find it in the field defs let's save it anyway if we have the relationshp
1890 $this->$rel = new Link2($rel, $this, array());
1891 return $this->$rel->add($new_rel_id);
1897 // nothing was saved so just return false;
1902 * This function retrieves a record of the appropriate type from the DB.
1903 * It fills in all of the fields from the DB into the object it was called on.
1905 * @param $id - If ID is specified, it overrides the current value of $this->id. If not specified the current value of $this->id will be used.
1906 * @return this - The object that it was called apon or null if exactly 1 record was not found.
1910 function check_date_relationships_load()
1912 global $disable_date_format;
1914 if (empty($timedate))
1915 $timedate=TimeDate::getInstance();
1917 if(empty($this->field_defs))
1921 foreach($this->field_defs as $fieldDef)
1923 $field = $fieldDef['name'];
1924 if(!isset($this->processed_dates_times[$field]))
1926 $this->processed_dates_times[$field] = '1';
1927 if(empty($this->$field)) continue;
1928 if($field == 'date_modified' || $field == 'date_entered')
1930 $this->$field = $this->db->fromConvert($this->$field, 'datetime');
1931 if(empty($disable_date_format)) {
1932 $this->$field = $timedate->to_display_date_time($this->$field);
1935 elseif(isset($this->field_name_map[$field]['type']))
1937 $type = $this->field_name_map[$field]['type'];
1939 if($type == 'relate' && isset($this->field_name_map[$field]['custom_module']))
1941 $type = $this->field_name_map[$field]['type'];
1946 if($this->$field == '0000-00-00')
1949 } elseif(!empty($this->field_name_map[$field]['rel_field']))
1951 $rel_field = $this->field_name_map[$field]['rel_field'];
1953 if(!empty($this->$rel_field))
1955 if(empty($disable_date_format)) {
1956 $mergetime = $timedate->merge_date_time($this->$field,$this->$rel_field);
1957 $this->$field = $timedate->to_display_date($mergetime);
1958 $this->$rel_field = $timedate->to_display_time($mergetime);
1964 if(empty($disable_date_format)) {
1965 $this->$field = $timedate->to_display_date($this->$field, false);
1968 } elseif($type == 'datetime' || $type == 'datetimecombo')
1970 if($this->$field == '0000-00-00 00:00:00')
1976 if(empty($disable_date_format)) {
1977 $this->$field = $timedate->to_display_date_time($this->$field, true, true);
1980 } elseif($type == 'time')
1982 if($this->$field == '00:00:00')
1987 //$this->$field = from_db_convert($this->$field, 'time');
1988 if(empty($this->field_name_map[$field]['rel_field']) && empty($disable_date_format))
1990 $this->$field = $timedate->to_display_time($this->$field,true, false);
1993 } elseif($type == 'encrypt' && empty($disable_date_format)){
1994 $this->$field = $this->decrypt_after_retrieve($this->$field);
2002 * This function processes the fields before save.
2003 * Interal function, do not override.
2005 function preprocess_fields_on_save()
2007 $GLOBALS['log']->deprecated('SugarBean.php: preprocess_fields_on_save() is deprecated');
2011 * Removes formatting from values posted from the user interface.
2012 * It only unformats numbers. Function relies on user/system prefernce for format strings.
2014 * Internal Function, do not override.
2016 function unformat_all_fields()
2018 $GLOBALS['log']->deprecated('SugarBean.php: unformat_all_fields() is deprecated');
2022 * This functions adds formatting to all number fields before presenting them to user interface.
2024 * Internal function, do not override.
2026 function format_all_fields()
2028 $GLOBALS['log']->deprecated('SugarBean.php: format_all_fields() is deprecated');
2031 function format_field($fieldDef)
2033 $GLOBALS['log']->deprecated('SugarBean.php: format_field() is deprecated');
2037 * Function corrects any bad formatting done by 3rd party/custom code
2039 * This function will be removed in a future release, it is only here to assist upgrading existing code that expects formatted data in the bean
2041 function fixUpFormatting()
2044 static $boolean_false_values = array('off', 'false', '0', 'no');
2047 foreach($this->field_defs as $field=>$def)
2049 if ( !isset($this->$field) ) {
2052 if ( (isset($def['source'])&&$def['source']=='non-db') || $field == 'deleted' ) {
2055 if ( isset($this->fetched_row[$field]) && $this->$field == $this->fetched_row[$field] ) {
2056 // Don't hand out warnings because the field was untouched between retrieval and saving, most database drivers hand pretty much everything back as strings.
2059 $reformatted = false;
2060 switch($def['type']) {
2062 case 'datetimecombo':
2063 if(empty($this->$field)) break;
2064 if ($this->$field == 'NULL') {
2068 if ( ! preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/',$this->$field) ) {
2069 // This appears to be formatted in user date/time
2070 $this->$field = $timedate->to_db($this->$field);
2071 $reformatted = true;
2075 if(empty($this->$field)) break;
2076 if ($this->$field == 'NULL') {
2080 if ( ! preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$this->$field) ) {
2081 // This date appears to be formatted in the user's format
2082 $this->$field = $timedate->to_db_date($this->$field, false);
2083 $reformatted = true;
2087 if(empty($this->$field)) break;
2088 if ($this->$field == 'NULL') {
2092 if ( preg_match('/(am|pm)/i',$this->$field) ) {
2093 // This time appears to be formatted in the user's format
2094 $this->$field = $timedate->fromUserTime($this->$field)->format(TimeDate::DB_TIME_FORMAT);
2095 $reformatted = true;
2102 if ( $this->$field === '' || $this->$field == NULL || $this->$field == 'NULL') {
2105 if ( is_string($this->$field) ) {
2106 $this->$field = (float)unformat_number($this->$field);
2107 $reformatted = true;
2116 if ( $this->$field === '' || $this->$field == NULL || $this->$field == 'NULL') {
2119 if ( is_string($this->$field) ) {
2120 $this->$field = (int)unformat_number($this->$field);
2121 $reformatted = true;
2125 if (empty($this->$field)) {
2126 $this->$field = false;
2127 } else if(true === $this->$field || 1 == $this->$field) {
2128 $this->$field = true;
2129 } else if(in_array(strval($this->$field), $boolean_false_values)) {
2130 $this->$field = false;
2131 $reformatted = true;
2133 $this->$field = true;
2134 $reformatted = true;
2138 $this->$field = $this->encrpyt_before_save($this->$field);
2141 if ( $reformatted ) {
2142 $GLOBALS['log']->deprecated('Formatting correction: '.$this->module_dir.'->'.$field.' had formatting automatically corrected. This will be removed in the future, please upgrade your external code');
2149 * Function fetches a single row of data given the primary key value.
2151 * The fetched data is then set into the bean. The function also processes the fetched data by formattig
2152 * date/time and numeric values.
2154 * @param string $id Optional, default -1, is set to -1 id value from the bean is used, else, passed value is used
2155 * @param boolean $encode Optional, default true, encodes the values fetched from the database.
2156 * @param boolean $deleted Optional, default true, if set to false deleted filter will not be added.
2158 * Internal function, do not override.
2160 function retrieve($id = -1, $encode=true,$deleted=true)
2163 $custom_logic_arguments['id'] = $id;
2164 $this->call_custom_logic('before_retrieve', $custom_logic_arguments);
2170 if(isset($this->custom_fields))
2172 $custom_join = $this->custom_fields->getJOIN();
2175 $custom_join = false;
2179 $query = "SELECT $this->table_name.*". $custom_join['select']. " FROM $this->table_name ";
2183 $query = "SELECT $this->table_name.* FROM $this->table_name ";
2188 $query .= ' ' . $custom_join['join'];
2190 $query .= " WHERE $this->table_name.id = ".$this->db->quoted($id);
2191 if ($deleted) $query .= " AND $this->table_name.deleted=0";
2192 $GLOBALS['log']->debug("Retrieve $this->object_name : ".$query);
2193 $result = $this->db->limitQuery($query,0,1,true, "Retrieving record by id $this->table_name:$id found ");
2199 $row = $this->db->fetchByAssoc($result, $encode);
2205 //make copy of the fetched row for construction of audit record and for business logic/workflow
2206 $row = $this->convertRow($row);
2207 $this->fetched_row=$row;
2208 $this->populateFromRow($row);
2210 global $module, $action;
2211 //Just to get optimistic locking working for this release
2212 if($this->optimistic_lock && $module == $this->module_dir && $action =='EditView' )
2214 $_SESSION['o_lock_id']= $id;
2215 $_SESSION['o_lock_dm']= $this->date_modified;
2216 $_SESSION['o_lock_on'] = $this->object_name;
2218 $this->processed_dates_times = array();
2219 $this->check_date_relationships_load();
2223 $this->custom_fields->fill_relationships();
2226 $this->is_updated_dependent_fields = false;
2227 $this->fill_in_additional_detail_fields();
2228 $this->fill_in_relationship_fields();
2229 // save related fields values for audit
2230 foreach ($this->get_related_fields() as $rel_field_name)
2232 if (! empty($this->$rel_field_name['name']))
2234 $this->fetched_rel_row[$rel_field_name['name']] = $this->$rel_field_name['name'];
2237 //make a copy of fields in the relationship_fields array. These field values will be used to
2238 //clear relationship.
2239 foreach ( $this->field_defs as $key => $def )
2241 if ($def [ 'type' ] == 'relate' && isset ( $def [ 'id_name'] ) && isset ( $def [ 'link'] ) && isset ( $def[ 'save' ])) {
2242 if (isset($this->$key)) {
2243 $this->rel_fields_before_value[$key]=$this->$key;
2244 if (isset($this->$def [ 'id_name']))
2245 $this->rel_fields_before_value[$def [ 'id_name']]=$this->$def [ 'id_name'];
2248 $this->rel_fields_before_value[$key]=null;
2251 if (isset($this->relationship_fields) && is_array($this->relationship_fields))
2253 foreach ($this->relationship_fields as $rel_id=>$rel_name)
2255 if (isset($this->$rel_id))
2256 $this->rel_fields_before_value[$rel_id]=$this->$rel_id;
2258 $this->rel_fields_before_value[$rel_id]=null;
2262 // call the custom business logic
2263 $custom_logic_arguments['id'] = $id;
2264 $custom_logic_arguments['encode'] = $encode;
2265 $this->call_custom_logic("after_retrieve", $custom_logic_arguments);
2266 unset($custom_logic_arguments);
2271 * Sets value from fetched row into the bean.
2273 * @param array $row Fetched row
2274 * @todo loop through vardefs instead
2275 * @internal runs into an issue when populating from field_defs for users - corrupts user prefs
2277 * Internal function, do not override.
2279 function populateFromRow($row)
2282 foreach($this->field_defs as $field=>$field_value)
2284 if($field == 'user_preferences' && $this->module_dir == 'Users')
2286 if(isset($row[$field]))
2288 $this->$field = $row[$field];
2289 $owner = $field . '_owner';
2290 if(!empty($row[$owner])){
2291 $this->$owner = $row[$owner];
2296 $this->$field = $nullvalue;
2304 * Add any required joins to the list count query. The joins are required if there
2305 * is a field in the $where clause that needs to be joined.
2307 * @param string $query
2308 * @param string $where
2310 * Internal Function, do Not override.
2312 function add_list_count_joins(&$query, $where)
2314 $custom_join = $this->custom_fields->getJOIN();
2317 $query .= $custom_join['join'];
2323 * Changes the select expression of the given query to be 'count(*)' so you
2324 * can get the number of items the query will return. This is used to
2325 * populate the upper limit on ListViews.
2327 * @param string $query Select query string
2328 * @return string count query
2330 * Internal function, do not override.
2332 function create_list_count_query($query)
2334 // remove the 'order by' clause which is expected to be at the end of the query
2335 $pattern = '/\sORDER BY.*/is'; // ignores the case
2337 $query = preg_replace($pattern, $replacement, $query);
2338 //handle distinct clause
2340 if(substr_count(strtolower($query), 'distinct')){
2341 if (!empty($this->seed) && !empty($this->seed->table_name ))
2342 $star = 'DISTINCT ' . $this->seed->table_name . '.id';
2344 $star = 'DISTINCT ' . $this->table_name . '.id';
2348 // change the select expression to 'count(*)'
2349 $pattern = '/SELECT(.*?)(\s){1}FROM(\s){1}/is'; // ignores the case
2350 $replacement = 'SELECT count(' . $star . ') c FROM ';
2352 //if the passed query has union clause then replace all instances of the pattern.
2353 //this is very rare. I have seen this happening only from projects module.
2354 //in addition to this added a condition that has union clause and uses
2356 if (strstr($query," UNION ALL ") !== false) {
2358 //separate out all the queries.
2359 $union_qs=explode(" UNION ALL ", $query);
2360 foreach ($union_qs as $key=>$union_query) {
2362 preg_match($pattern, $union_query, $matches);
2363 if (!empty($matches)) {
2364 if (stristr($matches[0], "distinct")) {
2365 if (!empty($this->seed) && !empty($this->seed->table_name ))
2366 $star = 'DISTINCT ' . $this->seed->table_name . '.id';
2368 $star = 'DISTINCT ' . $this->table_name . '.id';
2371 $replacement = 'SELECT count(' . $star . ') c FROM ';
2372 $union_qs[$key] = preg_replace($pattern, $replacement, $union_query,1);
2374 $modified_select_query=implode(" UNION ALL ",$union_qs);
2376 $modified_select_query = preg_replace($pattern, $replacement, $query,1);
2380 return $modified_select_query;
2384 * This function returns a paged list of the current object type. It is intended to allow for
2385 * hopping back and forth through pages of data. It only retrieves what is on the current page.
2387 * @internal This method must be called on a new instance. It trashes the values of all the fields in the current one.
2388 * @param string $order_by
2389 * @param string $where Additional where clause
2390 * @param int $row_offset Optaional,default 0, starting row number
2391 * @param init $limit Optional, default -1
2392 * @param int $max Optional, default -1
2393 * @param boolean $show_deleted Optional, default 0, if set to 1 system will show deleted records.
2394 * @return array Fetched data.
2396 * Internal function, do not override.
2399 function get_list($order_by = "", $where = "", $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $singleSelect=false, $select_fields = array())
2401 $GLOBALS['log']->debug("get_list: order_by = '$order_by' and where = '$where' and limit = '$limit'");
2402 if(isset($_SESSION['show_deleted']))
2406 $order_by=$this->process_order_by($order_by);
2408 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2410 global $current_user;
2411 $owner_where = $this->getOwnerWhere($current_user->id);
2413 //rrs - because $this->getOwnerWhere() can return '' we need to be sure to check for it and
2414 //handle it properly else you could get into a situation where you are create a where stmt like
2416 if(!empty($owner_where)){
2418 $where = $owner_where;
2420 $where .= ' AND '. $owner_where;
2424 $query = $this->create_new_list_query($order_by, $where,$select_fields,array(), $show_deleted,'',false,null,$singleSelect);
2425 return $this->process_list_query($query, $row_offset, $limit, $max, $where);
2429 * Prefixes column names with this bean's table name.
2431 * @param string $order_by Order by clause to be processed
2432 * @param SugarBean $submodule name of the module this order by clause is for
2433 * @return string Processed order by clause
2435 * Internal function, do not override.
2437 function process_order_by ($order_by, $submodule = null)
2439 if (empty($order_by))
2441 //submodule is empty,this is for list object in focus
2442 if (empty($submodule))
2444 $bean_queried = $this;
2448 //submodule is set, so this is for subpanel, use submodule
2449 $bean_queried = $submodule;
2451 $elements = explode(',',$order_by);
2452 foreach ($elements as $key=>$value)
2454 if (strchr($value,'.') === false)
2456 //value might have ascending and descending decorations
2457 $list_column = explode(' ',trim($value));
2458 if (isset($list_column[0]))
2460 $list_column_name=trim($list_column[0]);
2461 if (isset($bean_queried->field_defs[$list_column_name]))
2463 $source=isset($bean_queried->field_defs[$list_column_name]['source']) ? $bean_queried->field_defs[$list_column_name]['source']:'db';
2464 if (empty($bean_queried->field_defs[$list_column_name]['table']) && $source=='db')
2466 $list_column[0] = $bean_queried->table_name .".".$list_column[0] ;
2468 if (empty($bean_queried->field_defs[$list_column_name]['table']) && $source=='custom_fields')
2470 $list_column[0] = $bean_queried->table_name ."_cstm.".$list_column[0] ;
2472 // Bug 38803 - Use CONVERT() function when doing an order by on ntext, text, and image fields
2473 if ($source != 'non-db' && $this->db->isTextType($this->db->getFieldType($bean_queried->field_defs[$list_column_name]))) {
2474 $list_column[0] = $this->db->convert($list_column[0], "text2char");
2476 $value = implode(' ',$list_column);
2478 $GLOBALS['log']->debug("process_order_by: ($list_column[0]) does not have a vardef entry.");
2482 $elements[$key]=$value;
2484 return implode(',', $elements);
2490 * Returns a detail object like retrieving of the current object type.
2492 * It is intended for use in navigation buttons on the DetailView. It will pass an offset and limit argument to the sql query.
2493 * @internal This method must be called on a new instance. It overrides the values of all the fields in the current one.
2495 * @param string $order_by
2496 * @param string $where Additional where clause
2497 * @param int $row_offset Optaional,default 0, starting row number
2498 * @param init $limit Optional, default -1
2499 * @param int $max Optional, default -1
2500 * @param boolean $show_deleted Optioanl, default 0, if set to 1 system will show deleted records.
2501 * @return array Fetched data.
2503 * Internal function, do not override.
2505 function get_detail($order_by = "", $where = "", $offset = 0, $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)
2507 $GLOBALS['log']->debug("get_detail: order_by = '$order_by' and where = '$where' and limit = '$limit' and offset = '$offset'");
2508 if(isset($_SESSION['show_deleted']))
2513 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2515 global $current_user;
2516 $owner_where = $this->getOwnerWhere($current_user->id);
2520 $where = $owner_where;
2524 $where .= ' AND '. $owner_where;
2527 $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted, $offset);
2529 //Add Limit and Offset to query
2530 //$query .= " LIMIT 1 OFFSET $offset";
2532 return $this->process_detail_query($query, $row_offset, $limit, $max, $where, $offset);
2536 * Fetches data from all related tables.
2538 * @param object $child_seed
2539 * @param string $related_field_name relation to fetch data for
2540 * @param string $order_by Optional, default empty
2541 * @param string $where Optional, additional where clause
2542 * @return array Fetched data.
2544 * Internal function, do not override.
2546 function get_related_list($child_seed,$related_field_name, $order_by = "", $where = "",
2547 $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)
2549 global $layout_edit_mode;
2550 $query_array = array();
2552 if(isset($layout_edit_mode) && $layout_edit_mode)
2554 $response = array();
2555 $child_seed->assign_display_fields($child_seed->module_dir);
2556 $response['list'] = array($child_seed);
2557 $response['row_count'] = 1;
2558 $response['next_offset'] = 0;
2559 $response['previous_offset'] = 0;
2563 $GLOBALS['log']->debug("get_related_list: order_by = '$order_by' and where = '$where' and limit = '$limit'");
2564 if(isset($_SESSION['show_deleted']))
2569 $this->load_relationship($related_field_name);
2571 if ($this->$related_field_name instanceof Link) {
2573 $query_array = $this->$related_field_name->getQuery(true);
2576 $query_array = $this->$related_field_name->getQuery(array(
2577 "return_as_array" => true,
2578 'where' => '1=1' // hook for 'where' clause in M2MRelationship file
2582 $entire_where = $query_array['where'];
2585 if(empty($entire_where))
2587 $entire_where = ' WHERE ' . $where;
2591 $entire_where .= ' AND ' . $where;
2595 $query = 'SELECT '.$child_seed->table_name.'.* ' . $query_array['from'] . ' ' . $entire_where;
2596 if(!empty($order_by))
2598 $query .= " ORDER BY " . $order_by;
2601 return $child_seed->process_list_query($query, $row_offset, $limit, $max, $where);
2605 protected static function build_sub_queries_for_union($subpanel_list, $subpanel_def, $parentbean, $order_by)
2607 global $layout_edit_mode, $beanFiles, $beanList;
2608 $subqueries = array();
2609 foreach($subpanel_list as $this_subpanel)
2611 if(!$this_subpanel->isDatasourceFunction() || ($this_subpanel->isDatasourceFunction()
2612 && isset($this_subpanel->_instance_properties['generate_select'])
2613 && $this_subpanel->_instance_properties['generate_select']==true))
2615 //the custom query function must return an array with
2616 if ($this_subpanel->isDatasourceFunction()) {
2617 $shortcut_function_name = $this_subpanel->get_data_source_name();
2618 $parameters=$this_subpanel->get_function_parameters();
2619 if (!empty($parameters))
2621 //if the import file function is set, then import the file to call the custom function from
2622 if (is_array($parameters) && isset($parameters['import_function_file'])){
2623 //this call may happen multiple times, so only require if function does not exist
2624 if(!function_exists($shortcut_function_name)){
2625 require_once($parameters['import_function_file']);
2627 //call function from required file
2628 $query_array = $shortcut_function_name($parameters);
2630 //call function from parent bean
2631 $query_array = $parentbean->$shortcut_function_name($parameters);
2636 $query_array = $parentbean->$shortcut_function_name();
2639 $related_field_name = $this_subpanel->get_data_source_name();
2640 if (!$parentbean->load_relationship($related_field_name)){
2641 unset ($parentbean->$related_field_name);
2644 $query_array = $parentbean->$related_field_name->getSubpanelQuery(array(), true);
2646 $table_where = preg_replace('/^\s*WHERE/i', '', $this_subpanel->get_where());
2647 $where_definition = preg_replace('/^\s*WHERE/i', '', $query_array['where']);
2649 if(!empty($table_where))
2651 if(empty($where_definition))
2653 $where_definition = $table_where;
2657 $where_definition .= ' AND ' . $table_where;
2661 $submodulename = $this_subpanel->_instance_properties['module'];
2662 $submoduleclass = $beanList[$submodulename];
2663 //require_once($beanFiles[$submoduleclass]);
2665 /** @var SugarBean $submodule */
2666 $submodule = new $submoduleclass();
2667 $subwhere = $where_definition;
2671 $list_fields = $this_subpanel->get_list_fields();
2672 foreach($list_fields as $list_key=>$list_field)
2674 if(isset($list_field['usage']) && $list_field['usage'] == 'display_only')
2676 unset($list_fields[$list_key]);
2681 if(!$subpanel_def->isCollection() && isset($list_fields[$order_by]) && isset($submodule->field_defs[$order_by])&& (!isset($submodule->field_defs[$order_by]['source']) || $submodule->field_defs[$order_by]['source'] == 'db'))
2683 $order_by = $submodule->table_name .'.'. $order_by;
2685 $table_name = $this_subpanel->table_name;
2686 $panel_name=$this_subpanel->name;
2688 $params['distinct'] = $this_subpanel->distinct_query();
2690 $params['joined_tables'] = $query_array['join_tables'];
2691 $params['include_custom_fields'] = !$subpanel_def->isCollection();
2692 $params['collection_list'] = $subpanel_def->get_inst_prop_value('collection_list');
2694 // use single select in case when sorting by relate field
2695 $singleSelect = $submodule->is_relate_field($order_by);
2697 $subquery = $submodule->create_new_list_query('',$subwhere ,$list_fields,$params, 0,'', true,$parentbean, $singleSelect);
2699 $subquery['select'] = $subquery['select']." , '$panel_name' panel_name ";
2700 $subquery['from'] = $subquery['from'].$query_array['join'];
2701 $subquery['query_array'] = $query_array;
2702 $subquery['params'] = $params;
2704 $subqueries[] = $subquery;
2711 * Constructs a query to fetch data for supanels and list views
2713 * It constructs union queries for activities subpanel.
2715 * @param SugarBean $parentbean constructing queries for link attributes in this bean
2716 * @param string $order_by Optional, order by clause
2717 * @param string $sort_order Optional, sort order
2718 * @param string $where Optional, additional where clause
2720 * Internal Function, do not overide.
2722 function get_union_related_list($parentbean, $order_by = "", $sort_order='', $where = "",
2723 $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $subpanel_def)
2725 $secondary_queries = array();
2726 global $layout_edit_mode, $beanFiles, $beanList;
2728 if(isset($_SESSION['show_deleted']))
2733 $final_query_rows = '';
2734 $subpanel_list=array();
2735 if ($subpanel_def->isCollection())
2737 $subpanel_def->load_sub_subpanels();
2738 $subpanel_list=$subpanel_def->sub_subpanels;
2742 $subpanel_list[]=$subpanel_def;
2747 //Breaking the building process into two loops. The first loop gets a list of all the sub-queries.
2748 //The second loop merges the queries and forces them to select the same number of columns
2749 //All columns in a sub-subpanel group must have the same aliases
2750 //If the subpanel is a datasource function, it can't be a collection so we just poll that function for the and return that
2751 foreach($subpanel_list as $this_subpanel)
2753 if($this_subpanel->isDatasourceFunction() && empty($this_subpanel->_instance_properties['generate_select']))
2755 $shortcut_function_name = $this_subpanel->get_data_source_name();
2756 $parameters=$this_subpanel->get_function_parameters();
2757 if (!empty($parameters))
2759 //if the import file function is set, then import the file to call the custom function from
2760 if (is_array($parameters) && isset($parameters['import_function_file'])){
2761 //this call may happen multiple times, so only require if function does not exist
2762 if(!function_exists($shortcut_function_name)){
2763 require_once($parameters['import_function_file']);
2765 //call function from required file
2766 $tmp_final_query = $shortcut_function_name($parameters);
2768 //call function from parent bean
2769 $tmp_final_query = $parentbean->$shortcut_function_name($parameters);
2772 $tmp_final_query = $parentbean->$shortcut_function_name();
2776 $final_query_rows .= ' UNION ALL ( '.$parentbean->create_list_count_query($tmp_final_query, $parameters) . ' )';
2777 $final_query .= ' UNION ALL ( '.$tmp_final_query . ' )';
2779 $final_query_rows = '(' . $parentbean->create_list_count_query($tmp_final_query, $parameters) . ')';
2780 $final_query = '(' . $tmp_final_query . ')';
2785 //If final_query is still empty, its time to build the sub-queries
2786 if (empty($final_query))
2788 $subqueries = SugarBean::build_sub_queries_for_union($subpanel_list, $subpanel_def, $parentbean, $order_by);
2789 $all_fields = array();
2790 foreach($subqueries as $i => $subquery)
2792 $query_fields = $GLOBALS['db']->getSelectFieldsFromQuery($subquery['select']);
2793 foreach($query_fields as $field => $select)
2795 if (!in_array($field, $all_fields))
2796 $all_fields[] = $field;
2798 $subqueries[$i]['query_fields'] = $query_fields;
2801 //Now ensure the queries have the same set of fields in the same order.
2802 foreach($subqueries as $subquery)
2804 $subquery['select'] = "SELECT";
2805 foreach($all_fields as $field)
2807 if (!isset($subquery['query_fields'][$field]))
2809 $subquery['select'] .= " ' ' $field,";
2813 $subquery['select'] .= " {$subquery['query_fields'][$field]},";
2816 $subquery['select'] = substr($subquery['select'], 0 , strlen($subquery['select']) - 1);
2817 //Put the query into the final_query
2818 $query = $subquery['select'] . " " . $subquery['from'] . " " . $subquery['where'];
2821 $query = ' UNION ALL ( '.$query . ' )';
2822 $final_query_rows .= " UNION ALL ";
2824 $query = '(' . $query . ')';
2827 $query_array = $subquery['query_array'];
2828 $select_position=strpos($query_array['select'],"SELECT");
2829 $distinct_position=strpos($query_array['select'],"DISTINCT");
2830 if (!empty($subquery['params']['distinct']) && !empty($subpanel_def->table_name))
2832 $query_rows = "( SELECT count(DISTINCT ". $subpanel_def->table_name . ".id)". $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2834 elseif ($select_position !== false && $distinct_position!= false)
2836 $query_rows = "( ".substr_replace($query_array['select'],"SELECT count(",$select_position,6). ")" . $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2840 //resort to default behavior.
2841 $query_rows = "( SELECT count(*)". $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2843 if(!empty($subquery['secondary_select']))
2846 $subquerystring= $subquery['secondary_select'] . $subquery['secondary_from'].$query_array['join']. $subquery['where'];
2847 if (!empty($subquery['secondary_where']))
2849 if (empty($subquery['where']))
2851 $subquerystring.=" WHERE " .$subquery['secondary_where'];
2855 $subquerystring.=" AND " .$subquery['secondary_where'];
2858 $secondary_queries[]=$subquerystring;
2860 $final_query .= $query;
2861 $final_query_rows .= $query_rows;
2865 if(!empty($order_by))
2868 if(!$subpanel_def->isCollection())
2870 $submodulename = $subpanel_def->_instance_properties['module'];
2871 $submoduleclass = $beanList[$submodulename];
2872 $submodule = new $submoduleclass();
2874 if(!empty($submodule) && !empty($submodule->table_name))
2876 $final_query .= " ORDER BY " .$parentbean->process_order_by($order_by, $submodule);
2881 $final_query .= " ORDER BY ". $order_by . ' ';
2883 if(!empty($sort_order))
2885 $final_query .= ' ' .$sort_order;
2890 if(isset($layout_edit_mode) && $layout_edit_mode)
2892 $response = array();
2893 if(!empty($submodule))
2895 $submodule->assign_display_fields($submodule->module_dir);
2896 $response['list'] = array($submodule);
2900 $response['list'] = array();
2902 $response['parent_data'] = array();
2903 $response['row_count'] = 1;
2904 $response['next_offset'] = 0;
2905 $response['previous_offset'] = 0;
2910 return $parentbean->process_union_list_query($parentbean, $final_query, $row_offset, $limit, $max, '',$subpanel_def, $final_query_rows, $secondary_queries);
2915 * Returns a full (ie non-paged) list of the current object type.
2917 * @param string $order_by the order by SQL parameter. defaults to ""
2918 * @param string $where where clause. defaults to ""
2919 * @param boolean $check_dates. defaults to false
2920 * @param int $show_deleted show deleted records. defaults to 0
2922 function get_full_list($order_by = "", $where = "", $check_dates=false, $show_deleted = 0)
2924 $GLOBALS['log']->debug("get_full_list: order_by = '$order_by' and where = '$where'");
2925 if(isset($_SESSION['show_deleted']))
2929 $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted);
2930 return $this->process_full_list_query($query, $check_dates);
2934 * Return the list query used by the list views and export button. Next generation of create_new_list_query function.
2936 * Override this function to return a custom query.
2938 * @param string $order_by custom order by clause
2939 * @param string $where custom where clause
2940 * @param array $filter Optioanal
2941 * @param array $params Optional *
2942 * @param int $show_deleted Optional, default 0, show deleted records is set to 1.
2943 * @param string $join_type
2944 * @param boolean $return_array Optional, default false, response as array
2945 * @param object $parentbean creating a subquery for this bean.
2946 * @param boolean $singleSelect Optional, default false.
2947 * @return String select query string, optionally an array value will be returned if $return_array= true.
2949 function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false, $ifListForExport = false)
2951 global $beanFiles, $beanList;
2952 $selectedFields = array();
2953 $secondarySelectedFields = array();
2954 $ret_array = array();
2956 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2958 global $current_user;
2959 $owner_where = $this->getOwnerWhere($current_user->id);
2962 $where = $owner_where;
2966 $where .= ' AND '. $owner_where;
2969 if(!empty($params['distinct']))
2971 $distinct = ' DISTINCT ';
2975 $ret_array['select'] = " SELECT $distinct $this->table_name.* ";
2979 $ret_array['select'] = " SELECT $distinct $this->table_name.id ";
2981 $ret_array['from'] = " FROM $this->table_name ";
2982 $ret_array['from_min'] = $ret_array['from'];
2983 $ret_array['secondary_from'] = $ret_array['from'] ;
2984 $ret_array['where'] = '';
2985 $ret_array['order_by'] = '';
2986 //secondary selects are selects that need to be run after the primary query to retrieve additional info on main
2989 $ret_array['secondary_select']=& $ret_array['select'];
2990 $ret_array['secondary_from'] = & $ret_array['from'];
2994 $ret_array['secondary_select'] = '';
2996 $custom_join = false;
2997 if((!isset($params['include_custom_fields']) || $params['include_custom_fields']) && isset($this->custom_fields))
3000 $custom_join = $this->custom_fields->getJOIN( empty($filter)? true: $filter );
3003 $ret_array['select'] .= ' ' .$custom_join['select'];
3008 $ret_array['from'] .= ' ' . $custom_join['join'];
3009 // Bug 52490 - Captivea (Sve) - To be able to add custom fields inside where clause in a subpanel
3010 $ret_array['from_min'] .= ' ' . $custom_join['join'];
3013 //LOOP AROUND FOR FIXIN VARDEF ISSUES
3014 require('include/VarDefHandler/listvardefoverride.php');
3015 if (file_exists('custom/include/VarDefHandler/listvardefoverride.php'))
3017 require('custom/include/VarDefHandler/listvardefoverride.php');
3020 $joined_tables = array();
3021 if(!empty($params['joined_tables']))
3023 foreach($params['joined_tables'] as $table)
3025 $joined_tables[$table] = 1;
3031 $filterKeys = array_keys($filter);
3032 if(is_numeric($filterKeys[0]))
3035 foreach($filter as $field)
3037 $field = strtolower($field);
3038 //remove out id field so we don't duplicate it
3039 if ( $field == 'id' && !empty($filter) ) {
3042 if(isset($this->field_defs[$field]))
3044 $fields[$field]= $this->field_defs[$field];
3048 $fields[$field] = array('force_exists'=>true);
3057 $fields = $this->field_defs;
3060 $used_join_key = array();
3062 foreach($fields as $field=>$value)
3064 //alias is used to alias field names
3066 if (isset($value['alias']))
3068 $alias =' as ' . $value['alias'] . ' ';
3071 if(empty($this->field_defs[$field]) || !empty($value['force_blank']) )
3073 if(!empty($filter) && isset($filter[$field]['force_exists']) && $filter[$field]['force_exists'])
3075 if ( isset($filter[$field]['force_default']) )
3076 $ret_array['select'] .= ", {$filter[$field]['force_default']} $field ";
3078 //spaces are a fix for length issue problem with unions. The union only returns the maximum number of characters from the first select statement.
3079 $ret_array['select'] .= ", ' ' $field ";
3085 $data = $this->field_defs[$field];
3088 //ignore fields that are a part of the collection and a field has been removed as a result of
3089 //layout customization.. this happens in subpanel customizations, use case, from the contacts subpanel
3090 //in opportunities module remove the contact_role/opportunity_role field.
3091 $process_field=true;
3092 if (isset($data['relationship_fields']) and !empty($data['relationship_fields']))
3094 foreach ($data['relationship_fields'] as $field_name)
3096 if (!isset($fields[$field_name]))
3098 $process_field=false;
3102 if (!$process_field)
3107 if( (!isset($data['source']) || $data['source'] == 'db') && (!empty($alias) || !empty($filter) ))
3109 $ret_array['select'] .= ", $this->table_name.$field $alias";
3110 $selectedFields["$this->table_name.$field"] = true;
3111 } else if( (!isset($data['source']) || $data['source'] == 'custom_fields') && (!empty($alias) || !empty($filter) )) {
3112 //add this column only if it has NOT already been added to select statement string
3113 $colPos = strpos($ret_array['select'],"$this->table_name"."_cstm".".$field");
3114 if(!$colPos || $colPos<0)
3116 $ret_array['select'] .= ", $this->table_name"."_cstm".".$field $alias";
3119 $selectedFields["$this->table_name.$field"] = true;
3122 if($data['type'] != 'relate' && isset($data['db_concat_fields']))
3124 $ret_array['select'] .= ", " . $this->db->concat($this->table_name, $data['db_concat_fields']) . " as $field";
3125 $selectedFields[$this->db->concat($this->table_name, $data['db_concat_fields'])] = true;
3127 //Custom relate field or relate fields built in module builder which have no link field associated.
3128 if ($data['type'] == 'relate' && (isset($data['custom_module']) || isset($data['ext2']))) {
3129 $joinTableAlias = 'jt' . $jtcount;
3130 $relateJoinInfo = $this->custom_fields->getRelateJoin($data, $joinTableAlias);
3131 $ret_array['select'] .= $relateJoinInfo['select'];
3132 $ret_array['from'] .= $relateJoinInfo['from'];
3133 //Replace any references to the relationship in the where clause with the new alias
3134 //If the link isn't set, assume that search used the local table for the field
3135 $searchTable = isset($data['link']) ? $relateJoinInfo['rel_table'] : $this->table_name;
3136 $field_name = $relateJoinInfo['rel_table'] . '.' . !empty($data['name'])?$data['name']:'name';
3137 $where = preg_replace('/(^|[\s(])' . $field_name . '/' , '${1}' . $relateJoinInfo['name_field'], $where);
3141 if ($data['type'] == 'parent') {
3142 //See if we need to join anything by inspecting the where clause
3143 $match = preg_match('/(^|[\s(])parent_(\w+)_(\w+)\.name/', $where, $matches);
3145 $joinTableAlias = 'jt' . $jtcount;
3146 $joinModule = $matches[2];
3147 $joinTable = $matches[3];
3148 $localTable = $this->table_name;
3149 if (!empty($data['custom_module'])) {
3150 $localTable .= '_cstm';
3152 global $beanFiles, $beanList, $module;
3153 require_once($beanFiles[$beanList[$joinModule]]);
3154 $rel_mod = new $beanList[$joinModule]();
3155 $nameField = "$joinTableAlias.name";
3156 if (isset($rel_mod->field_defs['name']))
3158 $name_field_def = $rel_mod->field_defs['name'];
3159 if(isset($name_field_def['db_concat_fields']))
3161 $nameField = $this->db->concat($joinTableAlias, $name_field_def['db_concat_fields']);
3164 $ret_array['select'] .= ", $nameField {$data['name']} ";
3165 $ret_array['from'] .= " LEFT JOIN $joinTable $joinTableAlias
3166 ON $localTable.{$data['id_name']} = $joinTableAlias.id";
3167 //Replace any references to the relationship in the where clause with the new alias
3168 $where = preg_replace('/(^|[\s(])parent_' . $joinModule . '_' . $joinTable . '\.name/', '${1}' . $nameField, $where);
3173 if ($this->is_relate_field($field))
3175 $this->load_relationship($data['link']);
3176 if(!empty($this->$data['link']))
3179 if(empty($join_type))
3181 $params['join_type'] = ' LEFT JOIN ';
3185 $params['join_type'] = $join_type;
3187 if(isset($data['join_name']))
3189 $params['join_table_alias'] = $data['join_name'];
3193 $params['join_table_alias'] = 'jt' . $jtcount;
3196 if(isset($data['join_link_name']))
3198 $params['join_table_link_alias'] = $data['join_link_name'];
3202 $params['join_table_link_alias'] = 'jtl' . $jtcount;
3204 $join_primary = !isset($data['join_primary']) || $data['join_primary'];
3206 $join = $this->$data['link']->getJoin($params, true);
3207 $used_join_key[] = $join['rel_key'];
3208 $rel_module = $this->$data['link']->getRelatedModuleName();
3209 $table_joined = !empty($joined_tables[$params['join_table_alias']]) || (!empty($joined_tables[$params['join_table_link_alias']]) && isset($data['link_type']) && $data['link_type'] == 'relationship_info');
3211 //if rname is set to 'name', and bean files exist, then check if field should be a concatenated name
3212 global $beanFiles, $beanList;
3213 if($data['rname'] && !empty($beanFiles[$beanList[$rel_module]])) {
3215 //create an instance of the related bean
3216 require_once($beanFiles[$beanList[$rel_module]]);
3217 $rel_mod = new $beanList[$rel_module]();
3218 //if bean has first and last name fields, then name should be concatenated
3219 if(isset($rel_mod->field_name_map['first_name']) && isset($rel_mod->field_name_map['last_name'])){
3220 $data['db_concat_fields'] = array(0=>'first_name', 1=>'last_name');
3225 if($join['type'] == 'many-to-many')
3227 if(empty($ret_array['secondary_select']))
3229 $ret_array['secondary_select'] = " SELECT $this->table_name.id ref_id ";
3231 if(!empty($beanFiles[$beanList[$rel_module]]) && $join_primary)
3233 require_once($beanFiles[$beanList[$rel_module]]);
3234 $rel_mod = new $beanList[$rel_module]();
3235 if(isset($rel_mod->field_defs['assigned_user_id']))
3237 $ret_array['secondary_select'].= " , ". $params['join_table_alias'] . ".assigned_user_id {$field}_owner, '$rel_module' {$field}_mod";
3241 if(isset($rel_mod->field_defs['created_by']))
3243 $ret_array['secondary_select'].= " , ". $params['join_table_alias'] . ".created_by {$field}_owner , '$rel_module' {$field}_mod";
3249 if(isset($data['db_concat_fields']))
3251 $ret_array['secondary_select'] .= ' , ' . $this->db->concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
3255 if(!isset($data['relationship_fields']))
3257 $ret_array['secondary_select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
3262 $ret_array['select'] .= ", ' ' $field ";
3265 foreach($used_join_key as $used_key) {
3266 if($used_key == $join['rel_key']) $count_used++;
3268 if($count_used <= 1) {//27416, the $ret_array['secondary_select'] should always generate, regardless the dbtype
3269 // add rel_key only if it was not aready added
3272 $ret_array['select'] .= ", ' ' " . $join['rel_key'] . ' ';
3274 $ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'].'.'. $join['rel_key'] .' ' . $join['rel_key'];
3276 if(isset($data['relationship_fields']))
3278 foreach($data['relationship_fields'] as $r_name=>$alias_name)
3280 if(!empty( $secondarySelectedFields[$alias_name]))continue;
3281 $ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'].'.'. $r_name .' ' . $alias_name;
3282 $secondarySelectedFields[$alias_name] = true;
3287 $ret_array['secondary_from'] .= ' ' . $join['join']. ' AND ' . $params['join_table_alias'].'.deleted=0';
3288 if (isset($data['link_type']) && $data['link_type'] == 'relationship_info' && ($parentbean instanceOf SugarBean))
3290 $ret_array['secondary_where'] = $params['join_table_link_alias'] . '.' . $join['rel_key']. "='" .$parentbean->id . "'";
3296 if(isset($data['db_concat_fields']))
3298 $ret_array['select'] .= ' , ' . $this->db->concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
3302 $ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
3304 if(isset($data['additionalFields'])){
3305 foreach($data['additionalFields'] as $k=>$v){
3306 $ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $k . ' ' . $v;
3311 $ret_array['from'] .= ' ' . $join['join']. ' AND ' . $params['join_table_alias'].'.deleted=0';
3312 if(!empty($beanList[$rel_module]) && !empty($beanFiles[$beanList[$rel_module]]))
3314 require_once($beanFiles[$beanList[$rel_module]]);
3315 $rel_mod = new $beanList[$rel_module]();
3316 if(isset($value['target_record_key']) && !empty($filter))
3318 $selectedFields[$this->table_name.'.'.$value['target_record_key']] = true;
3319 $ret_array['select'] .= " , $this->table_name.{$value['target_record_key']} ";
3321 if(isset($rel_mod->field_defs['assigned_user_id']))
3323 $ret_array['select'] .= ' , ' .$params['join_table_alias'] . '.assigned_user_id ' . $field . '_owner';
3327 $ret_array['select'] .= ' , ' .$params['join_table_alias'] . '.created_by ' . $field . '_owner';
3329 $ret_array['select'] .= " , '".$rel_module ."' " . $field . '_mod';
3334 // To fix SOAP stuff where we are trying to retrieve all the accounts data where accounts.id = ..
3335 // and this code changes accounts to jt4 as there is a self join with the accounts table.
3337 if(isset($data['db_concat_fields'])){
3338 $buildWhere = false;
3339 if(in_array('first_name', $data['db_concat_fields']) && in_array('last_name', $data['db_concat_fields']))
3341 $exp = '/\(\s*?'.$data['name'].'.*?\%\'\s*?\)/';
3342 if(preg_match($exp, $where, $matches))
3344 $search_expression = $matches[0];
3345 //Create three search conditions - first + last, first, last
3346 $first_name_search = str_replace($data['name'], $params['join_table_alias'] . '.first_name', $search_expression);
3347 $last_name_search = str_replace($data['name'], $params['join_table_alias'] . '.last_name', $search_expression);
3348 $full_name_search = str_replace($data['name'], $this->db->concat($params['join_table_alias'], $data['db_concat_fields']), $search_expression);
3350 $where = str_replace($search_expression, '(' . $full_name_search . ' OR ' . $first_name_search . ' OR ' . $last_name_search . ')', $where);
3356 $db_field = $this->db->concat($params['join_table_alias'], $data['db_concat_fields']);
3357 $where = preg_replace('/'.$data['name'].'/', $db_field, $where);
3360 $where = preg_replace('/(^|[\s(])' . $data['name'] . '/', '${1}' . $params['join_table_alias'] . '.'.$data['rname'], $where);
3364 $joined_tables[$params['join_table_alias']]=1;
3365 $joined_tables[$params['join_table_link_alias']]=1;
3374 if(isset($this->field_defs['assigned_user_id']) && empty($selectedFields[$this->table_name.'.assigned_user_id']))
3376 $ret_array['select'] .= ", $this->table_name.assigned_user_id ";
3378 else if(isset($this->field_defs['created_by']) && empty($selectedFields[$this->table_name.'.created_by']))
3380 $ret_array['select'] .= ", $this->table_name.created_by ";
3382 if(isset($this->field_defs['system_id']) && empty($selectedFields[$this->table_name.'.system_id']))
3384 $ret_array['select'] .= ", $this->table_name.system_id ";
3389 if ($ifListForExport) {
3390 if(isset($this->field_defs['email1'])) {
3391 $ret_array['select'].= " ,email_addresses.email_address email1";
3392 $ret_array['from'].= " LEFT JOIN email_addr_bean_rel on {$this->table_name}.id = email_addr_bean_rel.bean_id and email_addr_bean_rel.bean_module='{$this->module_dir}' and email_addr_bean_rel.deleted=0 and email_addr_bean_rel.primary_address=1 LEFT JOIN email_addresses on email_addresses.id = email_addr_bean_rel.email_address_id ";
3396 $where_auto = '1=1';
3397 if($show_deleted == 0)
3399 $where_auto = "$this->table_name.deleted=0";
3400 }else if($show_deleted == 1)
3402 $where_auto = "$this->table_name.deleted=1";
3405 $ret_array['where'] = " where ($where) AND $where_auto";
3407 $ret_array['where'] = " where $where_auto";
3408 if(!empty($order_by))
3410 //make call to process the order by clause
3411 $ret_array['order_by'] = " ORDER BY ". $this->process_order_by($order_by);
3415 unset($ret_array['secondary_where']);
3416 unset($ret_array['secondary_from']);
3417 unset($ret_array['secondary_select']);
3425 return $ret_array['select'] . $ret_array['from'] . $ret_array['where']. $ret_array['order_by'];
3428 * Returns parent record data for objects that store relationship information
3430 * @param array $type_info
3432 * Interal function, do not override.
3434 function retrieve_parent_fields($type_info)
3437 global $beanList, $beanFiles;
3438 $templates = array();
3439 $parent_child_map = array();
3440 foreach($type_info as $children_info)
3442 foreach($children_info as $child_info)
3444 if($child_info['type'] == 'parent')
3446 if(empty($templates[$child_info['parent_type']]))
3448 //Test emails will have an invalid parent_type, don't try to load the non-existent parent bean
3449 if ($child_info['parent_type'] == 'test') {
3452 $class = $beanList[$child_info['parent_type']];
3453 // Added to avoid error below; just silently fail and write message to log
3454 if ( empty($beanFiles[$class]) ) {
3455 $GLOBALS['log']->error($this->object_name.'::retrieve_parent_fields() - cannot load class "'.$class.'", skip loading.');
3458 require_once($beanFiles[$class]);
3459 $templates[$child_info['parent_type']] = new $class();
3462 if(empty($queries[$child_info['parent_type']]))
3464 $queries[$child_info['parent_type']] = "SELECT id ";
3465 $field_def = $templates[$child_info['parent_type']]->field_defs['name'];
3466 if(isset($field_def['db_concat_fields']))
3468 $queries[$child_info['parent_type']] .= ' , ' . $this->db->concat($templates[$child_info['parent_type']]->table_name, $field_def['db_concat_fields']) . ' parent_name';
3472 $queries[$child_info['parent_type']] .= ' , name parent_name';
3474 if(isset($templates[$child_info['parent_type']]->field_defs['assigned_user_id']))
3476 $queries[$child_info['parent_type']] .= ", assigned_user_id parent_name_owner , '{$child_info['parent_type']}' parent_name_mod";;
3477 }else if(isset($templates[$child_info['parent_type']]->field_defs['created_by']))
3479 $queries[$child_info['parent_type']] .= ", created_by parent_name_owner, '{$child_info['parent_type']}' parent_name_mod";
3481 $queries[$child_info['parent_type']] .= " FROM " . $templates[$child_info['parent_type']]->table_name ." WHERE id IN ('{$child_info['parent_id']}'";
3485 if(empty($parent_child_map[$child_info['parent_id']]))
3486 $queries[$child_info['parent_type']] .= " ,'{$child_info['parent_id']}'";
3488 $parent_child_map[$child_info['parent_id']][] = $child_info['child_id'];
3493 foreach($queries as $query)
3495 $result = $this->db->query($query . ')');
3496 while($row = $this->db->fetchByAssoc($result))
3498 $results[$row['id']] = $row;
3502 $child_results = array();
3503 foreach($parent_child_map as $parent_key=>$parent_child)
3505 foreach($parent_child as $child)
3507 if(isset( $results[$parent_key]))
3509 $child_results[$child] = $results[$parent_key];
3513 return $child_results;
3517 * Processes the list query and return fetched row.
3519 * Internal function, do not override.
3520 * @param string $query select query to be processed.
3521 * @param int $row_offset starting position
3522 * @param int $limit Optioanl, default -1
3523 * @param int $max_per_page Optional, default -1
3524 * @param string $where Optional, additional filter criteria.
3525 * @return array Fetched data
3527 function process_list_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '')
3529 global $sugar_config;
3530 $db = DBManagerFactory::getInstance('listviews');
3532 * if the row_offset is set to 'end' go to the end of the list
3534 $toEnd = strval($row_offset) == 'end';
3535 $GLOBALS['log']->debug("process_list_query: ".$query);
3536 if($max_per_page == -1)
3538 $max_per_page = $sugar_config['list_max_entries_per_page'];
3540 // Check to see if we have a count query available.
3541 if(empty($sugar_config['disable_count_query']) || $toEnd)
3543 $count_query = $this->create_list_count_query($query);
3544 if(!empty($count_query) && (empty($limit) || $limit == -1))
3546 // We have a count query. Run it and get the results.
3547 $result = $db->query($count_query, true, "Error running count query for $this->object_name List: ");
3548 $assoc = $db->fetchByAssoc($result);
3549 if(!empty($assoc['c']))
3551 $rows_found = $assoc['c'];
3552 $limit = $sugar_config['list_max_entries_per_page'];
3556 $row_offset = (floor(($rows_found -1) / $limit)) * $limit;
3562 if((empty($limit) || $limit == -1))
3564 $limit = $max_per_page + 1;
3565 $max_per_page = $limit;
3570 if(empty($row_offset))
3574 if(!empty($limit) && $limit != -1 && $limit != -99)
3576 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $this->object_name list: ");
3580 $result = $db->query($query,true,"Error retrieving $this->object_name list: ");
3585 $previous_offset = $row_offset - $max_per_page;
3586 $next_offset = $row_offset + $max_per_page;
3588 $class = get_class($this);
3589 //FIXME: Bug? we should remove the magic number -99
3590 //use -99 to return all
3591 $index = $row_offset;
3592 while ($max_per_page == -99 || ($index < $row_offset + $max_per_page))
3594 $row = $db->fetchByAssoc($result);
3595 if (empty($row)) break;
3597 //instantiate a new class each time. This is because php5 passes
3598 //by reference by default so if we continually update $this, we will
3599 //at the end have a list of all the same objects
3600 $temp = new $class();
3602 foreach($this->field_defs as $field=>$value)
3604 if (isset($row[$field]))
3606 $temp->$field = $row[$field];
3607 $owner_field = $field . '_owner';
3608 if(isset($row[$owner_field]))
3610 $temp->$owner_field = $row[$owner_field];
3613 $GLOBALS['log']->debug("$temp->object_name({$row['id']}): ".$field." = ".$temp->$field);
3614 }else if (isset($row[$this->table_name .'.'.$field]))
3616 $temp->$field = $row[$this->table_name .'.'.$field];
3624 $temp->check_date_relationships_load();
3625 $temp->fill_in_additional_list_fields();
3626 if($temp->hasCustomFields()) $temp->custom_fields->fill_relationships();
3627 $temp->call_custom_logic("process_record");
3629 // fix defect #44206. implement the same logic as sugar_currency_format
3630 // Smarty modifier does.
3631 if (property_exists($temp, 'currency_id') && -99 == $temp->currency_id)
3633 // manually retrieve default currency object as long as it's
3634 // not stored in database and thus cannot be joined in query
3635 require_once 'modules/Currencies/Currency.php';
3636 $currency = new Currency();
3637 $currency->retrieve($temp->currency_id);
3639 // walk through all currency-related fields
3640 foreach ($temp->field_defs as $temp_field)
3642 if (isset($temp_field['type']) && 'relate' == $temp_field['type']
3643 && isset($temp_field['module']) && 'Currencies' == $temp_field['module']
3644 && isset($temp_field['id_name']) && 'currency_id' == $temp_field['id_name'])
3646 // populate related properties manually
3647 $temp_property = $temp_field['name'];
3648 $currency_property = $temp_field['rname'];
3649 $temp->$temp_property = $currency->$currency_property;
3658 if(!empty($sugar_config['disable_count_query']) && !empty($limit))
3661 $rows_found = $row_offset + count($list);
3663 unset($list[$limit - 1]);
3669 } else if(!isset($rows_found)){
3670 $rows_found = $row_offset + count($list);
3673 $response = Array();
3674 $response['list'] = $list;
3675 $response['row_count'] = $rows_found;
3676 $response['next_offset'] = $next_offset;
3677 $response['previous_offset'] = $previous_offset;
3678 $response['current_offset'] = $row_offset ;
3683 * Returns the number of rows that the given SQL query should produce
3685 * Internal function, do not override.
3686 * @param string $query valid select query
3687 * @param boolean $is_count_query Optional, Default false, set to true if passed query is a count query.
3688 * @return int count of rows found
3690 function _get_num_rows_in_query($query, $is_count_query=false)
3692 $num_rows_in_query = 0;
3693 if (!$is_count_query)
3695 $count_query = SugarBean::create_list_count_query($query);
3697 $count_query=$query;
3699 $result = $this->db->query($count_query, true, "Error running count query for $this->object_name List: ");
3701 while($row = $this->db->fetchByAssoc($result, true))
3703 $num_rows_in_query += current($row);
3706 return $num_rows_in_query;
3710 * Applies pagination window to union queries used by list view and subpanels,
3711 * executes the query and returns fetched data.
3713 * Internal function, do not override.
3714 * @param object $parent_bean
3715 * @param string $query query to be processed.
3716 * @param int $row_offset
3717 * @param int $limit optional, default -1
3718 * @param int $max_per_page Optional, default -1
3719 * @param string $where Custom where clause.
3720 * @param array $subpanel_def definition of sub-panel to be processed
3721 * @param string $query_row_count
3722 * @param array $seconday_queries
3723 * @return array Fetched data.
3725 function process_union_list_query($parent_bean, $query,
3726 $row_offset, $limit= -1, $max_per_page = -1, $where = '', $subpanel_def, $query_row_count='', $secondary_queries = array())
3729 $db = DBManagerFactory::getInstance('listviews');
3731 * if the row_offset is set to 'end' go to the end of the list
3733 $toEnd = strval($row_offset) == 'end';
3734 global $sugar_config;
3735 $use_count_query=false;
3736 $processing_collection=$subpanel_def->isCollection();
3738 $GLOBALS['log']->debug("process_union_list_query: ".$query);
3739 if($max_per_page == -1)
3741 $max_per_page = $sugar_config['list_max_entries_per_subpanel'];
3743 if(empty($query_row_count))
3745 $query_row_count = $query;
3747 $distinct_position=strpos($query_row_count,"DISTINCT");
3749 if ($distinct_position!= false)
3751 $use_count_query=true;
3753 $performSecondQuery = true;
3754 if(empty($sugar_config['disable_count_query']) || $toEnd)
3756 $rows_found = $this->_get_num_rows_in_query($query_row_count,$use_count_query);
3759 $performSecondQuery = false;
3761 if(!empty($rows_found) && (empty($limit) || $limit == -1))
3763 $limit = $sugar_config['list_max_entries_per_subpanel'];
3767 $row_offset = (floor(($rows_found -1) / $limit)) * $limit;
3773 if((empty($limit) || $limit == -1))
3775 $limit = $max_per_page + 1;
3776 $max_per_page = $limit;
3780 if(empty($row_offset))
3785 $previous_offset = $row_offset - $max_per_page;
3786 $next_offset = $row_offset + $max_per_page;
3788 if($performSecondQuery)
3790 if(!empty($limit) && $limit != -1 && $limit != -99)
3792 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $parent_bean->object_name list: ");
3796 $result = $db->query($query,true,"Error retrieving $this->object_name list: ");
3798 //use -99 to return all
3800 // get the current row
3801 $index = $row_offset;
3802 $row = $db->fetchByAssoc($result);
3804 $post_retrieve = array();
3805 $isFirstTime = true;
3808 $function_fields = array();
3809 if(($index < $row_offset + $max_per_page || $max_per_page == -99))
3811 if ($processing_collection)
3813 $current_bean =$subpanel_def->sub_subpanels[$row['panel_name']]->template_instance;
3816 $class = get_class($subpanel_def->sub_subpanels[$row['panel_name']]->template_instance);
3817 $current_bean = new $class();
3820 $current_bean=$subpanel_def->template_instance;
3823 $class = get_class($subpanel_def->template_instance);
3824 $current_bean = new $class();
3827 $isFirstTime = false;
3828 //set the panel name in the bean instance.
3829 if (isset($row['panel_name']))
3831 $current_bean->panel_name=$row['panel_name'];
3833 foreach($current_bean->field_defs as $field=>$value)
3836 if (isset($row[$field]))
3838 $current_bean->$field = $this->convertField($row[$field], $value);
3839 unset($row[$field]);
3841 else if (isset($row[$this->table_name .'.'.$field]))
3843 $current_bean->$field = $this->convertField($row[$this->table_name .'.'.$field], $value);
3844 unset($row[$this->table_name .'.'.$field]);
3848 $current_bean->$field = "";
3849 unset($row[$field]);
3851 if(isset($value['source']) && $value['source'] == 'function')
3853 $function_fields[]=$field;
3856 foreach($row as $key=>$value)
3858 $current_bean->$key = $value;
3860 foreach($function_fields as $function_field)
3862 $value = $current_bean->field_defs[$function_field];
3863 $can_execute = true;
3864 $execute_params = array();
3865 $execute_function = array();
3866 if(!empty($value['function_class']))
3868 $execute_function[] = $value['function_class'];
3869 $execute_function[] = $value['function_name'];
3873 $execute_function = $value['function_name'];
3875 foreach($value['function_params'] as $param )
3877 if (empty($value['function_params_source']) or $value['function_params_source']=='parent')
3879 if(empty($this->$param))
3881 $can_execute = false;
3882 } else if($param == '$this') {
3883 $execute_params[] = $this;
3887 $execute_params[] = $this->$param;
3889 } else if ($value['function_params_source']=='this')
3891 if(empty($current_bean->$param))
3893 $can_execute = false;
3894 } else if($param == '$this') {
3895 $execute_params[] = $current_bean;
3899 $execute_params[] = $current_bean->$param;
3904 $can_execute = false;
3910 if(!empty($value['function_require']))
3912 require_once($value['function_require']);
3914 $current_bean->$function_field = call_user_func_array($execute_function, $execute_params);
3917 if(!empty($current_bean->parent_type) && !empty($current_bean->parent_id))
3919 if(!isset($post_retrieve[$current_bean->parent_type]))
3921 $post_retrieve[$current_bean->parent_type] = array();
3923 $post_retrieve[$current_bean->parent_type][] = array('child_id'=>$current_bean->id, 'parent_id'=> $current_bean->parent_id, 'parent_type'=>$current_bean->parent_type, 'type'=>'parent');
3925 //$current_bean->fill_in_additional_list_fields();
3926 $list[$current_bean->id] = $current_bean;
3928 // go to the next row
3930 $row = $db->fetchByAssoc($result);
3932 //now handle retrieving many-to-many relationships
3935 foreach($secondary_queries as $query2)
3937 $result2 = $db->query($query2);
3939 $row2 = $db->fetchByAssoc($result2);
3942 $id_ref = $row2['ref_id'];
3944 if(isset($list[$id_ref]))
3946 foreach($row2 as $r2key=>$r2value)
3948 if($r2key != 'ref_id')
3950 $list[$id_ref]->$r2key = $r2value;
3954 $row2 = $db->fetchByAssoc($result2);
3960 if(isset($post_retrieve))
3962 $parent_fields = $this->retrieve_parent_fields($post_retrieve);
3966 $parent_fields = array();
3968 if(!empty($sugar_config['disable_count_query']) && !empty($limit))
3970 //C.L. Bug 43535 - Use the $index value to set the $rows_found value here
3971 $rows_found = isset($index) ? $index : $row_offset + count($list);
3973 if(count($list) >= $limit)
3987 $parent_fields = array();
3989 $response = array();
3990 $response['list'] = $list;
3991 $response['parent_data'] = $parent_fields;
3992 $response['row_count'] = $rows_found;
3993 $response['next_offset'] = $next_offset;
3994 $response['previous_offset'] = $previous_offset;
3995 $response['current_offset'] = $row_offset ;
3996 $response['query'] = $query;
4002 * Applies pagination window to select queries used by detail view,
4003 * executes the query and returns fetched data.
4005 * Internal function, do not override.
4006 * @param string $query query to be processed.
4007 * @param int $row_offset
4008 * @param int $limit optional, default -1
4009 * @param int $max_per_page Optional, default -1
4010 * @param string $where Custom where clause.
4011 * @param int $offset Optional, default 0
4012 * @return array Fetched data.
4015 function process_detail_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '', $offset = 0)
4017 global $sugar_config;
4018 $GLOBALS['log']->debug("process_detail_query: ".$query);
4019 if($max_per_page == -1)
4021 $max_per_page = $sugar_config['list_max_entries_per_page'];
4024 // Check to see if we have a count query available.
4025 $count_query = $this->create_list_count_query($query);
4027 if(!empty($count_query) && (empty($limit) || $limit == -1))
4029 // We have a count query. Run it and get the results.
4030 $result = $this->db->query($count_query, true, "Error running count query for $this->object_name List: ");
4031 $assoc = $this->db->fetchByAssoc($result);
4032 if(!empty($assoc['c']))
4034 $total_rows = $assoc['c'];
4038 if(empty($row_offset))
4043 $result = $this->db->limitQuery($query, $offset, 1, true,"Error retrieving $this->object_name list: ");
4045 $previous_offset = $row_offset - $max_per_page;
4046 $next_offset = $row_offset + $max_per_page;
4048 $row = $this->db->fetchByAssoc($result);
4049 $this->retrieve($row['id']);
4051 $response = Array();
4052 $response['bean'] = $this;
4053 if (empty($total_rows))
4055 $response['row_count'] = $total_rows;
4056 $response['next_offset'] = $next_offset;
4057 $response['previous_offset'] = $previous_offset;
4063 * Processes fetched list view data
4065 * Internal function, do not override.
4066 * @param string $query query to be processed.
4067 * @param boolean $check_date Optional, default false. if set to true date time values are processed.
4068 * @return array Fetched data.
4071 function process_full_list_query($query, $check_date=false)
4074 $GLOBALS['log']->debug("process_full_list_query: query is ".$query);
4075 $result = $this->db->query($query, false);
4076 $GLOBALS['log']->debug("process_full_list_query: result is ".print_r($result,true));
4077 $class = get_class($this);
4078 $isFirstTime = true;
4079 $bean = new $class();
4081 // We have some data.
4082 while (($row = $bean->db->fetchByAssoc($result)) != null)
4084 $row = $this->convertRow($row);
4087 $bean = new $class();
4089 $isFirstTime = false;
4091 foreach($bean->field_defs as $field=>$value)
4093 if (isset($row[$field]))
4095 $bean->$field = $row[$field];
4096 $GLOBALS['log']->debug("process_full_list: $bean->object_name({$row['id']}): ".$field." = ".$bean->$field);
4105 $bean->processed_dates_times = array();
4106 $bean->check_date_relationships_load();
4108 $bean->fill_in_additional_list_fields();
4109 $bean->call_custom_logic("process_record");
4110 $bean->fetched_row = $row;
4115 if (isset($list)) return $list;
4120 * Tracks the viewing of a detail record.
4121 * This leverages get_summary_text() which is object specific.
4123 * Internal function, do not override.
4124 * @param string $user_id - String value of the user that is viewing the record.
4125 * @param string $current_module - String value of the module being processed.
4126 * @param string $current_view - String value of the current view
4128 function track_view($user_id, $current_module, $current_view='')
4130 $trackerManager = TrackerManager::getInstance();
4131 if($monitor = $trackerManager->getMonitor('tracker')){
4132 $monitor->setValue('date_modified', $GLOBALS['timedate']->nowDb());
4133 $monitor->setValue('user_id', $user_id);
4134 $monitor->setValue('module_name', $current_module);
4135 $monitor->setValue('action', $current_view);
4136 $monitor->setValue('item_id', $this->id);
4137 $monitor->setValue('item_summary', $this->get_summary_text());
4138 $monitor->setValue('visible', $this->tracker_visibility);
4139 $trackerManager->saveMonitor($monitor);
4144 * Returns the summary text that should show up in the recent history list for this object.
4148 public function get_summary_text()
4150 return "Base Implementation. Should be overridden.";
4154 * This is designed to be overridden and add specific fields to each record.
4155 * This allows the generic query to fill in the major fields, and then targeted
4156 * queries to get related fields and add them to the record. The contact's
4157 * account for instance. This method is only used for populating extra fields
4160 function fill_in_additional_list_fields(){
4161 if(!empty($this->field_defs['parent_name']) && empty($this->parent_name)){
4162 $this->fill_in_additional_parent_fields();
4167 * This is designed to be overridden and add specific fields to each record.
4168 * This allows the generic query to fill in the major fields, and then targeted
4169 * queries to get related fields and add them to the record. The contact's
4170 * account for instance. This method is only used for populating extra fields
4171 * in the detail form
4173 function fill_in_additional_detail_fields()
4175 if(!empty($this->field_defs['assigned_user_name']) && !empty($this->assigned_user_id)){
4177 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
4180 if(!empty($this->field_defs['created_by']) && !empty($this->created_by))
4181 $this->created_by_name = get_assigned_user_name($this->created_by);
4182 if(!empty($this->field_defs['modified_user_id']) && !empty($this->modified_user_id))
4183 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
4185 if(!empty($this->field_defs['parent_name'])){
4186 $this->fill_in_additional_parent_fields();
4191 * This is desgined to be overridden or called from extending bean. This method
4192 * will fill in any parent_name fields.
4194 function fill_in_additional_parent_fields() {
4196 if(!empty($this->parent_id) && !empty($this->last_parent_id) && $this->last_parent_id == $this->parent_id){
4199 $this->parent_name = '';
4201 if(!empty($this->parent_type)) {
4202 $this->last_parent_id = $this->parent_id;
4203 $this->getRelatedFields($this->parent_type, $this->parent_id, array('name'=>'parent_name', 'document_name' => 'parent_document_name', 'first_name'=>'parent_first_name', 'last_name'=>'parent_last_name'));
4204 if(!empty($this->parent_first_name) || !empty($this->parent_last_name) ){
4205 $this->parent_name = $GLOBALS['locale']->getLocaleFormattedName($this->parent_first_name, $this->parent_last_name);
4206 } else if(!empty($this->parent_document_name)){
4207 $this->parent_name = $this->parent_document_name;
4213 * Fill in a link field
4216 function fill_in_link_field( $linkFieldName , $def)
4218 $idField = $linkFieldName;
4219 //If the id_name provided really was an ID, don't try to load it as a link. Use the normal link
4220 if (!empty($this->field_defs[$linkFieldName]['type']) && $this->field_defs[$linkFieldName]['type'] == "id" && !empty($def['link']))
4222 $linkFieldName = $def['link'];
4224 if ($this->load_relationship($linkFieldName))
4226 $list=$this->$linkFieldName->get();
4227 $this->$idField = '' ; // match up with null value in $this->populateFromRow()
4229 $this->$idField = $list[0];
4234 * Fill in fields where type = relate
4236 function fill_in_relationship_fields(){
4237 global $fill_in_rel_depth;
4238 if(empty($fill_in_rel_depth) || $fill_in_rel_depth < 0)
4239 $fill_in_rel_depth = 0;
4241 if($fill_in_rel_depth > 1)
4244 $fill_in_rel_depth++;
4246 foreach($this->field_defs as $field)
4248 if(0 == strcmp($field['type'],'relate') && !empty($field['module']))
4250 $name = $field['name'];
4251 if(empty($this->$name))
4253 // set the value of this relate field in this bean ($this->$field['name']) to the value of the 'name' field in the related module for the record identified by the value of $this->$field['id_name']
4254 $related_module = $field['module'];
4255 $id_name = $field['id_name'];
4257 if (empty($this->$id_name))
4259 $this->fill_in_link_field($id_name, $field);
4261 if(!empty($this->$id_name) && ( $this->object_name != $related_module || ( $this->object_name == $related_module && $this->$id_name != $this->id ))){
4262 if(isset($GLOBALS['beanList'][ $related_module])){
4263 $class = $GLOBALS['beanList'][$related_module];
4265 if(!empty($this->$id_name) && file_exists($GLOBALS['beanFiles'][$class]) && isset($this->$name)){
4266 require_once($GLOBALS['beanFiles'][$class]);
4267 $mod = new $class();
4269 // disable row level security in order to be able
4270 // to retrieve related bean properties (bug #44928)
4272 $mod->retrieve($this->$id_name);
4274 if (!empty($field['rname'])) {
4275 $this->$name = $mod->$field['rname'];
4276 } else if (isset($mod->name)) {
4277 $this->$name = $mod->name;
4282 if(!empty($this->$id_name) && isset($this->$name))
4284 if(!isset($field['additionalFields']))
4285 $field['additionalFields'] = array();
4286 if(!empty($field['rname']))
4288 $field['additionalFields'][$field['rname']]= $name;
4292 $field['additionalFields']['name']= $name;
4294 $this->getRelatedFields($related_module, $this->$id_name, $field['additionalFields']);
4299 $fill_in_rel_depth--;
4303 * This is a helper function that is used to quickly created indexes when creating tables.
4305 function create_index($query)
4307 $GLOBALS['log']->info("create_index: $query");
4309 $result = $this->db->query($query, true, "Error creating index:");
4313 * This function should be overridden in each module. It marks an item as deleted.
4315 * If it is not overridden, then marking this type of item is not allowed
4317 function mark_deleted($id)
4319 global $current_user;
4320 $date_modified = $GLOBALS['timedate']->nowDb();
4321 if(isset($_SESSION['show_deleted']))
4323 $this->mark_undeleted($id);
4327 // call the custom business logic
4328 $custom_logic_arguments['id'] = $id;
4329 $this->call_custom_logic("before_delete", $custom_logic_arguments);
4331 $this->mark_relationships_deleted($id);
4332 if ( isset($this->field_defs['modified_user_id']) ) {
4333 if (!empty($current_user)) {
4334 $this->modified_user_id = $current_user->id;
4336 $this->modified_user_id = 1;
4338 $query = "UPDATE $this->table_name set deleted=1 , date_modified = '$date_modified', modified_user_id = '$this->modified_user_id' where id='$id'";
4340 $query = "UPDATE $this->table_name set deleted=1 , date_modified = '$date_modified' where id='$id'";
4342 $this->db->query($query, true,"Error marking record deleted: ");
4344 SugarRelationship::resaveRelatedBeans();
4346 // Take the item off the recently viewed lists
4347 $tracker = new Tracker();
4348 $tracker->makeInvisibleForAll($id);
4351 // call the custom business logic
4352 $this->call_custom_logic("after_delete", $custom_logic_arguments);
4357 * Restores data deleted by call to mark_deleted() function.
4359 * Internal function, do not override.
4361 function mark_undeleted($id)
4363 // call the custom business logic
4364 $custom_logic_arguments['id'] = $id;
4365 $this->call_custom_logic("before_restore", $custom_logic_arguments);
4367 $date_modified = $GLOBALS['timedate']->nowDb();
4368 $query = "UPDATE $this->table_name set deleted=0 , date_modified = '$date_modified' where id='$id'";
4369 $this->db->query($query, true,"Error marking record undeleted: ");
4371 // call the custom business logic
4372 $this->call_custom_logic("after_restore", $custom_logic_arguments);
4376 * This function deletes relationships to this object. It should be overridden
4377 * to handle the relationships of the specific object.
4378 * This function is called when the item itself is being deleted.
4380 * @param int $id id of the relationship to delete
4382 function mark_relationships_deleted($id)
4384 $this->delete_linked($id);
4388 * This function is used to execute the query and create an array template objects
4389 * from the resulting ids from the query.
4390 * It is currently used for building sub-panel arrays.
4392 * @param string $query - the query that should be executed to build the list
4393 * @param object $template - The object that should be used to copy the records.
4394 * @param int $row_offset Optional, default 0
4395 * @param int $limit Optional, default -1
4398 function build_related_list($query, &$template, $row_offset = 0, $limit = -1)
4400 $GLOBALS['log']->debug("Finding linked records $this->object_name: ".$query);
4401 $db = DBManagerFactory::getInstance('listviews');
4403 if(!empty($row_offset) && $row_offset != 0 && !empty($limit) && $limit != -1)
4405 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $template->object_name list: ");
4409 $result = $db->query($query, true);
4413 $isFirstTime = true;
4414 $class = get_class($template);
4415 while($row = $this->db->fetchByAssoc($result))
4419 $template = new $class();
4421 $isFirstTime = false;
4422 $record = $template->retrieve($row['id']);
4426 // this copies the object into the array
4427 $list[] = $template;
4434 * This function is used to execute the query and create an array template objects
4435 * from the resulting ids from the query.
4436 * It is currently used for building sub-panel arrays. It supports an additional
4437 * where clause that is executed as a filter on the results
4439 * @param string $query - the query that should be executed to build the list
4440 * @param object $template - The object that should be used to copy the records.
4442 function build_related_list_where($query, &$template, $where='', $in='', $order_by, $limit='', $row_offset = 0)
4444 $db = DBManagerFactory::getInstance('listviews');
4445 // No need to do an additional query
4446 $GLOBALS['log']->debug("Finding linked records $this->object_name: ".$query);
4447 if(empty($in) && !empty($query))
4449 $idList = $this->build_related_in($query);
4450 $in = $idList['in'];
4452 // MFH - Added Support For Custom Fields in Searches
4454 if(isset($this->custom_fields)) {
4455 $custom_join = $this->custom_fields->getJOIN();
4458 $query = "SELECT id ";
4460 if (!empty($custom_join)) {
4461 $query .= $custom_join['select'];
4463 $query .= " FROM $this->table_name ";
4465 if (!empty($custom_join) && !empty($custom_join['join'])) {
4466 $query .= " " . $custom_join['join'];
4469 $query .= " WHERE deleted=0 AND id IN $in";
4472 $query .= " AND $where";
4476 if(!empty($order_by))
4478 $query .= "ORDER BY $order_by";
4482 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $this->object_name list: ");
4486 $result = $db->query($query, true);
4490 $isFirstTime = true;
4491 $class = get_class($template);
4493 $disable_security_flag = ($template->disable_row_level_security) ? true : false;
4494 while($row = $db->fetchByAssoc($result))
4498 $template = new $class();
4499 $template->disable_row_level_security = $disable_security_flag;
4501 $isFirstTime = false;
4502 $record = $template->retrieve($row['id']);
4505 // this copies the object into the array
4506 $list[] = $template;
4514 * Constructs an comma separated list of ids from passed query results.
4516 * @param string @query query to be executed.
4519 function build_related_in($query)
4522 $result = $this->db->query($query, true);
4524 while($row = $this->db->fetchByAssoc($result))
4526 $idList[] = $row['id'];
4529 $ids = "('" . $row['id'] . "'";
4533 $ids .= ",'" . $row['id'] . "'";
4543 return array('list'=>$idList, 'in'=>$ids);
4547 * Optionally copies values from fetched row into the bean.
4549 * Internal function, do not override.
4551 * @param string $query - the query that should be executed to build the list
4552 * @param object $template - The object that should be used to copy the records
4553 * @param array $field_list List of fields.
4556 function build_related_list2($query, &$template, &$field_list)
4558 $GLOBALS['log']->debug("Finding linked values $this->object_name: ".$query);
4560 $result = $this->db->query($query, true);
4563 $isFirstTime = true;
4564 $class = get_class($template);
4565 while($row = $this->db->fetchByAssoc($result))
4567 // Create a blank copy
4571 $copy = new $class();
4573 $isFirstTime = false;
4574 foreach($field_list as $field)
4576 // Copy the relevant fields
4577 $copy->$field = $row[$field];
4581 // this copies the object into the array
4589 * Let implementing classes to fill in row specific columns of a list view form
4592 function list_view_parse_additional_sections(&$list_form)
4596 * Assigns all of the values into the template for the list view
4598 function get_list_view_array()
4600 static $cache = array();
4601 // cn: bug 12270 - sensitive fields being passed arbitrarily in listViews
4602 $sensitiveFields = array('user_hash' => '');
4604 $return_array = Array();
4605 global $app_list_strings, $mod_strings;
4606 foreach($this->field_defs as $field=>$value){
4608 if(isset($this->$field)){
4610 // cn: bug 12270 - sensitive fields being passed arbitrarily in listViews
4611 if(isset($sensitiveFields[$field]))
4613 if(!isset($cache[$field]))
4614 $cache[$field] = strtoupper($field);
4616 //Fields hidden by Dependent Fields
4617 if (isset($value['hidden']) && $value['hidden'] === true) {
4618 $return_array[$cache[$field]] = "";
4621 //cn: if $field is a _dom, detect and return VALUE not KEY
4622 //cl: empty function check for meta-data enum types that have values loaded from a function
4623 else if (((!empty($value['type']) && ($value['type'] == 'enum' || $value['type'] == 'radioenum') )) && empty($value['function'])){
4624 if(!empty($value['options']) && !empty($app_list_strings[$value['options']][$this->$field])){
4625 $return_array[$cache[$field]] = $app_list_strings[$value['options']][$this->$field];
4627 //nsingh- bug 21672. some modules such as manufacturers, Releases do not have a listing for select fields in the $app_list_strings. Must also check $mod_strings to localize.
4628 elseif(!empty($value['options']) && !empty($mod_strings[$value['options']][$this->$field]))
4630 $return_array[$cache[$field]] = $mod_strings[$value['options']][$this->$field];
4633 $return_array[$cache[$field]] = $this->$field;
4636 // tjy: no need to do this str_replace as the changes in 29994 for ListViewGeneric.tpl for translation handle this now
4637 // }elseif(!empty($value['type']) && $value['type'] == 'multienum'&& empty($value['function'])){
4638 // $return_array[strtoupper($field)] = str_replace('^,^', ', ', $this->$field );
4639 }elseif(!empty($value['custom_module']) && $value['type'] != 'currency'){
4640 // $this->format_field($value);
4641 $return_array[$cache[$field]] = $this->$field;
4643 $return_array[$cache[$field]] = $this->$field;
4645 // handle "Assigned User Name"
4646 if($field == 'assigned_user_name'){
4647 $return_array['ASSIGNED_USER_NAME'] = get_assigned_user_name($this->assigned_user_id);
4651 return $return_array;
4654 * Override this function to set values in the array used to render list view data.
4657 function get_list_view_data()
4659 return $this->get_list_view_array();
4663 * Construct where clause from a list of name-value pairs.
4664 * @param array $fields_array Name/value pairs for column checks
4665 * @param boolean $deleted Optional, default true, if set to false deleted filter will not be added.
4666 * @return string The WHERE clause
4668 function get_where($fields_array, $deleted=true)
4671 foreach ($fields_array as $name=>$value)
4673 if (!empty($where_clause)) {
4674 $where_clause .= " AND ";
4676 $name = $this->db->getValidDBName($name);
4678 $where_clause .= "$name = ".$this->db->quoted($value,false);
4680 if(!empty($where_clause)) {
4682 return "WHERE $where_clause AND deleted=0";
4684 return "WHERE $where_clause";
4693 * Constructs a select query and fetch 1 row using this query, and then process the row
4695 * Internal function, do not override.
4696 * @param array @fields_array array of name value pairs used to construct query.
4697 * @param boolean $encode Optional, default true, encode fetched data.
4698 * @param boolean $deleted Optional, default true, if set to false deleted filter will not be added.
4699 * @return object Instance of this bean with fetched data.
4701 function retrieve_by_string_fields($fields_array, $encode=true, $deleted=true)
4703 $where_clause = $this->get_where($fields_array, $deleted);
4704 if(isset($this->custom_fields))
4705 $custom_join = $this->custom_fields->getJOIN();
4706 else $custom_join = false;
4709 $query = "SELECT $this->table_name.*". $custom_join['select']. " FROM $this->table_name " . $custom_join['join'];
4713 $query = "SELECT $this->table_name.* FROM $this->table_name ";
4715 $query .= " $where_clause";
4716 $GLOBALS['log']->debug("Retrieve $this->object_name: ".$query);
4717 //requireSingleResult has been deprecated.
4718 //$result = $this->db->requireSingleResult($query, true, "Retrieving record $where_clause:");
4719 $result = $this->db->limitQuery($query,0,1,true, "Retrieving record $where_clause:");
4726 $row = $this->db->fetchByAssoc($result, $encode);
4731 // Removed getRowCount-if-clause earlier and insert duplicates_found here as it seems that we have found something
4732 // if we didn't return null in the previous clause.
4733 $this->duplicates_found = true;
4734 $row = $this->convertRow($row);
4735 $this->fetched_row = $row;
4736 $this->fromArray($row);
4737 $this->is_updated_dependent_fields = false;
4738 $this->fill_in_additional_detail_fields();
4743 * This method is called during an import before inserting a bean
4744 * Define an associative array called $special_fields
4745 * the keys are user defined, and don't directly map to the bean's fields
4746 * the value is the method name within that bean that will do extra
4747 * processing for that field. example: 'full_name'=>'get_names_from_full_name'
4750 function process_special_fields()
4752 foreach ($this->special_functions as $func_name)
4754 if ( method_exists($this,$func_name) )
4756 $this->$func_name();
4762 * Override this function to build a where clause based on the search criteria set into bean .
4765 function build_generic_where_clause($value)
4769 function getRelatedFields($module, $id, $fields, $return_array = false){
4770 if(empty($GLOBALS['beanList'][$module]))return '';
4771 $object = BeanFactory::getObjectName($module);
4773 VardefManager::loadVardef($module, $object);
4774 if(empty($GLOBALS['dictionary'][$object]['table']))return '';
4775 $table = $GLOBALS['dictionary'][$object]['table'];
4776 $query = 'SELECT id';
4777 foreach($fields as $field=>$alias){
4778 if(!empty($GLOBALS['dictionary'][$object]['fields'][$field]['db_concat_fields'])){
4779 $query .= ' ,' .$this->db->concat($table, $GLOBALS['dictionary'][$object]['fields'][$field]['db_concat_fields']) . ' as ' . $alias ;
4780 }else if(!empty($GLOBALS['dictionary'][$object]['fields'][$field]) &&
4781 (empty($GLOBALS['dictionary'][$object]['fields'][$field]['source']) ||
4782 $GLOBALS['dictionary'][$object]['fields'][$field]['source'] != "non-db"))
4784 $query .= ' ,' .$table . '.' . $field . ' as ' . $alias;
4786 if(!$return_array)$this->$alias = '';
4788 if($query == 'SELECT id' || empty($id)){
4793 if(isset($GLOBALS['dictionary'][$object]['fields']['assigned_user_id']))
4795 $query .= " , ". $table . ".assigned_user_id owner";
4798 else if(isset($GLOBALS['dictionary'][$object]['fields']['created_by']))
4800 $query .= " , ". $table . ".created_by owner";
4803 $query .= ' FROM ' . $table . ' WHERE deleted=0 AND id=';
4804 $result = $GLOBALS['db']->query($query . "'$id'" );
4805 $row = $GLOBALS['db']->fetchByAssoc($result);
4809 $owner = (empty($row['owner']))?'':$row['owner'];
4810 foreach($fields as $alias){
4811 $this->$alias = (!empty($row[$alias]))? $row[$alias]: '';
4812 $alias = $alias .'_owner';
4813 $this->$alias = $owner;
4814 $a_mod = $alias .'_mod';
4815 $this->$a_mod = $module;
4822 function &parse_additional_headers(&$list_form, $xTemplateSection)
4827 function assign_display_fields($currentModule)
4830 foreach($this->column_fields as $field)
4832 if(isset($this->field_name_map[$field]) && empty($this->$field))
4834 if($this->field_name_map[$field]['type'] != 'date' && $this->field_name_map[$field]['type'] != 'enum')
4835 $this->$field = $field;
4836 if($this->field_name_map[$field]['type'] == 'date')
4838 $this->$field = $timedate->to_display_date('1980-07-09');
4840 if($this->field_name_map[$field]['type'] == 'enum')
4842 $dom = $this->field_name_map[$field]['options'];
4843 global $current_language, $app_list_strings;
4844 $mod_strings = return_module_language($current_language, $currentModule);
4846 if(isset($mod_strings[$dom]))
4848 $options = $mod_strings[$dom];
4849 foreach($options as $key=>$value)
4851 if(!empty($key) && empty($this->$field ))
4853 $this->$field = $key;
4857 if(isset($app_list_strings[$dom]))
4859 $options = $app_list_strings[$dom];
4860 foreach($options as $key=>$value)
4862 if(!empty($key) && empty($this->$field ))
4864 $this->$field = $key;
4876 * RELATIONSHIP HANDLING
4879 function set_relationship($table, $relate_values, $check_duplicates = true,$do_update=false,$data_values=null)
4883 // make sure there is a date modified
4884 $date_modified = $this->db->convert("'".$GLOBALS['timedate']->nowDb()."'", 'datetime');
4887 if($check_duplicates)
4889 $query = "SELECT * FROM $table ";
4890 $where = "WHERE deleted = '0' ";
4891 foreach($relate_values as $name=>$value)
4893 $where .= " AND $name = '$value' ";
4896 $result = $this->db->query($query, false, "Looking For Duplicate Relationship:" . $query);
4897 $row=$this->db->fetchByAssoc($result);
4900 if(!$check_duplicates || empty($row) )
4902 unset($relate_values['id']);
4903 if ( isset($data_values))
4905 $relate_values = array_merge($relate_values,$data_values);
4907 $query = "INSERT INTO $table (id, ". implode(',', array_keys($relate_values)) . ", date_modified) VALUES ('" . create_guid() . "', " . "'" . implode("', '", $relate_values) . "', ".$date_modified.")" ;
4909 $this->db->query($query, false, "Creating Relationship:" . $query);
4911 else if ($do_update)
4914 foreach($data_values as $key=>$value)
4916 array_push($conds,$key."='".$this->db->quote($value)."'");
4918 $query = "UPDATE $table SET ". implode(',', $conds).",date_modified=".$date_modified." ".$where;
4919 $this->db->query($query, false, "Updating Relationship:" . $query);
4923 function retrieve_relationships($table, $values, $select_id)
4925 $query = "SELECT $select_id FROM $table WHERE deleted = 0 ";
4926 foreach($values as $name=>$value)
4928 $query .= " AND $name = '$value' ";
4930 $query .= " ORDER BY $select_id ";
4931 $result = $this->db->query($query, false, "Retrieving Relationship:" . $query);
4933 while($row = $this->db->fetchByAssoc($result))
4940 // TODO: this function needs adjustment
4941 function loadLayoutDefs()
4943 global $layout_defs;
4944 if(empty( $this->layout_def) && file_exists('modules/'. $this->module_dir . '/layout_defs.php'))
4946 include_once('modules/'. $this->module_dir . '/layout_defs.php');
4947 if(file_exists('custom/modules/'. $this->module_dir . '/Ext/Layoutdefs/layoutdefs.ext.php'))
4949 include_once('custom/modules/'. $this->module_dir . '/Ext/Layoutdefs/layoutdefs.ext.php');
4951 if ( empty( $layout_defs[get_class($this)]))
4953 echo "\$layout_defs[" . get_class($this) . "]; does not exist";
4956 $this->layout_def = $layout_defs[get_class($this)];
4961 * Trigger custom logic for this module that is defined for the provided hook
4962 * The custom logic file is located under custom/modules/[CURRENT_MODULE]/logic_hooks.php.
4963 * That file should define the $hook_version that should be used.
4964 * It should also define the $hook_array. The $hook_array will be a two dimensional array
4965 * the first dimension is the name of the event, the second dimension is the information needed
4966 * to fire the hook. Each entry in the top level array should be defined on a single line to make it
4967 * easier to automatically replace this file. There should be no contents of this file that are not replacable.
4969 * $hook_array['before_save'][] = Array(1, testtype, 'custom/modules/Leads/test12.php', 'TestClass', 'lead_before_save_1');
4970 * This sample line creates a before_save hook. The hooks are procesed in the order in which they
4971 * are added to the array. The second dimension is an array of:
4972 * processing index (for sorting before exporting the array)
4975 * php file to include
4976 * php class the method is in
4977 * php method to call
4979 * The method signature for version 1 hooks is:
4980 * function NAME(&$bean, $event, $arguments)
4981 * $bean - $this bean passed in by reference.
4982 * $event - The string for the current event (i.e. before_save)
4983 * $arguments - An array of arguments that are specific to the event.
4985 function call_custom_logic($event, $arguments = null)
4987 if(!isset($this->processed) || $this->processed == false){
4988 //add some logic to ensure we do not get into an infinite loop
4989 if(!empty($this->logicHookDepth[$event])) {
4990 if($this->logicHookDepth[$event] > $this->max_logic_depth)
4993 $this->logicHookDepth[$event] = 0;
4995 //we have to put the increment operator here
4996 //otherwise we may never increase the depth for that event in the case
4997 //where one event will trigger another as in the case of before_save and after_save
4998 //Also keeping the depth per event allow any number of hooks to be called on the bean
4999 //and we only will return if one event gets caught in a loop. We do not increment globally
5000 //for each event called.
5001 $this->logicHookDepth[$event]++;
5003 //method defined in 'include/utils/LogicHook.php'
5005 $logicHook = new LogicHook();
5006 $logicHook->setBean($this);
5007 $logicHook->call_custom_logic($this->module_dir, $event, $arguments);
5008 $this->logicHookDepth[$event]--;
5013 /* When creating a custom field of type Dropdown, it creates an enum row in the DB.
5014 A typical get_list_view_array() result will have the *KEY* value from that drop-down.
5015 Since custom _dom objects are flat-files included in the $app_list_strings variable,
5016 We need to generate a key-key pair to get the true value like so:
5017 ([module]_cstm->fields_meta_data->$app_list_strings->*VALUE*)*/
5018 function getRealKeyFromCustomFieldAssignedKey($name)
5020 if ($this->custom_fields->avail_fields[$name]['ext1'])
5024 elseif ($this->custom_fields->avail_fields[$name]['ext2'])
5028 elseif ($this->custom_fields->avail_fields[$name]['ext3'])
5034 $GLOBALS['log']->fatal("SUGARBEAN: cannot find Real Key for custom field of type dropdown - cannot return Value.");
5039 return $this->custom_fields->avail_fields[$name][$realKey];
5043 function bean_implements($interface)
5048 * Check whether the user has access to a particular view for the current bean/module
5049 * @param $view string required, the view to determine access for i.e. DetailView, ListView...
5050 * @param $is_owner bool optional, this is part of the ACL check if the current user is an owner they will receive different access
5052 function ACLAccess($view,$is_owner='not_set')
5054 global $current_user;
5055 if($current_user->isAdminForModule($this->getACLCategory())) {
5059 if($is_owner == 'not_set')
5062 $is_owner = $this->isOwner($current_user->id);
5065 // If we don't implement ACLs, return true.
5066 if(!$this->bean_implements('ACL'))
5068 $view = strtolower($view);
5074 return ACLController::checkAccess($this->module_dir,'list', true);
5077 if( !$is_owner && $not_set && !empty($this->id)){
5078 $class = get_class($this);
5079 $temp = new $class();
5080 if(!empty($this->fetched_row) && !empty($this->fetched_row['id']) && !empty($this->fetched_row['assigned_user_id']) && !empty($this->fetched_row['created_by'])){
5081 $temp->populateFromRow($this->fetched_row);
5083 $temp->retrieve($this->id);
5085 $is_owner = $temp->isOwner($current_user->id);
5087 case 'popupeditview':
5089 return ACLController::checkAccess($this->module_dir,'edit', $is_owner, $this->acltype);
5093 return ACLController::checkAccess($this->module_dir,'view', $is_owner, $this->acltype);
5095 return ACLController::checkAccess($this->module_dir,'delete', $is_owner, $this->acltype);
5097 return ACLController::checkAccess($this->module_dir,'export', $is_owner, $this->acltype);
5099 return ACLController::checkAccess($this->module_dir,'import', true, $this->acltype);
5101 //if it is not one of the above views then it should be implemented on the page level
5110 function getOwnerField($returnFieldName = false)
5112 if (isset($this->field_defs['assigned_user_id']))
5114 return $returnFieldName? 'assigned_user_id': $this->assigned_user_id;
5117 if (isset($this->field_defs['created_by']))
5119 return $returnFieldName? 'created_by': $this->created_by;
5126 * Returns true of false if the user_id passed is the owner
5128 * @param GUID $user_id
5131 function isOwner($user_id)
5133 //if we don't have an id we must be the owner as we are creating it
5134 if(!isset($this->id))
5138 //if there is an assigned_user that is the owner
5139 if(isset($this->assigned_user_id))
5141 if($this->assigned_user_id == $user_id) return true;
5146 //other wise if there is a created_by that is the owner
5147 if(isset($this->created_by) && $this->created_by == $user_id)
5155 * Gets there where statement for checking if a user is an owner
5157 * @param GUID $user_id
5160 function getOwnerWhere($user_id)
5162 if(isset($this->field_defs['assigned_user_id']))
5164 return " $this->table_name.assigned_user_id ='$user_id' ";
5166 if(isset($this->field_defs['created_by']))
5168 return " $this->table_name.created_by ='$user_id' ";
5175 * Used in order to manage ListView links and if they should
5176 * links or not based on the ACL permissions of the user
5178 * @return ARRAY of STRINGS
5180 function listviewACLHelper()
5182 $array_assign = array();
5183 if($this->ACLAccess('DetailView'))
5185 $array_assign['MAIN'] = 'a';
5189 $array_assign['MAIN'] = 'span';
5191 return $array_assign;
5195 * returns this bean as an array
5197 * @return array of fields with id, name, access and category
5199 function toArray($dbOnly = false, $stringOnly = false, $upperKeys=false)
5201 static $cache = array();
5204 foreach($this->field_defs as $field=>$data)
5206 if( !$dbOnly || !isset($data['source']) || $data['source'] == 'db')
5207 if(!$stringOnly || is_string($this->$field))
5210 if(!isset($cache[$field])){
5211 $cache[$field] = strtoupper($field);
5213 $arr[$cache[$field]] = $this->$field;
5217 if(isset($this->$field)){
5218 $arr[$field] = $this->$field;
5228 * Converts an array into an acl mapping name value pairs into files
5232 function fromArray($arr)
5234 foreach($arr as $name=>$value)
5236 $this->$name = $value;
5241 * Convert row data from DB format to internal format
5242 * Mostly useful for dates/times
5244 * @return array $row
5246 public function convertRow($row)
5248 foreach($this->field_defs as $name => $fieldDef)
5250 // skip empty fields and non-db fields
5251 if (isset($name) && !empty($row[$name])) {
5252 $row[$name] = $this->convertField($row[$name], $fieldDef);
5259 * Converts the field value based on the provided fieldDef
5260 * @param $fieldvalue
5264 public function convertField($fieldvalue, $fieldDef)
5266 if (!empty($fieldvalue)) {
5267 if (!(isset($fieldDef['source']) &&
5268 !in_array($fieldDef['source'], array('db', 'custom_fields', 'relate'))
5269 && !isset($fieldDef['dbType']))
5271 // fromConvert other fields
5272 $fieldvalue = $this->db->fromConvert($fieldvalue, $this->db->getFieldType($fieldDef));
5279 * Loads a row of data into instance of a bean. The data is passed as an array to this function
5281 * @param array $arr row of data fetched from the database.
5284 * Internal function do not override.
5286 function loadFromRow($arr)
5288 $this->populateFromRow($arr);
5289 $this->processed_dates_times = array();
5290 $this->check_date_relationships_load();
5292 $this->fill_in_additional_list_fields();
5294 if($this->hasCustomFields())$this->custom_fields->fill_relationships();
5295 $this->call_custom_logic("process_record");
5298 function hasCustomFields()
5300 return !empty($GLOBALS['dictionary'][$this->object_name]['custom_fields']);
5304 * Ensure that fields within order by clauses are properly qualified with
5305 * their tablename. This qualification is a requirement for sql server support.
5307 * @param string $order_by original order by from the query
5308 * @param string $qualify prefix for columns in the order by list.
5311 * Internal function do not override.
5313 function create_qualified_order_by( $order_by, $qualify)
5314 { // if the column is empty, but the sort order is defined, the value will throw an error, so do not proceed if no order by is given
5315 if (empty($order_by))
5319 $order_by_clause = " ORDER BY ";
5320 $tmp = explode(",", $order_by);
5322 foreach ( $tmp as $stmp)
5324 $stmp = (substr_count($stmp, ".") > 0?trim($stmp):"$qualify." . trim($stmp));
5325 $order_by_clause .= $comma . $stmp;
5328 return $order_by_clause;
5332 * Combined the contents of street field 2 thru 4 into the main field
5334 * @param string $street_field
5337 function add_address_streets(
5341 $street_field_2 = $street_field.'_2';
5342 $street_field_3 = $street_field.'_3';
5343 $street_field_4 = $street_field.'_4';
5344 if ( isset($this->$street_field_2)) {
5345 $this->$street_field .= "\n". $this->$street_field_2;
5346 unset($this->$street_field_2);
5348 if ( isset($this->$street_field_3)) {
5349 $this->$street_field .= "\n". $this->$street_field_3;
5350 unset($this->$street_field_3);
5352 if ( isset($this->$street_field_4)) {
5353 $this->$street_field .= "\n". $this->$street_field_4;
5354 unset($this->$street_field_4);
5356 if ( isset($this->$street_field)) {
5357 $this->$street_field = trim($this->$street_field, "\n");
5361 protected function getEncryptKey()
5363 if(empty(self::$field_key)) {
5364 self::$field_key = blowfishGetKey('encrypt_field');
5366 return self::$field_key;
5370 * Encrpyt and base64 encode an 'encrypt' field type in the bean using Blowfish. The default system key is stored in cache/Blowfish/{keytype}
5371 * @param STRING value -plain text value of the bean field.
5374 function encrpyt_before_save($value)
5376 require_once("include/utils/encryption_utils.php");
5377 return blowfishEncode($this->getEncryptKey(), $value);
5381 * Decode and decrypt a base 64 encoded string with field type 'encrypt' in this bean using Blowfish.
5382 * @param STRING value - an encrypted and base 64 encoded string.
5385 function decrypt_after_retrieve($value)
5387 if(empty($value)) return $value; // no need to decrypt empty
5388 require_once("include/utils/encryption_utils.php");
5389 return blowfishDecode($this->getEncryptKey(), $value);
5393 * Moved from save() method, functionality is the same, but this is intended to handle
5394 * Optimistic locking functionality.
5396 private function _checkOptimisticLocking($action, $isUpdate){
5397 if($this->optimistic_lock && !isset($_SESSION['o_lock_fs'])){
5398 if(isset($_SESSION['o_lock_id']) && $_SESSION['o_lock_id'] == $this->id && $_SESSION['o_lock_on'] == $this->object_name)
5400 if($action == 'Save' && $isUpdate && isset($this->modified_user_id) && $this->has_been_modified_since($_SESSION['o_lock_dm'], $this->modified_user_id))
5402 $_SESSION['o_lock_class'] = get_class($this);
5403 $_SESSION['o_lock_module'] = $this->module_dir;
5404 $_SESSION['o_lock_object'] = $this->toArray();
5405 $saveform = "<form name='save' id='save' method='POST'>";
5406 foreach($_POST as $key=>$arg)
5408 $saveform .= "<input type='hidden' name='". addslashes($key) ."' value='". addslashes($arg) ."'>";
5410 $saveform .= "</form><script>document.getElementById('save').submit();</script>";
5411 $_SESSION['o_lock_save'] = $saveform;
5412 header('Location: index.php?module=OptimisticLock&action=LockResolve');
5417 unset ($_SESSION['o_lock_object']);
5418 unset ($_SESSION['o_lock_id']);
5419 unset ($_SESSION['o_lock_dm']);
5425 if(isset($_SESSION['o_lock_object'])) { unset ($_SESSION['o_lock_object']); }
5426 if(isset($_SESSION['o_lock_id'])) { unset ($_SESSION['o_lock_id']); }
5427 if(isset($_SESSION['o_lock_dm'])) { unset ($_SESSION['o_lock_dm']); }
5428 if(isset($_SESSION['o_lock_fs'])) { unset ($_SESSION['o_lock_fs']); }
5429 if(isset($_SESSION['o_lock_save'])) { unset ($_SESSION['o_lock_save']); }
5434 * Send assignment notifications and invites for meetings and calls
5436 private function _sendNotifications($check_notify){
5437 if($check_notify || (isset($this->notify_inworkflow) && $this->notify_inworkflow == true) // cn: bug 5795 - no invites sent to Contacts, and also bug 25995, in workflow, it will set the notify_on_save=true.
5438 && !$this->isOwner($this->created_by) ) // cn: bug 42727 no need to send email to owner (within workflow)
5440 $admin = new Administration();
5441 $admin->retrieveSettings();
5442 $sendNotifications = false;
5444 if ($admin->settings['notify_on'])
5446 $GLOBALS['log']->info("Notifications: user assignment has changed, checking if user receives notifications");
5447 $sendNotifications = true;
5449 elseif(isset($_REQUEST['send_invites']) && $_REQUEST['send_invites'] == 1)
5451 // cn: bug 5795 Send Invites failing for Contacts
5452 $sendNotifications = true;
5456 $GLOBALS['log']->info("Notifications: not sending e-mail, notify_on is set to OFF");
5460 if($sendNotifications == true)
5462 $notify_list = $this->get_notification_recipients();
5463 foreach ($notify_list as $notify_user)
5465 $this->send_assignment_notifications($notify_user, $admin);
5473 * Called from ImportFieldSanitize::relate(), when creating a new bean in a related module. Will
5474 * copies fields over from the current bean into the related. Designed to be overriden in child classes.
5476 * @param SugarBean $newbean newly created related bean
5478 public function populateRelatedBean(
5485 * Called during the import process before a bean save, to handle any needed pre-save logic when
5486 * importing a record
5488 public function beforeImportSave()
5493 * Called during the import process after a bean save, to handle any needed post-save logic when
5494 * importing a record
5496 public function afterImportSave()
5501 * This function is designed to cache references to field arrays that were previously stored in the
5502 * bean files and have since been moved to separate files. Was previously in include/CacheHandler.php
5505 * @param $module_dir string the module directory
5506 * @param $module string the name of the module
5507 * @param $key string the type of field array we are referencing, i.e. list_fields, column_fields, required_fields
5509 private function _loadCachedArray(
5515 static $moduleDefs = array();
5517 $fileName = 'field_arrays.php';
5519 $cache_key = "load_cached_array.$module_dir.$module.$key";
5520 $result = sugar_cache_retrieve($cache_key);
5523 // Use SugarCache::EXTERNAL_CACHE_NULL_VALUE to store null values in the cache.
5524 if($result == SugarCache::EXTERNAL_CACHE_NULL_VALUE)
5532 if(file_exists('modules/'.$module_dir.'/'.$fileName))
5534 // If the data was not loaded, try loading again....
5535 if(!isset($moduleDefs[$module]))
5537 include('modules/'.$module_dir.'/'.$fileName);
5538 $moduleDefs[$module] = $fields_array;
5540 // Now that we have tried loading, make sure it was loaded
5541 if(empty($moduleDefs[$module]) || empty($moduleDefs[$module][$module][$key]))
5543 // It was not loaded.... Fail. Cache null to prevent future repeats of this calculation
5544 sugar_cache_put($cache_key, SugarCache::EXTERNAL_CACHE_NULL_VALUE);
5548 // It has been loaded, cache the result.
5549 sugar_cache_put($cache_key, $moduleDefs[$module][$module][$key]);
5550 return $moduleDefs[$module][$module][$key];
5553 // It was not loaded.... Fail. Cache null to prevent future repeats of this calculation
5554 sugar_cache_put($cache_key, SugarCache::EXTERNAL_CACHE_NULL_VALUE);
5559 * Returns the ACL category for this module; defaults to the SugarBean::$acl_category if defined
5560 * otherwise it is SugarBean::$module_dir
5564 public function getACLCategory()
5566 return !empty($this->acl_category)?$this->acl_category:$this->module_dir;
5570 * Returns the query used for the export functionality for a module. Override this method if you wish
5571 * to have a custom query to pull this data together instead
5573 * @param string $order_by
5574 * @param string $where
5575 * @return string SQL query
5577 public function create_export_query($order_by, $where)
5579 return $this->create_new_list_query($order_by, $where, array(), array(), 0, '', false, $this, true, true);
5583 * Determine whether the given field is a relate field
5585 * @param string $field Field name
5588 protected function is_relate_field($field)
5590 if (!isset($this->field_defs[$field]))
5595 $field_def = $this->field_defs[$field];
5597 return isset($field_def['type'])
5598 && $field_def['type'] == 'relate'
5599 && isset($field_def['link']);