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-2011 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");
52 * SugarBean is the base class for all business objects in Sugar. It implements
53 * the primary functionality needed for manipulating business objects: create,
54 * retrieve, update, delete. It allows for searching and retrieving list of records.
55 * It allows for retrieving related objects (e.g. contacts related to a specific account).
57 * In the current implementation, there can only be one bean per folder.
58 * Naming convention has the bean name be the same as the module and folder name.
59 * All bean names should be singular (e.g. Contact). The primary table name for
60 * a bean should be plural (e.g. contacts).
66 * A pointer to the database helper object DBHelper
73 * When createing a bean, you can specify a value in the id column as
74 * long as that value is unique. During save, if the system finds an
75 * id, it assumes it is an update. Setting new_with_id to true will
76 * make sure the system performs an insert instead of an update.
78 * @var BOOL -- default false
80 var $new_with_id = false;
84 * Disble vardefs. This should be set to true only for beans that do not have varders. Tracker is an example
86 * @var BOOL -- default false
88 var $disable_vardefs = false;
92 * holds the full name of the user that an item is assigned to. Only used if notifications
93 * are turned on and going to be sent out.
97 var $new_assigned_user_name;
100 * An array of booleans. This array is cleared out when data is loaded.
101 * As date/times are converted, a "1" is placed under the key, the field is converted.
103 * @var Array of booleans
105 var $processed_dates_times = array();
108 * Whether to process date/time fields for storage in the database in GMT
112 var $process_save_dates =true;
115 * This signals to the bean that it is being saved in a mass mode.
116 * Examples of this kind of save are import and mass update.
117 * We turn off notificaitons of this is the case to make things more efficient.
121 var $save_from_post = true;
124 * When running a query on related items using the method: retrieve_by_string_fields
125 * this value will be set to true if more than one item matches the search criteria.
129 var $duplicates_found = false;
132 * The DBManager instance that was used to load this bean and should be used for
133 * future database interactions.
140 * true if this bean has been deleted, false otherwise.
147 * Should the date modified column of the bean be updated during save?
148 * This is used for admin level functionality that should not be updating
149 * the date modified. This is only used by sync to allow for updates to be
150 * replicated in a way that will not cause them to be replicated back.
154 var $update_date_modified = true;
157 * Should the modified by column of the bean be updated during save?
158 * This is used for admin level functionality that should not be updating
159 * the modified by column. This is only used by sync to allow for updates to be
160 * replicated in a way that will not cause them to be replicated back.
164 var $update_modified_by = true;
167 * Setting this to true allows for updates to overwrite the date_entered
171 var $update_date_entered = false;
174 * This allows for seed data to be created without using the current uesr to set the id.
175 * This should be replaced by altering the current user before the call to save.
179 //TODO This should be replaced by altering the current user before the call to save.
180 var $set_created_by = true;
185 * The database table where records of this Bean are stored.
189 var $table_name = '';
192 * This is the singular name of the bean. (i.e. Contact).
196 var $object_name = '';
198 /** Set this to true if you query contains a sub-select and bean is converting both select statements
199 * into count queries.
201 var $ungreedy_count=false;
204 * The name of the module folder for this type of bean.
208 var $module_dir = '';
209 var $module_name = '';
213 var $column_fields = array();
214 var $list_fields = array();
215 var $additional_column_fields = array();
216 var $relationship_fields = array();
217 var $current_notify_user;
218 var $fetched_row=false;
220 var $force_load_details = false;
221 var $optimistic_lock = false;
222 var $disable_custom_fields = false;
223 var $number_formatting_done = false;
224 var $process_field_encrypted=false;
226 * The default ACL type
228 var $acltype = 'module';
231 var $additional_meta_fields = array();
234 * Set to true in the child beans if the module supports importing
236 var $importable = false;
239 * Set to true in the child beans if the module use the special notification template
241 var $special_notification = false;
244 * Set to true if the bean is being dealt with in a workflow
246 var $in_workflow = false;
250 * By default it will be true but if any module is to be kept non visible
251 * to tracker, then its value needs to be overriden in that particular module to false.
254 var $tracker_visibility = true;
257 * Used to pass inner join string to ListView Data.
259 var $listview_inner_join = array();
262 * Set to true in <modules>/Import/views/view.step4.php if a module is being imported
264 var $in_import = false;
266 * Constructor for the bean, it performs following tasks:
268 * 1. Initalized a database connections
269 * 2. Load the vardefs for the module implemeting the class. cache the entries
271 * 3. Setup row-level security preference
272 * All implementing classes must call this constructor using the parent::SugarBean() class.
277 global $dictionary, $current_user;
278 static $loaded_defs = array();
279 $this->db = DBManagerFactory::getInstance();
280 $this->dbManager = DBManagerFactory::getInstance();
281 if (empty($this->module_name))
282 $this->module_name = $this->module_dir;
283 if((false == $this->disable_vardefs && empty($loaded_defs[$this->object_name])) || !empty($GLOBALS['reload_vardefs']))
285 VardefManager::loadVardef($this->module_dir, $this->object_name);
287 // build $this->column_fields from the field_defs if they exist
288 if (!empty($dictionary[$this->object_name]['fields'])) {
289 foreach ($dictionary[$this->object_name]['fields'] as $key=>$value_array) {
290 $column_fields[] = $key;
291 if(!empty($value_array['required']) && !empty($value_array['name'])) {
292 $this->required_fields[$value_array['name']] = 1;
295 $this->column_fields = $column_fields;
298 //setup custom fields
299 if(!isset($this->custom_fields) &&
300 empty($this->disable_custom_fields))
302 $this->setupCustomFields($this->module_dir);
304 //load up field_arrays from CacheHandler;
305 if(empty($this->list_fields))
306 $this->list_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'list_fields');
307 if(empty($this->column_fields))
308 $this->column_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'column_fields');
309 if(empty($this->required_fields))
310 $this->required_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'required_fields');
312 if(isset($GLOBALS['dictionary'][$this->object_name]) && !$this->disable_vardefs)
314 $this->field_name_map = $dictionary[$this->object_name]['fields'];
315 $this->field_defs = $dictionary[$this->object_name]['fields'];
317 if(!empty($dictionary[$this->object_name]['optimistic_locking']))
319 $this->optimistic_lock=true;
322 $loaded_defs[$this->object_name]['column_fields'] =& $this->column_fields;
323 $loaded_defs[$this->object_name]['list_fields'] =& $this->list_fields;
324 $loaded_defs[$this->object_name]['required_fields'] =& $this->required_fields;
325 $loaded_defs[$this->object_name]['field_name_map'] =& $this->field_name_map;
326 $loaded_defs[$this->object_name]['field_defs'] =& $this->field_defs;
330 $this->column_fields =& $loaded_defs[$this->object_name]['column_fields'] ;
331 $this->list_fields =& $loaded_defs[$this->object_name]['list_fields'];
332 $this->required_fields =& $loaded_defs[$this->object_name]['required_fields'];
333 $this->field_name_map =& $loaded_defs[$this->object_name]['field_name_map'];
334 $this->field_defs =& $loaded_defs[$this->object_name]['field_defs'];
335 $this->added_custom_field_defs = true;
337 if(!isset($this->custom_fields) &&
338 empty($this->disable_custom_fields))
340 $this->setupCustomFields($this->module_dir, false);
342 if(!empty($dictionary[$this->object_name]['optimistic_locking']))
344 $this->optimistic_lock=true;
348 if($this->bean_implements('ACL') && !empty($GLOBALS['current_user'])){
349 $this->acl_fields = (isset($dictionary[$this->object_name]['acl_fields']) && $dictionary[$this->object_name]['acl_fields'] === false)?false:true;
351 $this->populateDefaultValues();
356 * Returns the object name. If object_name is not set, table_name is returned.
358 * All implementing classes must set a value for the object_name variable.
360 * @param array $arr row of data fetched from the database.
364 function getObjectName()
366 if ($this->object_name)
367 return $this->object_name;
369 // This is a quick way out. The generated metadata files have the table name
370 // as the key. The correct way to do this is to override this function
371 // in bean and return the object name. That requires changing all the beans
372 // as well as put the object name in the generator.
373 return $this->table_name;
377 * Returns a list of fields with their definitions that have the audited property set to true.
378 * Before calling this function, check whether audit has been enabled for the table/module or not.
379 * You would set the audit flag in the implemting module's vardef file.
381 * @return an array of
382 * @see is_AuditEnabled
384 * Internal function, do not override.
386 function getAuditEnabledFieldDefinitions()
388 $aclcheck = $this->bean_implements('ACL');
389 $is_owner = $this->isOwner($GLOBALS['current_user']->id);
390 if (!isset($this->audit_enabled_fields))
393 $this->audit_enabled_fields=array();
394 foreach ($this->field_defs as $field => $properties)
399 !empty($properties['Audited']) || !empty($properties['audited']))
403 $this->audit_enabled_fields[$field]=$properties;
408 return $this->audit_enabled_fields;
412 * Return true if auditing is enabled for this object
413 * You would set the audit flag in the implemting module's vardef file.
417 * Internal function, do not override.
419 function is_AuditEnabled()
422 if (isset($dictionary[$this->getObjectName()]['audited']))
424 return $dictionary[$this->getObjectName()]['audited'];
435 * Returns the name of the audit table.
436 * Audit table's name is based on implementing class' table name.
438 * @return String Audit table name.
440 * Internal function, do not override.
442 function get_audit_table_name()
444 return $this->getTableName().'_audit';
448 * If auditing is enabled, create the audit table.
450 * Function is used by the install scripts and a repair utility in the admin panel.
452 * Internal function, do not override.
454 function create_audit_table()
457 $table_name=$this->get_audit_table_name();
459 require('metadata/audit_templateMetaData.php');
461 $fieldDefs = $dictionary['audit']['fields'];
462 $indices = $dictionary['audit']['indices'];
463 // '0' stands for the first index for all the audit tables
464 $indices[0]['name'] = 'idx_' . strtolower($this->getTableName()) . '_' . $indices[0]['name'];
465 $indices[1]['name'] = 'idx_' . strtolower($this->getTableName()) . '_' . $indices[1]['name'];
467 if(isset($dictionary['audit']['engine'])) {
468 $engine = $dictionary['audit']['engine'];
469 } else if(isset($dictionary[$this->getObjectName()]['engine'])) {
470 $engine = $dictionary[$this->getObjectName()]['engine'];
473 $sql=$this->dbManager->helper->createTableSQLParams($table_name, $fieldDefs, $indices, $engine);
475 $msg = "Error creating table: ".$table_name. ":";
476 $this->dbManager->query($sql,true,$msg);
480 * Returns the implementing class' table name.
482 * All implementing classes set a value for the table_name variable. This value is returned as the
483 * table name. If not set, table name is extracted from the implementing module's vardef.
485 * @return String Table name.
487 * Internal function, do not override.
489 function getTableName()
492 if(isset($this->table_name))
494 return $this->table_name;
496 return $dictionary[$this->getObjectName()]['table'];
500 * Returns field definitions for the implementing module.
502 * The definitions were loaded in the constructor.
504 * @return Array Field definitions.
506 * Internal function, do not override.
508 function getFieldDefinitions()
510 return $this->field_defs;
514 * Returns index definitions for the implementing module.
516 * The definitions were loaded in the constructor.
518 * @return Array Index definitions.
520 * Internal function, do not override.
522 function getIndices()
525 if(isset($dictionary[$this->getObjectName()]['indices']))
527 return $dictionary[$this->getObjectName()]['indices'];
533 * Returns field definition for the requested field name.
535 * The definitions were loaded in the constructor.
537 * @param string field name,
538 * @return Array Field properties or boolean false if the field doesn't exist
540 * Internal function, do not override.
542 function getFieldDefinition($name)
544 if ( !isset($this->field_defs[$name]) )
547 return $this->field_defs[$name];
551 * Returnss definition for the id field name.
553 * The definitions were loaded in the constructor.
555 * @return Array Field properties.
557 * Internal function, do not override.
559 function getPrimaryFieldDefinition()
561 $def = $this->getFieldDefinition("id");
563 $def = $this->getFieldDefinition(0);
567 * Returns the value for the requested field.
569 * When a row of data is fetched using the bean, all fields are created as variables in the context
570 * of the bean and then fetched values are set in these variables.
572 * @param string field name,
573 * @return varies Field value.
575 * Internal function, do not override.
577 function getFieldValue($name)
579 if (!isset($this->$name)){
582 if($this->$name === TRUE){
585 if($this->$name === FALSE){
592 * Basically undoes the effects of SugarBean::populateDefaultValues(); this method is best called right after object
595 public function unPopulateDefaultValues()
597 if ( !is_array($this->field_defs) )
600 foreach ($this->field_defs as $field => $value) {
601 if( !empty($this->$field)
602 && ((isset($value['default']) && $this->$field == $value['default']) || (!empty($value['display_default']) && $this->$field == $value['display_default']))
604 $this->$field = null;
607 if(!empty($this->$field) && !empty($value['display_default']) && in_array($value['type'], array('date', 'datetime', 'datetimecombo')) &&
608 $this->$field == $this->parseDateDefault($value['display_default'], ($value['type'] != 'date'))) {
609 $this->$field = null;
615 * Create date string from default value
617 * @param string $value
618 * @param bool $time Should be expect time set too?
621 protected function parseDateDefault($value, $time = false)
625 $dtAry = explode('&', $value, 2);
626 $dateValue = $timedate->getNow(true)->modify($dtAry[0]);
627 if(!empty($dtAry[1])) {
628 $timeValue = $timedate->fromString($dtAry[1]);
629 $dateValue->setTime($timeValue->hour, $timeValue->min, $timeValue->sec);
631 return $timedate->asUser($dateValue);
633 return $timedate->asUserDate($timedate->getNow(true)->modify($value));
637 function populateDefaultValues($force=false){
638 if ( !is_array($this->field_defs) )
640 foreach($this->field_defs as $field=>$value){
641 if((isset($value['default']) || !empty($value['display_default'])) && ($force || empty($this->$field))){
642 $type = $value['type'];
646 if(!empty($value['display_default'])){
647 $this->$field = $this->parseDateDefault($value['display_default']);
651 case 'datetimecombo':
652 if(!empty($value['display_default'])){
653 $this->$field = $this->parseDateDefault($value['display_default'], true);
657 if(empty($value['default']) && !empty($value['display_default']))
658 $this->$field = $value['display_default'];
660 $this->$field = $value['default'];
663 if ( isset($value['default']) && $value['default'] !== '' ) {
664 $this->$field = htmlentities($value['default'], ENT_QUOTES, 'UTF-8');
675 * Removes relationship metadata cache.
677 * Every module that has relationships defined with other modules, has this meta data cached. The cache is
678 * stores in 2 locations: relationships table and file system. This method clears the cache from both locations.
680 * @param string $key module whose meta cache is to be cleared.
681 * @param string $db database handle.
682 * @param string $tablename table name
683 * @param string $dictionary vardef for the module
684 * @param string $module_dir name of subdirectory where module is installed.
689 * Internal function, do not override.
691 function removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir)
693 //load the module dictionary if not supplied.
694 if ((!isset($dictionary) or empty($dictionary)) && !empty($module_dir))
696 $filename='modules/'. $module_dir . '/vardefs.php';
697 if(file_exists($filename))
702 if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
704 $GLOBALS['log']->fatal("removeRelationshipMeta: Metadata for table ".$tablename. " does not exist");
705 display_notice("meta data absent for table ".$tablename." keyed to $key ");
709 if (isset($dictionary[$key]['relationships']))
711 $RelationshipDefs = $dictionary[$key]['relationships'];
712 foreach ($RelationshipDefs as $rel_name)
714 Relationship::delete($rel_name,$db);
722 * This method has been deprecated.
724 * @see removeRelationshipMeta()
725 * @deprecated 4.5.1 - Nov 14, 2006
728 function remove_relationship_meta($key,$db,$log,$tablename,$dictionary,$module_dir)
730 SugarBean::removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
735 * Populates the relationship meta for a module.
737 * It is called during setup/install. It is used statically to create relationship meta data for many-to-many tables.
739 * @param string $key name of the object.
740 * @param object $db database handle.
741 * @param string $tablename table, meta data is being populated for.
742 * @param array dictionary vardef dictionary for the object. *
743 * @param string module_dir name of subdirectory where module is installed.
744 * @param boolean $iscustom Optional,set to true if module is installed in a custom directory. Default value is false.
747 * Internal function, do not override.
749 function createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir,$iscustom=false)
751 //load the module dictionary if not supplied.
752 if (empty($dictionary) && !empty($module_dir))
756 $filename='custom/modules/' . $module_dir . '/Ext/Vardefs/vardefs.ext.php';
762 // a very special case for the Employees module
763 // this must be done because the Employees/vardefs.php does an include_once on
765 $filename='modules/Users/vardefs.php';
769 $filename='modules/'. $module_dir . '/vardefs.php';
773 if(file_exists($filename))
776 // cn: bug 7679 - dictionary entries defined as $GLOBALS['name'] not found
777 if(empty($dictionary) || !empty($GLOBALS['dictionary'][$key]))
779 $dictionary = $GLOBALS['dictionary'];
784 $GLOBALS['log']->debug("createRelationshipMeta: no metadata file found" . $filename);
789 if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
791 $GLOBALS['log']->fatal("createRelationshipMeta: Metadata for table ".$tablename. " does not exist");
792 display_notice("meta data absent for table ".$tablename." keyed to $key ");
796 if (isset($dictionary[$key]['relationships']))
799 $RelationshipDefs = $dictionary[$key]['relationships'];
803 $beanList_ucase=array_change_key_case ( $beanList ,CASE_UPPER);
804 foreach ($RelationshipDefs as $rel_name=>$rel_def)
806 if (isset($rel_def['lhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['lhs_module'])])) {
807 $GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' lhs module is missing ' . $rel_def['lhs_module']);
810 if (isset($rel_def['rhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['rhs_module'])])) {
811 $GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' rhs module is missing ' . $rel_def['rhs_module']);
816 //check whether relationship exists or not first.
817 if (Relationship::exists($rel_name,$db))
819 $GLOBALS['log']->debug('Skipping, reltionship already exists '.$rel_name);
823 // add Id to the insert statement.
825 $value_list="'".create_guid()."'";
827 //add relationship name to the insert statement.
828 $column_list .= $delimiter.'relationship_name';
829 $value_list .= $delimiter."'".$rel_name."'";
831 //todo check whether $rel_def is an array or not.
832 //for now make that assumption.
833 //todo specify defaults if meta not defined.
834 foreach ($rel_def as $def_key=>$value)
836 $column_list.= $delimiter.$def_key;
837 $value_list.= $delimiter."'".$value."'";
840 //create the record. todo add error check.
841 $insert_string = "INSERT into relationships (" .$column_list. ") values (".$value_list.")";
842 $db->query($insert_string, true);
849 //log informational message stating no relationships meta was set for this bean.
855 * This method has been deprecated.
856 * @see createRelationshipMeta()
857 * @deprecated 4.5.1 - Nov 14, 2006
860 function create_relationship_meta($key,&$db,&$log,$tablename,$dictionary,$module_dir)
862 SugarBean::createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
867 * Loads the request relationship. This method should be called before performing any operations on the related data.
869 * This method searches the vardef array for the requested attribute's definition. If the attribute is of the type
870 * link then it creates a similary named variable and loads the relationship definition.
872 * @param string $rel_name relationship/attribute name.
875 function load_relationship($rel_name)
877 $GLOBALS['log']->debug("SugarBean[{$this->object_name}].load_relationships, Loading relationship (".$rel_name.").");
879 if (empty($rel_name))
881 $GLOBALS['log']->error("SugarBean.load_relationships, Null relationship name passed.");
884 $fieldDefs = $this->getFieldDefinitions();
886 //find all definitions of type link.
887 if (!empty($fieldDefs[$rel_name]))
889 //initialize a variable of type Link
890 require_once('data/Link2.php');
891 $class = load_link_class($fieldDefs[$rel_name]);
892 if (isset($this->$rel_name) && $this->$rel_name instanceof $class) {
895 //if rel_name is provided, search the fieldef array keys by name.
896 if (isset($fieldDefs[$rel_name]['type']) && $fieldDefs[$rel_name]['type'] == 'link')
898 if ($class == "Link2")
899 $this->$rel_name = new $class($rel_name, $this);
901 $this->$rel_name = new $class($fieldDefs[$rel_name]['relationship'], $this, $fieldDefs[$rel_name]);
903 if (empty($this->$rel_name) ||
904 (method_exists($this->$rel_name, "loadedSuccesfully") && !$this->$rel_name->loadedSuccesfully()))
906 unset($this->$rel_name);
912 $GLOBALS['log']->debug("SugarBean.load_relationships, Error Loading relationship (".$rel_name.")");
917 * Loads all attributes of type link.
919 * Method searches the implmenting module's vardef file for attributes of type link, and for each attribute
920 * create a similary named variable and load the relationship definition.
924 * Internal function, do not override.
926 function load_relationships()
929 $GLOBALS['log']->debug("SugarBean.load_relationships, Loading all relationships of type link.");
931 $linked_fields=$this->get_linked_fields();
932 require_once("data/Link2.php");
933 foreach($linked_fields as $name=>$properties)
935 $class = load_link_class($properties);
937 $this->$name=new $class($properties['relationship'], $this, $properties);
942 * Returns an array of beans of related data.
944 * For instance, if an account is related to 10 contacts , this function will return an array of contacts beans (10)
945 * with each bean representing a contact record.
946 * Method will load the relationship if not done so already.
948 * @param string $field_name relationship to be loaded.
949 * @param string $bean name class name of the related bean.
950 * @param array $sort_array optional, unused
951 * @param int $begin_index Optional, default 0, unused.
952 * @param int $end_index Optional, default -1
953 * @param int $deleted Optional, Default 0, 0 adds deleted=0 filter, 1 adds deleted=1 filter.
954 * @param string $optional_where, Optional, default empty.
956 * Internal function, do not override.
958 function get_linked_beans($field_name,$bean_name, $sort_array = array(), $begin_index = 0, $end_index = -1,
959 $deleted=0, $optional_where="")
961 if($this->load_relationship($field_name))
962 return array_values($this->$field_name->getBeans());
968 * Returns an array of fields that are of type link.
970 * @return array List of fields.
972 * Internal function, do not override.
974 function get_linked_fields()
977 $linked_fields=array();
979 // require_once('data/Link.php');
981 $fieldDefs = $this->getFieldDefinitions();
983 //find all definitions of type link.
984 if (!empty($fieldDefs))
986 foreach ($fieldDefs as $name=>$properties)
988 if (array_search('link',$properties) === 'type')
990 $linked_fields[$name]=$properties;
995 return $linked_fields;
999 * Returns an array of fields that are able to be Imported into
1000 * i.e. 'importable' not set to 'false'
1002 * @return array List of fields.
1004 * Internal function, do not override.
1006 function get_importable_fields()
1008 $importableFields = array();
1010 $fieldDefs= $this->getFieldDefinitions();
1012 if (!empty($fieldDefs)) {
1013 foreach ($fieldDefs as $key=>$value_array) {
1014 if ( (isset($value_array['importable'])
1015 && (is_string($value_array['importable']) && $value_array['importable'] == 'false'
1016 || is_bool($value_array['importable']) && $value_array['importable'] == false))
1017 || (isset($value_array['type']) && $value_array['type'] == 'link')
1018 || (isset($value_array['auto_increment'])
1019 && ($value_array['type'] == true || $value_array['type'] == 'true')) ) {
1020 // only allow import if we force it
1021 if (isset($value_array['importable'])
1022 && (is_string($value_array['importable']) && $value_array['importable'] == 'true'
1023 || is_bool($value_array['importable']) && $value_array['importable'] == true)) {
1024 $importableFields[$key]=$value_array;
1028 $importableFields[$key]=$value_array;
1033 return $importableFields;
1037 * Returns an array of fields that are of type relate.
1039 * @return array List of fields.
1041 * Internal function, do not override.
1043 function get_related_fields()
1046 $related_fields=array();
1048 // require_once('data/Link.php');
1050 $fieldDefs = $this->getFieldDefinitions();
1052 //find all definitions of type link.
1053 if (!empty($fieldDefs))
1055 foreach ($fieldDefs as $name=>$properties)
1057 if (array_search('relate',$properties) === 'type')
1059 $related_fields[$name]=$properties;
1064 return $related_fields;
1068 * Returns an array of fields that are required for import
1072 function get_import_required_fields()
1074 $importable_fields = $this->get_importable_fields();
1075 $required_fields = array();
1077 foreach ( $importable_fields as $name => $properties ) {
1078 if ( isset($properties['importable']) && is_string($properties['importable']) && $properties['importable'] == 'required' ) {
1079 $required_fields[$name] = $properties;
1083 return $required_fields;
1087 * Iterates through all the relationships and deletes all records for reach relationship.
1089 * @param string $id Primary key value of the parent reocrd
1091 function delete_linked($id)
1093 $linked_fields=$this->get_linked_fields();
1095 foreach ($linked_fields as $name => $value)
1097 if ($this->load_relationship($name))
1099 $GLOBALS['log']->debug("relationship $name loaded");
1100 $this->$name->delete($id);
1104 $GLOBALS['log']->error("error loading relationship $name");
1110 * Creates tables for the module implementing the class.
1111 * If you override this function make sure that your code can handles table creation.
1114 function create_tables()
1118 $key = $this->getObjectName();
1119 if (!array_key_exists($key, $dictionary))
1121 $GLOBALS['log']->fatal("create_tables: Metadata for table ".$this->table_name. " does not exist");
1122 display_notice("meta data absent for table ".$this->table_name." keyed to $key ");
1126 if(!$this->db->tableExists($this->table_name))
1128 $this->dbManager->createTable($this);
1129 if($this->bean_implements('ACL')){
1130 if(!empty($this->acltype)){
1131 ACLAction::addActions($this->getACLCategory(), $this->acltype);
1133 ACLAction::addActions($this->getACLCategory());
1139 echo "Table already exists : $this->table_name<br>";
1141 if($this->is_AuditEnabled()){
1142 if (!$this->db->tableExists($this->get_audit_table_name())) {
1143 $this->create_audit_table();
1151 * Delete the primary table for the module implementing the class.
1152 * If custom fields were added to this table/module, the custom table will be removed too, along with the cache
1153 * entries that define the custom fields.
1156 function drop_tables()
1159 $key = $this->getObjectName();
1160 if (!array_key_exists($key, $dictionary))
1162 $GLOBALS['log']->fatal("drop_tables: Metadata for table ".$this->table_name. " does not exist");
1163 echo "meta data absent for table ".$this->table_name."<br>\n";
1165 if(empty($this->table_name))return;
1166 if ($this->db->tableExists($this->table_name))
1168 $this->dbManager->dropTable($this);
1169 if ($this->db->tableExists($this->table_name. '_cstm'))
1171 $this->dbManager->dropTableName($this->table_name. '_cstm');
1172 DynamicField::deleteCache();
1174 if ($this->db->tableExists($this->get_audit_table_name())) {
1175 $this->dbManager->dropTableName($this->get_audit_table_name());
1184 * Loads the definition of custom fields defined for the module.
1185 * Local file system cache is created as needed.
1187 * @param string $module_name setting up custom fields for this module.
1188 * @param boolean $clean_load Optional, default true, rebuilds the cache if set to true.
1190 function setupCustomFields($module_name, $clean_load=true)
1192 $this->custom_fields = new DynamicField($module_name);
1193 $this->custom_fields->setup($this);
1198 * Cleans char, varchar, text, etc. fields of XSS type materials
1200 function cleanBean() {
1201 foreach($this->field_defs as $key => $def) {
1203 if (isset($def['type'])) {
1206 if(isset($def['dbType']))
1207 $type .= $def['dbType'];
1209 if((strpos($type, 'char') !== false ||
1210 strpos($type, 'text') !== false ||
1214 $str = from_html($this->$key);
1215 // Julian's XSS cleaner
1216 $potentials = clean_xss($str, false);
1218 if(is_array($potentials) && !empty($potentials)) {
1219 foreach($potentials as $bad) {
1220 $str = str_replace($bad, "", $str);
1222 $this->$key = to_html($str);
1229 * Implements a generic insert and update logic for any SugarBean
1230 * This method only works for subclasses that implement the same variable names.
1231 * This method uses the presence of an id field that is not null to signify and update.
1232 * The id field should not be set otherwise.
1234 * @param boolean $check_notify Optional, default false, if set to true assignee of the record is notified via email.
1235 * @todo Add support for field type validation and encoding of parameters.
1237 function save($check_notify = FALSE)
1239 $this->in_save = true;
1240 // cn: SECURITY - strip XSS potential vectors
1242 // This is used so custom/3rd-party code can be upgraded with fewer issues, this will be removed in a future release
1243 $this->fixUpFormatting();
1245 global $current_user, $action;
1248 if(empty($this->id))
1253 if ( $this->new_with_id == true )
1257 if(empty($this->date_modified) || $this->update_date_modified)
1259 $this->date_modified = $GLOBALS['timedate']->nowDb();
1262 $this->_checkOptimisticLocking($action, $isUpdate);
1264 if(!empty($this->modified_by_name)) $this->old_modified_by_name = $this->modified_by_name;
1265 if($this->update_modified_by)
1267 $this->modified_user_id = 1;
1269 if (!empty($current_user))
1271 $this->modified_user_id = $current_user->id;
1272 $this->modified_by_name = $current_user->user_name;
1275 if ($this->deleted != 1)
1283 if (empty($this->date_entered))
1285 $this->date_entered = $this->date_modified;
1287 if($this->set_created_by == true)
1289 // created by should always be this user
1290 $this->created_by = (isset($current_user)) ? $current_user->id : "";
1292 if( $this->new_with_id == false)
1294 $this->id = create_guid();
1296 $query = "INSERT into ";
1301 require_once("data/BeanFactory.php");
1302 BeanFactory::registerBean($this->module_name, $this);
1304 if (empty($GLOBALS['updating_relationships']) && empty($GLOBALS['saving_relationships']) && empty ($GLOBALS['resavingRelatedBeans']))
1306 $GLOBALS['saving_relationships'] = true;
1307 // let subclasses save related field changes
1308 $this->save_relationship_changes($isUpdate);
1309 $GLOBALS['saving_relationships'] = false;
1311 if($isUpdate && !$this->update_date_entered)
1313 unset($this->date_entered);
1315 // call the custom business logic
1316 $custom_logic_arguments['check_notify'] = $check_notify;
1319 $this->call_custom_logic("before_save", $custom_logic_arguments);
1320 unset($custom_logic_arguments);
1322 if(isset($this->custom_fields))
1324 $this->custom_fields->bean = $this;
1325 $this->custom_fields->save($isUpdate);
1328 // use the db independent query generator
1329 $this->preprocess_fields_on_save();
1331 //construct the SQL to create the audit record if auditing is enabled.
1332 $dataChanges=array();
1333 if ($this->is_AuditEnabled())
1335 if ($isUpdate && !isset($this->fetched_row))
1337 $GLOBALS['log']->debug('Auditing: Retrieve was not called, audit record will not be created.');
1341 $dataChanges=$this->dbManager->helper->getDataChanges($this);
1345 $this->_sendNotifications($check_notify);
1347 if ($this->db->dbType == "oci8")
1350 if ($this->db->dbType == 'mysql')
1352 // write out the SQL statement.
1353 $query .= $this->table_name." set ";
1357 foreach($this->field_defs as $field=>$value)
1359 if(!isset($value['source']) || $value['source'] == 'db')
1361 // Do not write out the id field on the update statement.
1362 // We are not allowed to change ids.
1363 if($isUpdate && ('id' == $field))
1365 //custom fields handle there save seperatley
1366 if(isset($this->field_name_map) && !empty($this->field_name_map[$field]['custom_type']))
1369 // Only assign variables that have been set.
1370 if(isset($this->$field))
1372 //bug: 37908 - this is to handle the issue where the bool value is false, but strlen(false) <= so it will
1373 //set the default value. TODO change this code to esend all fields through getFieldValue() like DbHelper->insertSql
1374 if(!empty($value['type']) && $value['type'] == 'bool'){
1375 $this->$field = $this->getFieldValue($field);
1378 if(strlen($this->$field) <= 0)
1380 if(!$isUpdate && isset($value['default']) && (strlen($value['default']) > 0))
1382 $this->$field = $value['default'];
1386 $this->$field = null;
1389 // Try comparing this element with the head element.
1395 if(is_null($this->$field))
1397 $query .= $field."=null";
1401 //added check for ints because sql-server does not like casting varchar with a decimal value
1403 if(isset($value['type']) and $value['type']=='int') {
1404 $query .= $field."=".$this->db->quote($this->$field);
1405 } elseif ( isset($value['len']) ) {
1406 $query .= $field."='".$this->db->quote($this->db->truncate(from_html($this->$field),$value['len']))."'";
1408 $query .= $field."='".$this->db->quote($this->$field)."'";
1417 $query = $query." WHERE ID = '$this->id'";
1418 $GLOBALS['log']->info("Update $this->object_name: ".$query);
1422 $GLOBALS['log']->info("Insert: ".$query);
1424 $GLOBALS['log']->info("Save: $query");
1425 $this->db->query($query, true);
1427 //process if type is set to mssql
1428 if ($this->db->dbType == 'mssql')
1432 // build out the SQL UPDATE statement.
1433 $query = "UPDATE " . $this->table_name." SET ";
1435 foreach($this->field_defs as $field=>$value)
1437 if(!isset($value['source']) || $value['source'] == 'db')
1439 // Do not write out the id field on the update statement.
1440 // We are not allowed to change ids.
1441 if($isUpdate && ('id' == $field))
1444 // If the field is an auto_increment field, then we shouldn't be setting it. This was added
1445 // specially for Bugs and Cases which have a number associated with them.
1446 if ($isUpdate && isset($this->field_name_map[$field]['auto_increment']) &&
1447 $this->field_name_map[$field]['auto_increment'] == true)
1450 //custom fields handle their save seperatley
1451 if(isset($this->field_name_map) && !empty($this->field_name_map[$field]['custom_type']))
1454 // Only assign variables that have been set.
1455 if(isset($this->$field))
1457 //bug: 37908 - this is to handle the issue where the bool value is false, but strlen(false) <= so it will
1458 //set the default value. TODO change this code to esend all fields through getFieldValue() like DbHelper->insertSql
1459 if(!empty($value['type']) && $value['type'] == 'bool'){
1460 $this->$field = $this->getFieldValue($field);
1463 if(strlen($this->$field) <= 0)
1465 if(!$isUpdate && isset($value['default']) && (strlen($value['default']) > 0))
1467 $this->$field = $value['default'];
1471 $this->$field = null;
1474 // Try comparing this element with the head element.
1480 if(is_null($this->$field))
1482 $query .= $field."=null";
1484 elseif ( isset($value['len']) )
1486 $query .= $field."='".$this->db->quote($this->db->truncate(from_html($this->$field),$value['len']))."'";
1490 $query .= $field."='".$this->db->quote($this->$field)."'";
1495 $query = $query." WHERE ID = '$this->id'";
1496 $GLOBALS['log']->info("Update $this->object_name: ".$query);
1502 foreach($this->field_defs as $field=>$value)
1504 if(!isset($value['source']) || $value['source'] == 'db')
1506 // Do not write out the id field on the update statement.
1507 // We are not allowed to change ids.
1508 //if($isUpdate && ('id' == $field)) continue;
1509 //custom fields handle there save seperatley
1511 if(isset($this->field_name_map) && !empty($this->field_name_map[$field]['custom_module']))
1514 // Only assign variables that have been set.
1515 if(isset($this->$field))
1517 //trim the value in case empty space is passed in.
1518 //this will allow default values set in db to take effect, otherwise
1519 //will insert blanks into db
1520 $trimmed_field = trim($this->$field);
1521 //if this value is empty, do not include the field value in statement
1522 if($trimmed_field =='')
1526 //bug: 37908 - this is to handle the issue where the bool value is false, but strlen(false) <= so it will
1527 //set the default value. TODO change this code to esend all fields through getFieldValue() like DbHelper->insertSql
1528 if(!empty($value['type']) && $value['type'] == 'bool'){
1529 $this->$field = $this->getFieldValue($field);
1531 //added check for ints because sql-server does not like casting varchar with a decimal value
1533 if(isset($value['type']) and $value['type']=='int') {
1534 $values[] = $this->db->quote($this->$field);
1535 } elseif ( isset($value['len']) ) {
1536 $values[] = "'".$this->db->quote($this->db->truncate(from_html($this->$field),$value['len']))."'";
1538 $values[] = "'".$this->db->quote($this->$field)."'";
1541 $columns[] = $field;
1545 // build out the SQL INSERT statement.
1546 $query = "INSERT INTO $this->table_name (" .implode("," , $columns). " ) VALUES ( ". implode("," , $values). ')';
1547 $GLOBALS['log']->info("Insert: ".$query);
1550 $GLOBALS['log']->info("Save: $query");
1551 $this->db->query($query, true);
1553 if (!empty($dataChanges) && is_array($dataChanges))
1555 foreach ($dataChanges as $change)
1557 $this->dbManager->helper->save_audit_records($this,$change);
1562 //If we aren't in setup mode and we have a current user and module, then we track
1563 if(isset($GLOBALS['current_user']) && isset($this->module_dir))
1565 $this->track_view($current_user->id, $this->module_dir, 'save');
1568 $this->call_custom_logic('after_save', '');
1570 //Now that the record has been saved, we don't want to insert again on further saves
1571 $this->new_with_id = false;
1572 $this->in_save = false;
1578 * Performs a check if the record has been modified since the specified date
1580 * @param date $date Datetime for verification
1581 * @param string $modified_user_id User modified by
1583 function has_been_modified_since($date, $modified_user_id)
1585 global $current_user;
1586 if (isset($current_user))
1588 if ($this->db->dbType == 'mssql')
1589 $date_modified_string = 'CONVERT(varchar(20), date_modified, 120)';
1591 $date_modified_string = 'date_modified';
1593 $query = "SELECT date_modified FROM $this->table_name WHERE id='$this->id' AND modified_user_id != '$current_user->id' AND (modified_user_id != '$modified_user_id' OR $date_modified_string > " . db_convert("'".$date."'", 'datetime') . ')';
1594 $result = $this->db->query($query);
1596 if($this->db->fetchByAssoc($result))
1605 * Determines which users receive a notification
1607 function get_notification_recipients() {
1608 $notify_user = new User();
1609 $notify_user->retrieve($this->assigned_user_id);
1610 $this->new_assigned_user_name = $notify_user->full_name;
1612 $GLOBALS['log']->info("Notifications: recipient is $this->new_assigned_user_name");
1614 $user_list = array($notify_user);
1617 //send notifications to followers, but ensure to not query for the assigned_user.
1618 return SugarFollowing::getFollowers($this, $notify_user);
1623 * Handles sending out email notifications when items are first assigned to users
1625 * @param string $notify_user user to notify
1626 * @param string $admin the admin user that sends out the notification
1628 function send_assignment_notifications($notify_user, $admin)
1630 global $current_user;
1632 if(($this->object_name == 'Meeting' || $this->object_name == 'Call') || $notify_user->receive_notifications)
1634 $sendToEmail = $notify_user->emailAddress->getPrimaryAddress($notify_user);
1636 if(empty($sendToEmail)) {
1637 $GLOBALS['log']->warn("Notifications: no e-mail address set for user {$notify_user->user_name}, cancelling send");
1641 $notify_mail = $this->create_notification_email($notify_user);
1642 $notify_mail->setMailerForSystem();
1644 if(empty($admin->settings['notify_send_from_assigning_user'])) {
1645 $notify_mail->From = $admin->settings['notify_fromaddress'];
1646 $notify_mail->FromName = (empty($admin->settings['notify_fromname'])) ? "" : $admin->settings['notify_fromname'];
1648 // Send notifications from the current user's e-mail (ifset)
1649 $fromAddress = $current_user->emailAddress->getReplyToAddress($current_user);
1650 $fromAddress = !empty($fromAddress) ? $fromAddress : $admin->settings['notify_fromaddress'];
1651 $notify_mail->From = $fromAddress;
1652 //Use the users full name is available otherwise default to system name
1653 $from_name = !empty($admin->settings['notify_fromname']) ? $admin->settings['notify_fromname'] : "";
1654 $from_name = !empty($current_user->full_name) ? $current_user->full_name : $from_name;
1655 $notify_mail->FromName = $from_name;
1658 $oe = new OutboundEmail();
1659 $oe = $oe->getUserMailerSettings($current_user);
1660 //only send if smtp server is defined
1662 if(empty($oe->mail_smtpserver)){
1663 $GLOBALS['log']->fatal("Notifications: error sending e-mail, smtp server was not found ");
1668 if(!$notify_mail->Send()) {
1669 $GLOBALS['log']->fatal("Notifications: error sending e-mail (method: {$notify_mail->Mailer}), (error: {$notify_mail->ErrorInfo})");
1671 $GLOBALS['log']->fatal("Notifications: e-mail successfully sent");
1679 * This function handles create the email notifications email.
1680 * @param string $notify_user the user to send the notification email to
1682 function create_notification_email($notify_user) {
1683 global $sugar_version;
1684 global $sugar_config;
1685 global $app_list_strings;
1686 global $current_user;
1689 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
1692 require_once("include/SugarPHPMailer.php");
1694 $notify_address = $notify_user->emailAddress->getPrimaryAddress($notify_user);
1695 $notify_name = $notify_user->full_name;
1696 $GLOBALS['log']->debug("Notifications: user has e-mail defined");
1698 $notify_mail = new SugarPHPMailer();
1699 $notify_mail->AddAddress($notify_address,$locale->translateCharsetMIME(trim($notify_name), 'UTF-8', $OBCharset));
1701 if(empty($_SESSION['authenticated_user_language'])) {
1702 $current_language = $sugar_config['default_language'];
1704 $current_language = $_SESSION['authenticated_user_language'];
1706 $xtpl = new XTemplate(get_notify_template_file($current_language));
1707 if($this->module_dir == "Cases") {
1708 $template_name = "Case"; //we should use Case, you can refer to the en_us.notify_template.html.
1711 $template_name = $beanList[$this->module_dir]; //bug 20637, in workflow this->object_name = strange chars.
1714 $this->current_notify_user = $notify_user;
1716 if(in_array('set_notification_body', get_class_methods($this))) {
1717 $xtpl = $this->set_notification_body($xtpl, $this);
1719 $xtpl->assign("OBJECT", $this->object_name);
1720 $template_name = "Default";
1722 if(!empty($_SESSION["special_notification"]) && $_SESSION["special_notification"]) {
1723 $template_name = $beanList[$this->module_dir].'Special';
1725 if($this->special_notification) {
1726 $template_name = $beanList[$this->module_dir].'Special';
1728 $xtpl->assign("ASSIGNED_USER", $this->new_assigned_user_name);
1729 $xtpl->assign("ASSIGNER", $current_user->name);
1732 if(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
1733 $port = $_SERVER['SERVER_PORT'];
1736 if (!isset($_SERVER['HTTP_HOST'])) {
1737 $_SERVER['HTTP_HOST'] = '';
1740 $httpHost = $_SERVER['HTTP_HOST'];
1742 if($colon = strpos($httpHost, ':')) {
1743 $httpHost = substr($httpHost, 0, $colon);
1746 $parsedSiteUrl = parse_url($sugar_config['site_url']);
1747 $host = $parsedSiteUrl['host'];
1748 if(!isset($parsedSiteUrl['port'])) {
1749 $parsedSiteUrl['port'] = 80;
1752 $port = ($parsedSiteUrl['port'] != 80) ? ":".$parsedSiteUrl['port'] : '';
1753 $path = !empty($parsedSiteUrl['path']) ? $parsedSiteUrl['path'] : "";
1754 $cleanUrl = "{$parsedSiteUrl['scheme']}://{$host}{$port}{$path}";
1756 $xtpl->assign("URL", $cleanUrl."/index.php?module={$this->module_dir}&action=DetailView&record={$this->id}");
1757 $xtpl->assign("SUGAR", "Sugar v{$sugar_version}");
1758 $xtpl->parse($template_name);
1759 $xtpl->parse($template_name . "_Subject");
1761 $notify_mail->Body = from_html(trim($xtpl->text($template_name)));
1762 $notify_mail->Subject = from_html($xtpl->text($template_name . "_Subject"));
1764 // cn: bug 8568 encode notify email in User's outbound email encoding
1765 $notify_mail->prepForOutbound();
1767 return $notify_mail;
1771 * This function is a good location to save changes that have been made to a relationship.
1772 * This should be overriden in subclasses that have something to save.
1774 * @param $is_update true if this save is an update.
1776 function save_relationship_changes($is_update, $exclude=array())
1778 $new_rel_id = false;
1779 $new_rel_link = false;
1781 //this allows us to dynamically relate modules without adding it to the relationship_fields array
1782 if(!empty($_REQUEST['relate_id']) && !empty($_REQUEST['relate_to']) && !in_array($_REQUEST['relate_to'], $exclude) && $_REQUEST['relate_id'] != $this->id){
1783 $new_rel_id = $_REQUEST['relate_id'];
1784 $new_rel_relname = $_REQUEST['relate_to'];
1785 if(!empty($this->in_workflow) && !empty($this->not_use_rel_in_req)) {
1786 $new_rel_id = !empty($this->new_rel_id) ? $this->new_rel_id : '';
1787 $new_rel_relname = !empty($this->new_rel_relname) ? $this->new_rel_relname : '';
1789 $new_rel_link = $new_rel_relname;
1790 //Try to find the link in this bean based on the relationship
1791 foreach ( $this->field_defs as $key => $def ) {
1792 if (isset($def['type']) && $def['type'] == 'link'
1793 && isset($def['relationship']) && $def['relationship'] == $new_rel_relname) {
1794 $new_rel_link = $key;
1800 // First we handle the preset fields listed in the fixed relationship_fields array hardcoded into the OOB beans
1801 // TODO: remove this mechanism and replace with mechanism exclusively based on the vardefs
1802 if (isset($this->relationship_fields) && is_array($this->relationship_fields))
1804 foreach ($this->relationship_fields as $id=>$rel_name)
1807 if(in_array($id, $exclude))continue;
1809 if(!empty($this->$id))
1811 $GLOBALS['log']->debug('save_relationship_changes(): From relationship_field array - adding a relationship record: '.$rel_name . ' = ' . $this->$id);
1812 //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
1813 if($this->$id == $new_rel_id){
1814 $new_rel_id = false;
1816 $this->load_relationship($rel_name);
1817 $this->$rel_name->add($this->$id);
1822 //if before value is not empty then attempt to delete relationship
1823 if(!empty($this->rel_fields_before_value[$id]))
1825 $GLOBALS['log']->debug('save_relationship_changes(): From relationship_field array - attempting to remove the relationship record, using relationship attribute'.$rel_name);
1826 $this->load_relationship($rel_name);
1827 $this->$rel_name->delete($this->id,$this->rel_fields_before_value[$id]);
1833 /* Next, we'll attempt to update all of the remaining relate fields in the vardefs that have 'save' set in their field_def
1834 Only the 'save' fields should be saved as some vardef entries today are not for display only purposes and break the application if saved
1835 If the vardef has entries for field <a> of type relate, where a->id_name = <b> and field <b> of type link
1836 then we receive a value for b from the MVC in the _REQUEST, and it should be set in the bean as $this->$b
1839 foreach ( $this->field_defs as $def )
1841 if ($def [ 'type' ] == 'relate' && isset ( $def [ 'id_name'] ) && isset ( $def [ 'link'] ) && isset ( $def[ 'save' ]) )
1843 if ( in_array( $def['id_name'], $exclude) || in_array( $def['id_name'], $this->relationship_fields ) )
1844 continue ; // continue to honor the exclude array and exclude any relationships that will be handled by the relationship_fields mechanism
1846 $linkField = $def [ 'link' ] ;
1847 if (isset( $this->field_defs[$linkField ] ))
1849 $linkfield = $this->field_defs[$linkField] ;
1851 if ($this->load_relationship ( $linkField))
1853 $idName = $def['id_name'];
1855 if (!empty($this->rel_fields_before_value[$idName]) && empty($this->$idName))
1857 //if before value is not empty then attempt to delete relationship
1858 $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' ]]}");
1859 $this->$def ['link' ]->delete($this->id, $this->rel_fields_before_value[$def [ 'id_name' ]] );
1862 if (!empty($this->$idName) && is_string($this->$idName))
1864 $GLOBALS['log']->debug("save_relationship_changes(): From field_defs - attempting to add a relationship record - {$def [ 'link' ]} = {$this->$def [ 'id_name' ]}" );
1866 $this->$linkField->add($this->$idName);
1869 $GLOBALS['log']->fatal("Failed to load relationship {$linkField} while saving {$this->module_dir}");
1875 // Finally, we update a field listed in the _REQUEST['*/relate_id']/_REQUEST['relate_to'] mechanism (if it hasn't already been updated above)
1876 if(!empty($new_rel_id)){
1878 if($this->load_relationship($new_rel_link)){
1879 $this->$new_rel_link->add($new_rel_id);
1882 $lower_link = strtolower($new_rel_link);
1883 if($this->load_relationship($lower_link)){
1884 $this->$lower_link->add($new_rel_id);
1887 require_once('data/Link2.php');
1888 $rel = Relationship::retrieve_by_modules($new_rel_link, $this->module_dir, $GLOBALS['db'], 'many-to-many');
1891 foreach($this->field_defs as $field=>$def){
1892 if($def['type'] == 'link' && !empty($def['relationship']) && $def['relationship'] == $rel){
1893 $this->load_relationship($field);
1894 $this->$field->add($new_rel_id);
1900 //ok so we didn't find it in the field defs let's save it anyway if we have the relationshp
1902 $this->$rel=new Link2($rel, $this, array());
1903 $this->$rel->add($new_rel_id);
1913 * This function retrieves a record of the appropriate type from the DB.
1914 * It fills in all of the fields from the DB into the object it was called on.
1916 * @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.
1917 * @return this - The object that it was called apon or null if exactly 1 record was not found.
1921 function check_date_relationships_load()
1923 global $disable_date_format;
1925 if (empty($timedate))
1926 $timedate=TimeDate::getInstance();
1928 if(empty($this->field_defs))
1932 foreach($this->field_defs as $fieldDef)
1934 $field = $fieldDef['name'];
1935 if(!isset($this->processed_dates_times[$field]))
1937 $this->processed_dates_times[$field] = '1';
1938 if(empty($this->$field)) continue;
1939 if($field == 'date_modified' || $field == 'date_entered')
1941 $this->$field = from_db_convert($this->$field, 'datetime');
1942 if(empty($disable_date_format)) {
1943 $this->$field = $timedate->to_display_date_time($this->$field);
1946 elseif(isset($this->field_name_map[$field]['type']))
1948 $type = $this->field_name_map[$field]['type'];
1950 if($type == 'relate' && isset($this->field_name_map[$field]['custom_module']))
1952 $type = $this->field_name_map[$field]['type'];
1957 $this->$field = from_db_convert($this->$field, 'date');
1959 if($this->$field == '0000-00-00')
1962 } elseif(!empty($this->field_name_map[$field]['rel_field']))
1964 $rel_field = $this->field_name_map[$field]['rel_field'];
1966 if(!empty($this->$rel_field))
1968 $this->$rel_field=from_db_convert($this->$rel_field, 'time');
1969 if(empty($disable_date_format)) {
1970 $mergetime = $timedate->merge_date_time($this->$field,$this->$rel_field);
1971 $this->$field = $timedate->to_display_date($mergetime);
1972 $this->$rel_field = $timedate->to_display_time($mergetime);
1978 if(empty($disable_date_format)) {
1979 $this->$field = $timedate->to_display_date($this->$field, false);
1982 } elseif($type == 'datetime' || $type == 'datetimecombo')
1984 if($this->$field == '0000-00-00 00:00:00')
1990 $this->$field = from_db_convert($this->$field, 'datetime');
1991 if(empty($disable_date_format)) {
1992 $this->$field = $timedate->to_display_date_time($this->$field, true, true);
1995 } elseif($type == 'time')
1997 if($this->$field == '00:00:00')
2002 //$this->$field = from_db_convert($this->$field, 'time');
2003 if(empty($this->field_name_map[$field]['rel_field']) && empty($disable_date_format))
2005 $this->$field = $timedate->to_display_time($this->$field,true, false);
2008 } elseif($type == 'encrypt' && empty($disable_date_format)){
2009 $this->$field = $this->decrypt_after_retrieve($this->$field);
2017 * This function processes the fields before save.
2018 * Interal function, do not override.
2020 function preprocess_fields_on_save()
2022 $GLOBALS['log']->deprecated('SugarBean.php: preprocess_fields_on_save() is deprecated');
2026 * Removes formatting from values posted from the user interface.
2027 * It only unformats numbers. Function relies on user/system prefernce for format strings.
2029 * Internal Function, do not override.
2031 function unformat_all_fields()
2033 $GLOBALS['log']->deprecated('SugarBean.php: unformat_all_fields() is deprecated');
2037 * This functions adds formatting to all number fields before presenting them to user interface.
2039 * Internal function, do not override.
2041 function format_all_fields()
2043 $GLOBALS['log']->deprecated('SugarBean.php: format_all_fields() is deprecated');
2046 function format_field($fieldDef)
2048 $GLOBALS['log']->deprecated('SugarBean.php: format_field() is deprecated');
2052 * Function corrects any bad formatting done by 3rd party/custom code
2054 * 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
2056 function fixUpFormatting()
2059 static $boolean_false_values = array('off', 'false', '0', 'no');
2062 foreach($this->field_defs as $field=>$def)
2064 if ( !isset($this->$field) ) {
2067 if ( (isset($def['source'])&&$def['source']=='non-db') || $field == 'deleted' ) {
2070 if ( isset($this->fetched_row[$field]) && $this->$field == $this->fetched_row[$field] ) {
2071 // Don't hand out warnings because the field was untouched between retrieval and saving, most database drivers hand pretty much everything back as strings.
2074 $reformatted = false;
2075 switch($def['type']) {
2077 case 'datetimecombo':
2078 if(empty($this->$field)) break;
2079 if ($this->$field == 'NULL') {
2083 if ( ! preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/',$this->$field) ) {
2084 // This appears to be formatted in user date/time
2085 $this->$field = $timedate->to_db($this->$field);
2086 $reformatted = true;
2090 if(empty($this->$field)) break;
2091 if ($this->$field == 'NULL') {
2095 if ( ! preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$this->$field) ) {
2096 // This date appears to be formatted in the user's format
2097 $this->$field = $timedate->to_db_date($this->$field, false);
2098 $reformatted = true;
2102 if(empty($this->$field)) break;
2103 if ($this->$field == 'NULL') {
2107 if ( preg_match('/(am|pm)/i',$this->$field) ) {
2108 // This time appears to be formatted in the user's format
2109 $this->$field = $timedate->fromUserTime($this->$field)->format(TimeDate::DB_TIME_FORMAT);
2110 $reformatted = true;
2117 if ( $this->$field === '' || $this->$field == NULL || $this->$field == 'NULL') {
2120 if ( is_string($this->$field) ) {
2121 $this->$field = (float)unformat_number($this->$field);
2122 $reformatted = true;
2131 if ( $this->$field === '' || $this->$field == NULL || $this->$field == 'NULL') {
2134 if ( is_string($this->$field) ) {
2135 $this->$field = (int)unformat_number($this->$field);
2136 $reformatted = true;
2140 if (empty($this->$field)) {
2141 $this->$field = false;
2142 } else if(true === $this->$field || 1 == $this->$field) {
2143 $this->$field = true;
2144 } else if(in_array(strval($this->$field), $boolean_false_values)) {
2145 $this->$field = false;
2146 $reformatted = true;
2148 $this->$field = true;
2149 $reformatted = true;
2153 $this->$field = $this->encrpyt_before_save($this->$field);
2156 if ( $reformatted ) {
2157 $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');
2164 * Function fetches a single row of data given the primary key value.
2166 * The fetched data is then set into the bean. The function also processes the fetched data by formattig
2167 * date/time and numeric values.
2169 * @param string $id Optional, default -1, is set to -1 id value from the bean is used, else, passed value is used
2170 * @param boolean $encode Optional, default true, encodes the values fetched from the database.
2171 * @param boolean $deleted Optional, default true, if set to false deleted filter will not be added.
2173 * Internal function, do not override.
2175 function retrieve($id = -1, $encode=true,$deleted=true)
2178 $custom_logic_arguments['id'] = $id;
2179 $this->call_custom_logic('before_retrieve', $custom_logic_arguments);
2185 if(isset($this->custom_fields))
2187 $custom_join = $this->custom_fields->getJOIN();
2190 $custom_join = false;
2194 $query = "SELECT $this->table_name.*". $custom_join['select']. " FROM $this->table_name ";
2198 $query = "SELECT $this->table_name.* FROM $this->table_name ";
2203 $query .= ' ' . $custom_join['join'];
2205 $query .= " WHERE $this->table_name.id = '$id' ";
2206 if ($deleted) $query .= " AND $this->table_name.deleted=0";
2207 $GLOBALS['log']->debug("Retrieve $this->object_name : ".$query);
2208 //requireSingleResult has beeen deprecated.
2209 //$result = $this->db->requireSingleResult($query, true, "Retrieving record by id $this->table_name:$id found ");
2210 $result = $this->db->limitQuery($query,0,1,true, "Retrieving record by id $this->table_name:$id found ");
2216 $row = $this->db->fetchByAssoc($result, -1, $encode);
2222 //make copy of the fetched row for construction of audit record and for business logic/workflow
2223 $this->fetched_row=$row;
2224 $this->populateFromRow($row);
2226 global $module, $action;
2227 //Just to get optimistic locking working for this release
2228 if($this->optimistic_lock && $module == $this->module_dir && $action =='EditView' )
2230 $_SESSION['o_lock_id']= $id;
2231 $_SESSION['o_lock_dm']= $this->date_modified;
2232 $_SESSION['o_lock_on'] = $this->object_name;
2234 $this->processed_dates_times = array();
2235 $this->check_date_relationships_load();
2239 $this->custom_fields->fill_relationships();
2242 $this->fill_in_additional_detail_fields();
2243 $this->fill_in_relationship_fields();
2244 //make a copy of fields in the relatiosnhip_fields array. these field values will be used to
2245 //clear relatioship.
2246 foreach ( $this->field_defs as $key => $def )
2248 if ($def [ 'type' ] == 'relate' && isset ( $def [ 'id_name'] ) && isset ( $def [ 'link'] ) && isset ( $def[ 'save' ])) {
2249 if (isset($this->$key)) {
2250 $this->rel_fields_before_value[$key]=$this->$key;
2251 if (isset($this->$def [ 'id_name']))
2252 $this->rel_fields_before_value[$def [ 'id_name']]=$this->$def [ 'id_name'];
2255 $this->rel_fields_before_value[$key]=null;
2258 if (isset($this->relationship_fields) && is_array($this->relationship_fields))
2260 foreach ($this->relationship_fields as $rel_id=>$rel_name)
2262 if (isset($this->$rel_id))
2263 $this->rel_fields_before_value[$rel_id]=$this->$rel_id;
2265 $this->rel_fields_before_value[$rel_id]=null;
2269 // call the custom business logic
2270 $custom_logic_arguments['id'] = $id;
2271 $custom_logic_arguments['encode'] = $encode;
2272 $this->call_custom_logic("after_retrieve", $custom_logic_arguments);
2273 unset($custom_logic_arguments);
2275 require_once("data/BeanFactory.php");
2276 BeanFactory::registerBean($this->module_dir, $this);
2281 * Sets value from fetched row into the bean.
2283 * @param array $row Fetched row
2284 * @todo loop through vardefs instead
2285 * @internal runs into an issue when populating from field_defs for users - corrupts user prefs
2287 * Internal function, do not override.
2289 function populateFromRow($row)
2292 foreach($this->field_defs as $field=>$field_value)
2294 if($field == 'user_preferences' && $this->module_dir == 'Users')
2296 $rfield = $field; // fetch returns it in lowercase only
2297 if(isset($row[$rfield]))
2299 $this->$field = $row[$rfield];
2300 $owner = $rfield . '_owner';
2301 if(!empty($row[$owner])){
2302 $this->$owner = $row[$owner];
2307 $this->$field = $nullvalue;
2315 * Add any required joins to the list count query. The joins are required if there
2316 * is a field in the $where clause that needs to be joined.
2318 * @param string $query
2319 * @param string $where
2321 * Internal Function, do Not override.
2323 function add_list_count_joins(&$query, $where)
2325 $custom_join = $this->custom_fields->getJOIN();
2328 $query .= $custom_join['join'];
2334 * Changes the select expression of the given query to be 'count(*)' so you
2335 * can get the number of items the query will return. This is used to
2336 * populate the upper limit on ListViews.
2338 * @param string $query Select query string
2339 * @return string count query
2341 * Internal function, do not override.
2343 function create_list_count_query($query)
2345 // remove the 'order by' clause which is expected to be at the end of the query
2346 $pattern = '/\sORDER BY.*/is'; // ignores the case
2348 $query = preg_replace($pattern, $replacement, $query);
2349 //handle distinct clause
2351 if(substr_count(strtolower($query), 'distinct')){
2352 if (!empty($this->seed) && !empty($this->seed->table_name ))
2353 $star = 'DISTINCT ' . $this->seed->table_name . '.id';
2355 $star = 'DISTINCT ' . $this->table_name . '.id';
2359 // change the select expression to 'count(*)'
2360 $pattern = '/SELECT(.*?)(\s){1}FROM(\s){1}/is'; // ignores the case
2361 $replacement = 'SELECT count(' . $star . ') c FROM ';
2363 //if the passed query has union clause then replace all instances of the pattern.
2364 //this is very rare. I have seen this happening only from projects module.
2365 //in addition to this added a condition that has union clause and uses
2367 if (strstr($query," UNION ALL ") !== false) {
2369 //seperate out all the queries.
2370 $union_qs=explode(" UNION ALL ", $query);
2371 foreach ($union_qs as $key=>$union_query) {
2373 preg_match($pattern, $union_query, $matches);
2374 if (!empty($matches)) {
2375 if (stristr($matches[0], "distinct")) {
2376 if (!empty($this->seed) && !empty($this->seed->table_name ))
2377 $star = 'DISTINCT ' . $this->seed->table_name . '.id';
2379 $star = 'DISTINCT ' . $this->table_name . '.id';
2382 $replacement = 'SELECT count(' . $star . ') c FROM ';
2383 $union_qs[$key] = preg_replace($pattern, $replacement, $union_query,1);
2385 $modified_select_query=implode(" UNION ALL ",$union_qs);
2387 $modified_select_query = preg_replace($pattern, $replacement, $query,1);
2391 return $modified_select_query;
2395 * This function returns a paged list of the current object type. It is intended to allow for
2396 * hopping back and forth through pages of data. It only retrieves what is on the current page.
2398 * @internal This method must be called on a new instance. It trashes the values of all the fields in the current one.
2399 * @param string $order_by
2400 * @param string $where Additional where clause
2401 * @param int $row_offset Optaional,default 0, starting row number
2402 * @param init $limit Optional, default -1
2403 * @param int $max Optional, default -1
2404 * @param boolean $show_deleted Optioanl, default 0, if set to 1 system will show deleted records.
2405 * @return array Fetched data.
2407 * Internal function, do not override.
2410 function get_list($order_by = "", $where = "", $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $singleSelect=false)
2412 $GLOBALS['log']->debug("get_list: order_by = '$order_by' and where = '$where' and limit = '$limit'");
2413 if(isset($_SESSION['show_deleted']))
2417 $order_by=$this->process_order_by($order_by, null);
2419 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2421 global $current_user;
2422 $owner_where = $this->getOwnerWhere($current_user->id);
2424 //rrs - because $this->getOwnerWhere() can return '' we need to be sure to check for it and
2425 //handle it properly else you could get into a situation where you are create a where stmt like
2427 if(!empty($owner_where)){
2429 $where = $owner_where;
2431 $where .= ' AND '. $owner_where;
2435 $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted,'',false,null,$singleSelect);
2436 return $this->process_list_query($query, $row_offset, $limit, $max, $where);
2440 * Prefixes column names with this bean's table name.
2441 * This call can be ignored for mysql since it does a better job than Oracle in resolving ambiguity.
2443 * @param string $order_by Order by clause to be processed
2444 * @param string $submodule name of the module this order by clause is for
2445 * @return string Processed order by clause
2447 * Internal function, do not override.
2449 function process_order_by ($order_by, $submodule)
2451 if (empty($order_by))
2454 //submodule is empty,this is for list object in focus
2455 if (empty($submodule))
2457 $bean_queried = &$this;
2461 //submodule is set, so this is for subpanel, use submodule
2462 $bean_queried = $submodule;
2464 $elements = explode(',',$order_by);
2465 foreach ($elements as $key=>$value)
2467 if (strchr($value,'.') === false)
2469 //value might have ascending and descending decorations
2470 $list_column = explode(' ',trim($value));
2471 if (isset($list_column[0]))
2473 $list_column_name=trim($list_column[0]);
2474 if (isset($bean_queried->field_defs[$list_column_name]))
2476 $source=isset($bean_queried->field_defs[$list_column_name]['source']) ? $bean_queried->field_defs[$list_column_name]['source']:'db';
2477 if (empty($bean_queried->field_defs[$list_column_name]['table']) && $source=='db')
2479 $list_column[0] = $bean_queried->table_name .".".$list_column[0] ;
2481 if (empty($bean_queried->field_defs[$list_column_name]['table']) && $source=='custom_fields')
2483 $list_column[0] = $bean_queried->table_name ."_cstm.".$list_column[0] ;
2485 $value = implode($list_column,' ');
2486 // Bug 38803 - Use CONVERT() function when doing an order by on ntext, text, and image fields
2487 if ( $this->db->dbType == 'mssql'
2488 && $source != 'non-db'
2490 $this->db->getHelper()->getColumnType($this->db->getHelper()->getFieldType($bean_queried->field_defs[$list_column_name])),
2491 array('ntext','text','image')
2494 $value = "CONVERT(varchar(500),{$list_column[0]}) {$list_column[1]}";
2496 // Bug 29011 - Use TO_CHAR() function when doing an order by on a clob field
2497 if ( $this->db->dbType == 'oci8'
2498 && $source != 'non-db'
2500 $this->db->getHelper()->getColumnType($this->db->getHelper()->getFieldType($bean_queried->field_defs[$list_column_name])),
2504 $value = "TO_CHAR({$list_column[0]}) {$list_column[1]}";
2509 $GLOBALS['log']->debug("process_order_by: ($list_column[0]) does not have a vardef entry.");
2513 $elements[$key]=$value;
2515 return implode($elements,',');
2521 * Returns a detail object like retrieving of the current object type.
2523 * It is intended for use in navigation buttons on the DetailView. It will pass an offset and limit argument to the sql query.
2524 * @internal This method must be called on a new instance. It overrides the values of all the fields in the current one.
2526 * @param string $order_by
2527 * @param string $where Additional where clause
2528 * @param int $row_offset Optaional,default 0, starting row number
2529 * @param init $limit Optional, default -1
2530 * @param int $max Optional, default -1
2531 * @param boolean $show_deleted Optioanl, default 0, if set to 1 system will show deleted records.
2532 * @return array Fetched data.
2534 * Internal function, do not override.
2536 function get_detail($order_by = "", $where = "", $offset = 0, $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)
2538 $GLOBALS['log']->debug("get_detail: order_by = '$order_by' and where = '$where' and limit = '$limit' and offset = '$offset'");
2539 if(isset($_SESSION['show_deleted']))
2544 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2546 global $current_user;
2547 $owner_where = $this->getOwnerWhere($current_user->id);
2551 $where = $owner_where;
2555 $where .= ' AND '. $owner_where;
2558 $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted, $offset);
2560 //Add Limit and Offset to query
2561 //$query .= " LIMIT 1 OFFSET $offset";
2563 return $this->process_detail_query($query, $row_offset, $limit, $max, $where, $offset);
2567 * Fetches data from all related tables.
2569 * @param object $child_seed
2570 * @param string $related_field_name relation to fetch data for
2571 * @param string $order_by Optional, default empty
2572 * @param string $where Optional, additional where clause
2573 * @return array Fetched data.
2575 * Internal function, do not override.
2577 function get_related_list($child_seed,$related_field_name, $order_by = "", $where = "",
2578 $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)
2580 global $layout_edit_mode;
2581 if(isset($layout_edit_mode) && $layout_edit_mode)
2583 $response = array();
2584 $child_seed->assign_display_fields($child_seed->module_dir);
2585 $response['list'] = array($child_seed);
2586 $response['row_count'] = 1;
2587 $response['next_offset'] = 0;
2588 $response['previous_offset'] = 0;
2592 $GLOBALS['log']->debug("get_related_list: order_by = '$order_by' and where = '$where' and limit = '$limit'");
2593 if(isset($_SESSION['show_deleted']))
2598 $this->load_relationship($related_field_name);
2599 $query_array = $this->$related_field_name->getQuery(true);
2600 $entire_where = $query_array['where'];
2603 if(empty($entire_where))
2605 $entire_where = ' WHERE ' . $where;
2609 $entire_where .= ' AND ' . $where;
2613 $query = 'SELECT '.$child_seed->table_name.'.* ' . $query_array['from'] . ' ' . $entire_where;
2614 if(!empty($order_by))
2616 $query .= " ORDER BY " . $order_by;
2619 return $child_seed->process_list_query($query, $row_offset, $limit, $max, $where);
2623 protected static function build_sub_queries_for_union($subpanel_list, $subpanel_def, $parentbean, $order_by)
2625 global $layout_edit_mode, $beanFiles, $beanList;
2626 $subqueries = array();
2627 foreach($subpanel_list as $this_subpanel)
2629 if(!$this_subpanel->isDatasourceFunction() || ($this_subpanel->isDatasourceFunction()
2630 && isset($this_subpanel->_instance_properties['generate_select'])
2631 && $this_subpanel->_instance_properties['generate_select']==true))
2633 //the custom query function must return an array with
2634 if ($this_subpanel->isDatasourceFunction()) {
2635 $shortcut_function_name = $this_subpanel->get_data_source_name();
2636 $parameters=$this_subpanel->get_function_parameters();
2637 if (!empty($parameters))
2639 //if the import file function is set, then import the file to call the custom function from
2640 if (is_array($parameters) && isset($parameters['import_function_file'])){
2641 //this call may happen multiple times, so only require if function does not exist
2642 if(!function_exists($shortcut_function_name)){
2643 require_once($parameters['import_function_file']);
2645 //call function from required file
2646 $query_array = $shortcut_function_name($parameters);
2648 //call function from parent bean
2649 $query_array = $parentbean->$shortcut_function_name($parameters);
2654 $query_array = $parentbean->$shortcut_function_name();
2657 $related_field_name = $this_subpanel->get_data_source_name();
2658 if (!$parentbean->load_relationship($related_field_name)){
2659 unset ($parentbean->$related_field_name);
2662 $query_array = $parentbean->$related_field_name->getSubpanelQuery(array(), true);
2664 $table_where = $this_subpanel->get_where();
2665 $where_definition = $query_array['where'];
2667 if(!empty($table_where))
2669 if(empty($where_definition))
2671 $where_definition = $table_where;
2675 $where_definition .= ' AND ' . $table_where;
2679 $submodulename = $this_subpanel->_instance_properties['module'];
2680 $submoduleclass = $beanList[$submodulename];
2681 //require_once($beanFiles[$submoduleclass]);
2682 $submodule = new $submoduleclass();
2683 $subwhere = $where_definition;
2687 $subwhere = str_replace('WHERE', '', $subwhere);
2688 $list_fields = $this_subpanel->get_list_fields();
2689 foreach($list_fields as $list_key=>$list_field)
2691 if(isset($list_field['usage']) && $list_field['usage'] == 'display_only')
2693 unset($list_fields[$list_key]);
2698 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'))
2700 $order_by = $submodule->table_name .'.'. $order_by;
2702 $table_name = $this_subpanel->table_name;
2703 $panel_name=$this_subpanel->name;
2705 $params['distinct'] = $this_subpanel->distinct_query();
2707 $params['joined_tables'] = $query_array['join_tables'];
2708 $params['include_custom_fields'] = !$subpanel_def->isCollection();
2709 $params['collection_list'] = $subpanel_def->get_inst_prop_value('collection_list');
2711 $subquery = $submodule->create_new_list_query('',$subwhere ,$list_fields,$params, 0,'', true,$parentbean);
2713 $subquery['select'] = $subquery['select']." , '$panel_name' panel_name ";
2714 $subquery['from'] = $subquery['from'].$query_array['join'];
2715 $subquery['query_array'] = $query_array;
2716 $subquery['params'] = $params;
2718 $subqueries[] = $subquery;
2725 * Constructs a query to fetch data for supanels and list views
2727 * It constructs union queries for activities subpanel.
2729 * @param SugarBean $parentbean constructing queries for link attributes in this bean
2730 * @param string $order_by Optional, order by clause
2731 * @param string $sort_order Optional, sort order
2732 * @param string $where Optional, additional where clause
2734 * Internal Function, do not overide.
2736 function get_union_related_list($parentbean, $order_by = "", $sort_order='', $where = "",
2737 $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $subpanel_def)
2739 $secondary_queries = array();
2740 global $layout_edit_mode, $beanFiles, $beanList;
2742 if(isset($_SESSION['show_deleted']))
2747 $final_query_rows = '';
2748 $subpanel_list=array();
2749 if ($subpanel_def->isCollection())
2751 $subpanel_def->load_sub_subpanels();
2752 $subpanel_list=$subpanel_def->sub_subpanels;
2756 $subpanel_list[]=$subpanel_def;
2761 //Breaking the building process into two loops. The first loop gets a list of all the sub-queries.
2762 //The second loop merges the queries and forces them to select the same number of columns
2763 //All columns in a sub-subpanel group must have the same aliases
2764 //If the subpanel is a datasource function, it can't be a collection so we just poll that function for the and return that
2765 foreach($subpanel_list as $this_subpanel)
2767 if($this_subpanel->isDatasourceFunction() && empty($this_subpanel->_instance_properties['generate_select']))
2769 $shortcut_function_name = $this_subpanel->get_data_source_name();
2770 $parameters=$this_subpanel->get_function_parameters();
2771 if (!empty($parameters))
2773 //if the import file function is set, then import the file to call the custom function from
2774 if (is_array($parameters) && isset($parameters['import_function_file'])){
2775 //this call may happen multiple times, so only require if function does not exist
2776 if(!function_exists($shortcut_function_name)){
2777 require_once($parameters['import_function_file']);
2779 //call function from required file
2780 $tmp_final_query = $shortcut_function_name($parameters);
2782 //call function from parent bean
2783 $tmp_final_query = $parentbean->$shortcut_function_name($parameters);
2786 $tmp_final_query = $parentbean->$shortcut_function_name();
2790 $final_query_rows .= ' UNION ALL ( '.$parentbean->create_list_count_query($tmp_final_query, $parameters) . ' )';
2791 $final_query .= ' UNION ALL ( '.$tmp_final_query . ' )';
2793 $final_query_rows = '(' . $parentbean->create_list_count_query($tmp_final_query, $parameters) . ')';
2794 $final_query = '(' . $tmp_final_query . ')';
2799 //If final_query is still empty, its time to build the sub-queries
2800 if (empty($final_query))
2802 $subqueries = SugarBean::build_sub_queries_for_union($subpanel_list, $subpanel_def, $parentbean, $order_by);
2803 $all_fields = array();
2804 foreach($subqueries as $i => $subquery)
2806 $query_fields = $GLOBALS['db']->helper->getSelectFieldsFromQuery($subquery['select']);
2807 foreach($query_fields as $field => $select)
2809 if (!in_array($field, $all_fields))
2810 $all_fields[] = $field;
2812 $subqueries[$i]['query_fields'] = $query_fields;
2815 //Now ensure the queries have the same set of fields in the same order.
2816 foreach($subqueries as $subquery)
2818 $subquery['select'] = "SELECT";
2819 foreach($all_fields as $field)
2821 if (!isset($subquery['query_fields'][$field]))
2823 $subquery['select'] .= " ' ' $field,";
2827 $subquery['select'] .= " {$subquery['query_fields'][$field]},";
2830 $subquery['select'] = substr($subquery['select'], 0 , strlen($subquery['select']) - 1);
2831 //Put the query into the final_query
2832 $query = $subquery['select'] . " " . $subquery['from'] . " " . $subquery['where'];
2835 $query = ' UNION ALL ( '.$query . ' )';
2836 $final_query_rows .= " UNION ALL ";
2838 $query = '(' . $query . ')';
2841 $query_array = $subquery['query_array'];
2842 $select_position=strpos($query_array['select'],"SELECT");
2843 $distinct_position=strpos($query_array['select'],"DISTINCT");
2844 if ($select_position !== false && $distinct_position!= false)
2846 $query_rows = "( ".substr_replace($query_array['select'],"SELECT count(",$select_position,6). ")" . $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2850 //resort to default behavior.
2851 $query_rows = "( SELECT count(*)". $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2853 if(!empty($subquery['secondary_select']))
2856 $subquerystring= $subquery['secondary_select'] . $subquery['secondary_from'].$query_array['join']. $subquery['where'];
2857 if (!empty($subquery['secondary_where']))
2859 if (empty($subquery['where']))
2861 $subquerystring.=" WHERE " .$subquery['secondary_where'];
2865 $subquerystring.=" AND " .$subquery['secondary_where'];
2868 $secondary_queries[]=$subquerystring;
2870 $final_query .= $query;
2871 $final_query_rows .= $query_rows;
2875 if(!empty($order_by))
2878 if(!$subpanel_def->isCollection())
2880 $submodulename = $subpanel_def->_instance_properties['module'];
2881 $submoduleclass = $beanList[$submodulename];
2882 $submodule = new $submoduleclass();
2884 if(!empty($submodule) && !empty($submodule->table_name))
2886 $final_query .= " ORDER BY " .$parentbean->process_order_by($order_by, $submodule);
2891 $final_query .= " ORDER BY ". $order_by . ' ';
2893 if(!empty($sort_order))
2895 $final_query .= ' ' .$sort_order;
2900 if(isset($layout_edit_mode) && $layout_edit_mode)
2902 $response = array();
2903 if(!empty($submodule))
2905 $submodule->assign_display_fields($submodule->module_dir);
2906 $response['list'] = array($submodule);
2910 $response['list'] = array();
2912 $response['parent_data'] = array();
2913 $response['row_count'] = 1;
2914 $response['next_offset'] = 0;
2915 $response['previous_offset'] = 0;
2920 return $parentbean->process_union_list_query($parentbean, $final_query, $row_offset, $limit, $max, '',$subpanel_def, $final_query_rows, $secondary_queries);
2925 * Returns a full (ie non-paged) list of the current object type.
2927 * @param string $order_by the order by SQL parameter. defaults to ""
2928 * @param string $where where clause. defaults to ""
2929 * @param boolean $check_dates. defaults to false
2930 * @param int $show_deleted show deleted records. defaults to 0
2932 function get_full_list($order_by = "", $where = "", $check_dates=false, $show_deleted = 0)
2934 $GLOBALS['log']->debug("get_full_list: order_by = '$order_by' and where = '$where'");
2935 if(isset($_SESSION['show_deleted']))
2939 $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted);
2940 return $this->process_full_list_query($query, $check_dates);
2944 * Return the list query used by the list views and export button. Next generation of create_new_list_query function.
2946 * Override this function to return a custom query.
2948 * @param string $order_by custom order by clause
2949 * @param string $where custom where clause
2950 * @param array $filter Optioanal
2951 * @param array $params Optional *
2952 * @param int $show_deleted Optional, default 0, show deleted records is set to 1.
2953 * @param string $join_type
2954 * @param boolean $return_array Optional, default false, response as array
2955 * @param object $parentbean creating a subquery for this bean.
2956 * @param boolean $singleSelect Optional, default false.
2957 * @return String select query string, optionally an array value will be returned if $return_array= true.
2959 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)
2961 global $beanFiles, $beanList;
2962 $selectedFields = array();
2963 $secondarySelectedFields = array();
2964 $ret_array = array();
2966 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2968 global $current_user;
2969 $owner_where = $this->getOwnerWhere($current_user->id);
2972 $where = $owner_where;
2976 $where .= ' AND '. $owner_where;
2979 if(!empty($params['distinct']))
2981 $distinct = ' DISTINCT ';
2985 $ret_array['select'] = " SELECT $distinct $this->table_name.* ";
2989 $ret_array['select'] = " SELECT $distinct $this->table_name.id ";
2991 $ret_array['from'] = " FROM $this->table_name ";
2992 $ret_array['from_min'] = $ret_array['from'];
2993 $ret_array['secondary_from'] = $ret_array['from'] ;
2994 $ret_array['where'] = '';
2995 $ret_array['order_by'] = '';
2996 //secondary selects are selects that need to be run after the primarty query to retrieve additional info on main
2999 $ret_array['secondary_select']=& $ret_array['select'];
3000 $ret_array['secondary_from'] = & $ret_array['from'];
3004 $ret_array['secondary_select'] = '';
3006 $custom_join = false;
3007 if((!isset($params['include_custom_fields']) || $params['include_custom_fields']) && isset($this->custom_fields))
3010 $custom_join = $this->custom_fields->getJOIN( empty($filter)? true: $filter );
3013 $ret_array['select'] .= ' ' .$custom_join['select'];
3018 $ret_array['from'] .= ' ' . $custom_join['join'];
3021 //LOOP AROUND FOR FIXIN VARDEF ISSUES
3022 require('include/VarDefHandler/listvardefoverride.php');
3023 $joined_tables = array();
3024 if(isset($params['joined_tables']))
3026 foreach($params['joined_tables'] as $table)
3028 $joined_tables[$table] = 1;
3034 $filterKeys = array_keys($filter);
3035 if(is_numeric($filterKeys[0]))
3038 foreach($filter as $field)
3040 $field = strtolower($field);
3041 //remove out id field so we don't duplicate it
3042 if ( $field == 'id' && !empty($filter) ) {
3045 if(isset($this->field_defs[$field]))
3047 $fields[$field]= $this->field_defs[$field];
3051 $fields[$field] = array('force_exists'=>true);
3060 $fields = $this->field_defs;
3063 $used_join_key = array();
3065 foreach($fields as $field=>$value)
3067 //alias is used to alias field names
3069 if (isset($value['alias']))
3071 $alias =' as ' . $value['alias'] . ' ';
3074 if(empty($this->field_defs[$field]) || !empty($value['force_blank']) )
3076 if(!empty($filter) && isset($filter[$field]['force_exists']) && $filter[$field]['force_exists'])
3078 if ( isset($filter[$field]['force_default']) )
3079 $ret_array['select'] .= ", {$filter[$field]['force_default']} $field ";
3081 //spaces are a fix for length issue problem with unions. The union only returns the maximum number of characters from the first select statemtn.
3082 $ret_array['select'] .= ", ' ' $field ";
3088 $data = $this->field_defs[$field];
3091 //ignore fields that are a part of the collection and a field has been removed as a result of
3092 //layout customization.. this happens in subpanel customizations, use case, from the contacts subpanel
3093 //in opportunities module remove the contact_role/opportunity_role field.
3094 $process_field=true;
3095 if (isset($data['relationship_fields']) and !empty($data['relationship_fields']))
3097 foreach ($data['relationship_fields'] as $field_name)
3099 if (!isset($fields[$field_name]))
3101 $process_field=false;
3105 if (!$process_field)
3110 if( (!isset($data['source']) || $data['source'] == 'db') && (!empty($alias) || !empty($filter) ))
3112 $ret_array['select'] .= ", $this->table_name.$field $alias";
3113 $selectedFields["$this->table_name.$field"] = true;
3118 if($data['type'] != 'relate' && isset($data['db_concat_fields']))
3120 $ret_array['select'] .= ", " . db_concat($this->table_name, $data['db_concat_fields']) . " as $field";
3121 $selectedFields[db_concat($this->table_name, $data['db_concat_fields'])] = true;
3123 //Custom relate field or relate fields built in module builder which have no link field associated.
3124 if ($data['type'] == 'relate' && (isset($data['custom_module']) || isset($data['ext2']))) {
3125 $joinTableAlias = 'jt' . $jtcount;
3126 $relateJoinInfo = $this->custom_fields->getRelateJoin($data, $joinTableAlias);
3127 $ret_array['select'] .= $relateJoinInfo['select'];
3128 $ret_array['from'] .= $relateJoinInfo['from'];
3129 //Replace any references to the relationship in the where clause with the new alias
3130 //If the link isn't set, assume that search used the local table for the field
3131 $searchTable = isset($data['link']) ? $relateJoinInfo['rel_table'] : $this->table_name;
3132 $field_name = $relateJoinInfo['rel_table'] . '.' . !empty($data['name'])?$data['name']:'name';
3133 $where = preg_replace('/(^|[\s(])' . $field_name . '/' , '${1}' . $relateJoinInfo['name_field'], $where);
3137 if ($data['type'] == 'parent') {
3138 //See if we need to join anything by inspecting the where clause
3139 $match = preg_match('/(^|[\s(])parent_(\w+)_(\w+)\.name/', $where, $matches);
3141 $joinTableAlias = 'jt' . $jtcount;
3142 $joinModule = $matches[2];
3143 $joinTable = $matches[3];
3144 $localTable = $this->table_name;
3145 if (!empty($data['custom_module'])) {
3146 $localTable .= '_cstm';
3148 global $beanFiles, $beanList, $module;
3149 require_once($beanFiles[$beanList[$joinModule]]);
3150 $rel_mod = new $beanList[$joinModule]();
3151 $nameField = "$joinTableAlias.name";
3152 if (isset($rel_mod->field_defs['name']))
3154 $name_field_def = $rel_mod->field_defs['name'];
3155 if(isset($name_field_def['db_concat_fields']))
3157 $nameField = db_concat($joinTableAlias, $name_field_def['db_concat_fields']);
3160 $ret_array['select'] .= ", $nameField {$data['name']} ";
3161 $ret_array['from'] .= " LEFT JOIN $joinTable $joinTableAlias
3162 ON $localTable.{$data['id_name']} = $joinTableAlias.id";
3163 //Replace any references to the relationship in the where clause with the new alias
3164 $where = preg_replace('/(^|[\s(])parent_' . $joinModule . '_' . $joinTable . '\.name/', '${1}' . $nameField, $where);
3168 if($data['type'] == 'relate' && isset($data['link']))
3170 $this->load_relationship($data['link']);
3171 if(!empty($this->$data['link']))
3174 if(empty($join_type))
3176 $params['join_type'] = ' LEFT JOIN ';
3180 $params['join_type'] = $join_type;
3182 if(isset($data['join_name']))
3184 $params['join_table_alias'] = $data['join_name'];
3188 $params['join_table_alias'] = 'jt' . $jtcount;
3191 if(isset($data['join_link_name']))
3193 $params['join_table_link_alias'] = $data['join_link_name'];
3197 $params['join_table_link_alias'] = 'jtl' . $jtcount;
3199 $join_primary = !isset($data['join_primary']) || $data['join_primary'];
3201 $join = $this->$data['link']->getJoin($params, true);
3202 $used_join_key[] = $join['rel_key'];
3203 $rel_module = $this->$data['link']->getRelatedModuleName();
3204 $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');
3206 //if rnanme is set to 'name', and bean files exist, then check if field should be a concatenated name
3207 global $beanFiles, $beanList;
3208 if($data['rname'] && !empty($beanFiles[$beanList[$rel_module]])) {
3210 //create an instance of the related bean
3211 require_once($beanFiles[$beanList[$rel_module]]);
3212 $rel_mod = new $beanList[$rel_module]();
3213 //if bean has first and last name fields, then name should be concatenated
3214 if(isset($rel_mod->field_name_map['first_name']) && isset($rel_mod->field_name_map['last_name'])){
3215 $data['db_concat_fields'] = array(0=>'first_name', 1=>'last_name');
3220 if($join['type'] == 'many-to-many')
3222 if(empty($ret_array['secondary_select']))
3224 $ret_array['secondary_select'] = " SELECT $this->table_name.id ref_id ";
3226 if(!empty($beanFiles[$beanList[$rel_module]]) && $join_primary)
3228 require_once($beanFiles[$beanList[$rel_module]]);
3229 $rel_mod = new $beanList[$rel_module]();
3230 if(isset($rel_mod->field_defs['assigned_user_id']))
3232 $ret_array['secondary_select'].= " , ". $params['join_table_alias'] . ".assigned_user_id {$field}_owner, '$rel_module' {$field}_mod";
3237 if(isset($rel_mod->field_defs['created_by']))
3239 $ret_array['secondary_select'].= " , ". $params['join_table_alias'] . ".created_by {$field}_owner , '$rel_module' {$field}_mod";
3250 if(isset($data['db_concat_fields']))
3252 $ret_array['secondary_select'] .= ' , ' . db_concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
3256 if(!isset($data['relationship_fields']))
3258 $ret_array['secondary_select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
3263 $ret_array['select'] .= ", ' ' $field ";
3264 $ret_array['select'] .= ", ' ' " . $join['rel_key'] . ' ';
3267 if($this->db->dbType != 'mysql') {//bug 26801, these codes are just used to duplicate rel_key in the select sql, or it will throw error in MSSQL and Oracle.
3268 foreach($used_join_key as $used_key) {
3269 if($used_key == $join['rel_key']) $count_used++;
3272 if($count_used <= 1) {//27416, the $ret_array['secondary_select'] should always generate, regardless the dbtype
3273 $ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'].'.'. $join['rel_key'] .' ' . $join['rel_key'];
3275 if(isset($data['relationship_fields']))
3277 foreach($data['relationship_fields'] as $r_name=>$alias_name)
3279 if(!empty( $secondarySelectedFields[$alias_name]))continue;
3280 $ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'].'.'. $r_name .' ' . $alias_name;
3281 $secondarySelectedFields[$alias_name] = true;
3286 $ret_array['secondary_from'] .= ' ' . $join['join']. ' AND ' . $params['join_table_alias'].'.deleted=0';
3287 if (isset($data['link_type']) && $data['link_type'] == 'relationship_info' && ($parentbean instanceOf SugarBean))
3289 $ret_array['secondary_where'] = $params['join_table_link_alias'] . '.' . $join['rel_key']. "='" .$parentbean->id . "'";
3295 if(isset($data['db_concat_fields']))
3297 $ret_array['select'] .= ' , ' . db_concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
3301 $ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
3303 if(isset($data['additionalFields'])){
3304 foreach($data['additionalFields'] as $k=>$v){
3305 $ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $k . ' ' . $v;
3310 $ret_array['from'] .= ' ' . $join['join']. ' AND ' . $params['join_table_alias'].'.deleted=0';
3311 if(!empty($beanList[$rel_module]) && !empty($beanFiles[$beanList[$rel_module]]))
3313 require_once($beanFiles[$beanList[$rel_module]]);
3314 $rel_mod = new $beanList[$rel_module]();
3315 if(isset($value['target_record_key']) && !empty($filter))
3317 $selectedFields[$this->table_name.'.'.$value['target_record_key']] = true;
3318 $ret_array['select'] .= " , $this->table_name.{$value['target_record_key']} ";
3320 if(isset($rel_mod->field_defs['assigned_user_id']))
3322 $ret_array['select'] .= ' , ' .$params['join_table_alias'] . '.assigned_user_id ' . $field . '_owner';
3326 $ret_array['select'] .= ' , ' .$params['join_table_alias'] . '.created_by ' . $field . '_owner';
3328 $ret_array['select'] .= " , '".$rel_module ."' " . $field . '_mod';
3333 // To fix SOAP stuff where we are trying to retrieve all the accounts data where accounts.id = ..
3334 // and this code changes accounts to jt4 as there is a self join with the accounts table.
3336 if(isset($data['db_concat_fields'])){
3337 $buildWhere = false;
3338 if(in_array('first_name', $data['db_concat_fields']) && in_array('last_name', $data['db_concat_fields']))
3340 $exp = '/\(\s*?'.$data['name'].'.*?\%\'\s*?\)/';
3341 if(preg_match($exp, $where, $matches))
3343 $search_expression = $matches[0];
3344 //Create three search conditions - first + last, first, last
3345 $first_name_search = str_replace($data['name'], $params['join_table_alias'] . '.first_name', $search_expression);
3346 $last_name_search = str_replace($data['name'], $params['join_table_alias'] . '.last_name', $search_expression);
3347 $full_name_search = str_replace($data['name'], db_concat($params['join_table_alias'], $data['db_concat_fields']), $search_expression);
3349 $where = str_replace($search_expression, '(' . $full_name_search . ' OR ' . $first_name_search . ' OR ' . $last_name_search . ')', $where);
3355 $db_field = db_concat($params['join_table_alias'], $data['db_concat_fields']);
3356 $where = preg_replace('/'.$data['name'].'/', $db_field, $where);
3359 $where = preg_replace('/(^|[\s(])' . $data['name'] . '/', '${1}' . $params['join_table_alias'] . '.'.$data['rname'], $where);
3363 $joined_tables[$params['join_table_alias']]=1;
3364 $joined_tables[$params['join_table_link_alias']]=1;
3373 if(isset($this->field_defs['assigned_user_id']) && empty($selectedFields[$this->table_name.'.assigned_user_id']))
3375 $ret_array['select'] .= ", $this->table_name.assigned_user_id ";
3377 else if(isset($this->field_defs['created_by']) && empty($selectedFields[$this->table_name.'.created_by']))
3379 $ret_array['select'] .= ", $this->table_name.created_by ";
3381 if(isset($this->field_defs['system_id']) && empty($selectedFields[$this->table_name.'.system_id']))
3383 $ret_array['select'] .= ", $this->table_name.system_id ";
3388 if ($ifListForExport) {
3389 if(isset($this->field_defs['email1'])) {
3390 $ret_array['select'].= " ,email_addresses.email_address email1";
3391 $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 ";
3395 $where_auto = '1=1';
3396 if($show_deleted == 0)
3398 $where_auto = "$this->table_name.deleted=0";
3399 }else if($show_deleted == 1)
3401 $where_auto = "$this->table_name.deleted=1";
3404 $ret_array['where'] = " where ($where) AND $where_auto";
3406 $ret_array['where'] = " where $where_auto";
3407 if(!empty($order_by))
3409 //make call to process the order by clause
3410 $ret_array['order_by'] = " ORDER BY ". $this->process_order_by($order_by, null);
3414 unset($ret_array['secondary_where']);
3415 unset($ret_array['secondary_from']);
3416 unset($ret_array['secondary_select']);
3424 return $ret_array['select'] . $ret_array['from'] . $ret_array['where']. $ret_array['order_by'];
3427 * Returns parent record data for objects that store relationship information
3429 * @param array $type_info
3431 * Interal function, do not override.
3433 function retrieve_parent_fields($type_info)
3436 global $beanList, $beanFiles;
3437 $templates = array();
3438 $parent_child_map = array();
3439 foreach($type_info as $children_info)
3441 foreach($children_info as $child_info)
3443 if($child_info['type'] == 'parent')
3445 if(empty($templates[$child_info['parent_type']]))
3447 //Test emails will have an invalid parent_type, don't try to load the non-existant parent bean
3448 if ($child_info['parent_type'] == 'test') {
3451 $class = $beanList[$child_info['parent_type']];
3452 // Added to avoid error below; just silently fail and write message to log
3453 if ( empty($beanFiles[$class]) ) {
3454 $GLOBALS['log']->error($this->object_name.'::retrieve_parent_fields() - cannot load class "'.$class.'", skip loading.');
3457 require_once($beanFiles[$class]);
3458 $templates[$child_info['parent_type']] = new $class();
3461 if(empty($queries[$child_info['parent_type']]))
3463 $queries[$child_info['parent_type']] = "SELECT id ";
3464 $field_def = $templates[$child_info['parent_type']]->field_defs['name'];
3465 if(isset($field_def['db_concat_fields']))
3467 $queries[$child_info['parent_type']] .= ' , ' . db_concat($templates[$child_info['parent_type']]->table_name, $field_def['db_concat_fields']) . ' parent_name';
3471 $queries[$child_info['parent_type']] .= ' , name parent_name';
3473 if(isset($templates[$child_info['parent_type']]->field_defs['assigned_user_id']))
3475 $queries[$child_info['parent_type']] .= ", assigned_user_id parent_name_owner , '{$child_info['parent_type']}' parent_name_mod";;
3476 }else if(isset($templates[$child_info['parent_type']]->field_defs['created_by']))
3478 $queries[$child_info['parent_type']] .= ", created_by parent_name_owner, '{$child_info['parent_type']}' parent_name_mod";
3480 $queries[$child_info['parent_type']] .= " FROM " . $templates[$child_info['parent_type']]->table_name ." WHERE id IN ('{$child_info['parent_id']}'";
3484 if(empty($parent_child_map[$child_info['parent_id']]))
3485 $queries[$child_info['parent_type']] .= " ,'{$child_info['parent_id']}'";
3487 $parent_child_map[$child_info['parent_id']][] = $child_info['child_id'];
3492 foreach($queries as $query)
3494 $result = $this->db->query($query . ')');
3495 while($row = $this->db->fetchByAssoc($result))
3497 $results[$row['id']] = $row;
3501 $child_results = array();
3502 foreach($parent_child_map as $parent_key=>$parent_child)
3504 foreach($parent_child as $child)
3506 if(isset( $results[$parent_key]))
3508 $child_results[$child] = $results[$parent_key];
3512 return $child_results;
3516 * Processes the list query and return fetched row.
3518 * Internal function, do not override.
3519 * @param string $query select query to be processed.
3520 * @param int $row_offset starting position
3521 * @param int $limit Optioanl, default -1
3522 * @param int $max_per_page Optional, default -1
3523 * @param string $where Optional, additional filter criteria.
3524 * @return array Fetched data
3526 function process_list_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '')
3528 global $sugar_config;
3529 $db = &DBManagerFactory::getInstance('listviews');
3531 * if the row_offset is set to 'end' go to the end of the list
3533 $toEnd = strval($row_offset) == 'end';
3534 $GLOBALS['log']->debug("process_list_query: ".$query);
3535 if($max_per_page == -1)
3537 $max_per_page = $sugar_config['list_max_entries_per_page'];
3539 // Check to see if we have a count query available.
3540 if(empty($sugar_config['disable_count_query']) || $toEnd)
3542 $count_query = $this->create_list_count_query($query);
3543 if(!empty($count_query) && (empty($limit) || $limit == -1))
3545 // We have a count query. Run it and get the results.
3546 $result = $db->query($count_query, true, "Error running count query for $this->object_name List: ");
3547 $assoc = $db->fetchByAssoc($result);
3548 if(!empty($assoc['c']))
3550 $rows_found = $assoc['c'];
3551 $limit = $sugar_config['list_max_entries_per_page'];
3555 $row_offset = (floor(($rows_found -1) / $limit)) * $limit;
3561 if((empty($limit) || $limit == -1))
3563 $limit = $max_per_page + 1;
3564 $max_per_page = $limit;
3569 if(empty($row_offset))
3573 if(!empty($limit) && $limit != -1 && $limit != -99)
3575 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $this->object_name list: ");
3579 $result = $db->query($query,true,"Error retrieving $this->object_name list: ");
3584 if(empty($rows_found))
3586 $rows_found = $db->getRowCount($result);
3589 $GLOBALS['log']->debug("Found $rows_found ".$this->object_name."s");
3591 $previous_offset = $row_offset - $max_per_page;
3592 $next_offset = $row_offset + $max_per_page;
3594 $class = get_class($this);
3595 if($rows_found != 0 or $db->dbType != 'mysql')
3597 //todo Bug? we should remove the magic number -99
3598 //use -99 to return all
3599 $index = $row_offset;
3600 while ($max_per_page == -99 || ($index < $row_offset + $max_per_page))
3603 if(!empty($sugar_config['disable_count_query']))
3605 $row = $db->fetchByAssoc($result);
3609 $row = $db->fetchByAssoc($result, $index);
3616 //instantiate a new class each time. This is because php5 passes
3617 //by reference by default so if we continually update $this, we will
3618 //at the end have a list of all the same objects
3619 $temp = new $class();
3621 foreach($this->field_defs as $field=>$value)
3623 if (isset($row[$field]))
3625 $temp->$field = $row[$field];
3626 $owner_field = $field . '_owner';
3627 if(isset($row[$owner_field]))
3629 $temp->$owner_field = $row[$owner_field];
3632 $GLOBALS['log']->debug("$temp->object_name({$row['id']}): ".$field." = ".$temp->$field);
3633 }else if (isset($row[$this->table_name .'.'.$field]))
3635 $temp->$field = $row[$this->table_name .'.'.$field];
3643 $temp->check_date_relationships_load();
3644 $temp->fill_in_additional_list_fields();
3645 if($temp->hasCustomFields()) $temp->custom_fields->fill_relationships();
3646 $temp->call_custom_logic("process_record");
3653 if(!empty($sugar_config['disable_count_query']) && !empty($limit))
3656 $rows_found = $row_offset + count($list);
3658 unset($list[$limit - 1]);
3665 $response = Array();
3666 $response['list'] = $list;
3667 $response['row_count'] = $rows_found;
3668 $response['next_offset'] = $next_offset;
3669 $response['previous_offset'] = $previous_offset;
3670 $response['current_offset'] = $row_offset ;
3675 * Returns the number of rows that the given SQL query should produce
3677 * Internal function, do not override.
3678 * @param string $query valid select query
3679 * @param boolean $is_count_query Optional, Default false, set to true if passed query is a count query.
3680 * @return int count of rows found
3682 function _get_num_rows_in_query($query, $is_count_query=false)
3684 $num_rows_in_query = 0;
3685 if (!$is_count_query)
3687 $count_query = SugarBean::create_list_count_query($query);
3689 $count_query=$query;
3691 $result = $this->db->query($count_query, true, "Error running count query for $this->object_name List: ");
3693 $row = $this->db->fetchByAssoc($result, $row_num);
3696 $num_rows_in_query += current($row);
3698 $row = $this->db->fetchByAssoc($result, $row_num);
3701 return $num_rows_in_query;
3705 * Applies pagination window to union queries used by list view and subpanels,
3706 * executes the query and returns fetched data.
3708 * Internal function, do not override.
3709 * @param object $parent_bean
3710 * @param string $query query to be processed.
3711 * @param int $row_offset
3712 * @param int $limit optional, default -1
3713 * @param int $max_per_page Optional, default -1
3714 * @param string $where Custom where clause.
3715 * @param array $subpanel_def definition of sub-panel to be processed
3716 * @param string $query_row_count
3717 * @param array $seconday_queries
3718 * @return array Fetched data.
3720 function process_union_list_query($parent_bean, $query,
3721 $row_offset, $limit= -1, $max_per_page = -1, $where = '', $subpanel_def, $query_row_count='', $secondary_queries = array())
3724 $db = &DBManagerFactory::getInstance('listviews');
3726 * if the row_offset is set to 'end' go to the end of the list
3728 $toEnd = strval($row_offset) == 'end';
3729 global $sugar_config;
3730 $use_count_query=false;
3731 $processing_collection=$subpanel_def->isCollection();
3733 $GLOBALS['log']->debug("process_list_query: ".$query);
3734 if($max_per_page == -1)
3736 $max_per_page = $sugar_config['list_max_entries_per_subpanel'];
3738 if(empty($query_row_count))
3740 $query_row_count = $query;
3742 $distinct_position=strpos($query_row_count,"DISTINCT");
3744 if ($distinct_position!= false)
3746 $use_count_query=true;
3748 $performSecondQuery = true;
3749 if(empty($sugar_config['disable_count_query']) || $toEnd)
3751 $rows_found = $this->_get_num_rows_in_query($query_row_count,$use_count_query);
3754 $performSecondQuery = false;
3756 if(!empty($rows_found) && (empty($limit) || $limit == -1))
3758 $limit = $sugar_config['list_max_entries_per_subpanel'];
3762 $row_offset = (floor(($rows_found -1) / $limit)) * $limit;
3768 if((empty($limit) || $limit == -1))
3770 $limit = $max_per_page + 1;
3771 $max_per_page = $limit;
3775 if(empty($row_offset))
3780 $previous_offset = $row_offset - $max_per_page;
3781 $next_offset = $row_offset + $max_per_page;
3783 if($performSecondQuery)
3785 if(!empty($limit) && $limit != -1 && $limit != -99)
3787 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $parent_bean->object_name list: ");
3791 $result = $db->query($query,true,"Error retrieving $this->object_name list: ");
3793 if(empty($rows_found))
3795 $rows_found = $db->getRowCount($result);
3798 $GLOBALS['log']->debug("Found $rows_found ".$parent_bean->object_name."s");
3799 if($rows_found != 0 or $db->dbType != 'mysql')
3801 //use -99 to return all
3803 // get the current row
3804 $index = $row_offset;
3805 if(!empty($sugar_config['disable_count_query']))
3807 $row = $db->fetchByAssoc($result);
3811 $row = $db->fetchByAssoc($result, $index);
3814 $post_retrieve = array();
3815 $isFirstTime = true;
3818 $function_fields = array();
3819 if(($index < $row_offset + $max_per_page || $max_per_page == -99) or ($db->dbType != 'mysql'))
3821 if ($processing_collection)
3823 $current_bean =$subpanel_def->sub_subpanels[$row['panel_name']]->template_instance;
3826 $class = get_class($subpanel_def->sub_subpanels[$row['panel_name']]->template_instance);
3827 $current_bean = new $class();
3830 $current_bean=$subpanel_def->template_instance;
3833 $class = get_class($subpanel_def->template_instance);
3834 $current_bean = new $class();
3837 $isFirstTime = false;
3838 //set the panel name in the bean instance.
3839 if (isset($row['panel_name']))
3841 $current_bean->panel_name=$row['panel_name'];
3843 foreach($current_bean->field_defs as $field=>$value)
3846 if (isset($row[$field]))
3848 $current_bean->$field = $row[$field];
3849 unset($row[$field]);
3851 else if (isset($row[$this->table_name .'.'.$field]))
3853 $current_bean->$field = $row[$current_bean->table_name .'.'.$field];
3854 unset($row[$current_bean->table_name .'.'.$field]);
3858 $current_bean->$field = "";
3859 unset($row[$field]);
3861 if(isset($value['source']) && $value['source'] == 'function')
3863 $function_fields[]=$field;
3866 foreach($row as $key=>$value)
3868 $current_bean->$key = $value;
3870 foreach($function_fields as $function_field)
3872 $value = $current_bean->field_defs[$function_field];
3873 $can_execute = true;
3874 $execute_params = array();
3875 $execute_function = array();
3876 if(!empty($value['function_class']))
3878 $execute_function[] = $value['function_class'];
3879 $execute_function[] = $value['function_name'];
3883 $execute_function = $value['function_name'];
3885 foreach($value['function_params'] as $param )
3887 if (empty($value['function_params_source']) or $value['function_params_source']=='parent')
3889 if(empty($this->$param))
3891 $can_execute = false;
3895 $execute_params[] = $this->$param;
3897 } else if ($value['function_params_source']=='this')
3899 if(empty($current_bean->$param))
3901 $can_execute = false;
3905 $execute_params[] = $current_bean->$param;
3910 $can_execute = false;
3916 if(!empty($value['function_require']))
3918 require_once($value['function_require']);
3920 $current_bean->$function_field = call_user_func_array($execute_function, $execute_params);
3923 if(!empty($current_bean->parent_type) && !empty($current_bean->parent_id))
3925 if(!isset($post_retrieve[$current_bean->parent_type]))
3927 $post_retrieve[$current_bean->parent_type] = array();
3929 $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');
3931 //$current_bean->fill_in_additional_list_fields();
3932 $list[$current_bean->id] = $current_bean;
3934 // go to the next row
3936 $row = $db->fetchByAssoc($result, $index);
3939 //now handle retrieving many-to-many relationships
3942 foreach($secondary_queries as $query2)
3944 $result2 = $db->query($query2);
3946 $row2 = $db->fetchByAssoc($result2);
3949 $id_ref = $row2['ref_id'];
3951 if(isset($list[$id_ref]))
3953 foreach($row2 as $r2key=>$r2value)
3955 if($r2key != 'ref_id')
3957 $list[$id_ref]->$r2key = $r2value;
3961 $row2 = $db->fetchByAssoc($result2);
3967 if(isset($post_retrieve))
3969 $parent_fields = $this->retrieve_parent_fields($post_retrieve);
3973 $parent_fields = array();
3975 if(!empty($sugar_config['disable_count_query']) && !empty($limit))
3978 //C.L. Bug 43535 - Use the $index value to set the $rows_found value here
3979 $rows_found = isset($index) ? $index : $row_offset + count($list);
3981 if(count($list) >= $limit)
3995 $parent_fields = array();
3997 $response = array();
3998 $response['list'] = $list;
3999 $response['parent_data'] = $parent_fields;
4000 $response['row_count'] = $rows_found;
4001 $response['next_offset'] = $next_offset;
4002 $response['previous_offset'] = $previous_offset;
4003 $response['current_offset'] = $row_offset ;
4004 $response['query'] = $query;
4010 * Applies pagination window to select queries used by detail view,
4011 * executes the query and returns fetched data.
4013 * Internal function, do not override.
4014 * @param string $query query to be processed.
4015 * @param int $row_offset
4016 * @param int $limit optional, default -1
4017 * @param int $max_per_page Optional, default -1
4018 * @param string $where Custom where clause.
4019 * @param int $offset Optional, default 0
4020 * @return array Fetched data.
4023 function process_detail_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '', $offset = 0)
4025 global $sugar_config;
4026 $GLOBALS['log']->debug("process_list_query: ".$query);
4027 if($max_per_page == -1)
4029 $max_per_page = $sugar_config['list_max_entries_per_page'];
4032 // Check to see if we have a count query available.
4033 $count_query = $this->create_list_count_query($query);
4035 if(!empty($count_query) && (empty($limit) || $limit == -1))
4037 // We have a count query. Run it and get the results.
4038 $result = $this->db->query($count_query, true, "Error running count query for $this->object_name List: ");
4039 $assoc = $this->db->fetchByAssoc($result);
4040 if(!empty($assoc['c']))
4042 $total_rows = $assoc['c'];
4046 if(empty($row_offset))
4051 $result = $this->db->limitQuery($query, $offset, 1, true,"Error retrieving $this->object_name list: ");
4053 $rows_found = $this->db->getRowCount($result);
4055 $GLOBALS['log']->debug("Found $rows_found ".$this->object_name."s");
4057 $previous_offset = $row_offset - $max_per_page;
4058 $next_offset = $row_offset + $max_per_page;
4060 if($rows_found != 0 or $this->db->dbType != 'mysql')
4063 $row = $this->db->fetchByAssoc($result, $index);
4064 $this->retrieve($row['id']);
4067 $response = Array();
4068 $response['bean'] = $this;
4069 if (empty($total_rows))
4071 $response['row_count'] = $total_rows;
4072 $response['next_offset'] = $next_offset;
4073 $response['previous_offset'] = $previous_offset;
4079 * Processes fetched list view data
4081 * Internal function, do not override.
4082 * @param string $query query to be processed.
4083 * @param boolean $check_date Optional, default false. if set to true date time values are processed.
4084 * @return array Fetched data.
4087 function process_full_list_query($query, $check_date=false)
4090 $GLOBALS['log']->debug("process_full_list_query: query is ".$query);
4091 $result = $this->db->query($query, false);
4092 $GLOBALS['log']->debug("process_full_list_query: result is ".print_r($result,true));
4093 $class = get_class($this);
4094 $isFirstTime = true;
4095 $bean = new $class();
4097 //if($this->db->getRowCount($result) > 0){
4100 // We have some data.
4101 //while ($row = $this->db->fetchByAssoc($result)) {
4102 while (($row = $bean->db->fetchByAssoc($result)) != null)
4106 $bean = new $class();
4108 $isFirstTime = false;
4110 foreach($bean->field_defs as $field=>$value)
4112 if (isset($row[$field]))
4114 $bean->$field = $row[$field];
4115 $GLOBALS['log']->debug("process_full_list: $bean->object_name({$row['id']}): ".$field." = ".$bean->$field);
4124 $bean->processed_dates_times = array();
4125 $bean->check_date_relationships_load();
4127 $bean->fill_in_additional_list_fields();
4128 $bean->call_custom_logic("process_record");
4129 $bean->fetched_row = $row;
4134 if (isset($list)) return $list;
4139 * Tracks the viewing of a detail record.
4140 * This leverages get_summary_text() which is object specific.
4142 * Internal function, do not override.
4143 * @param string $user_id - String value of the user that is viewing the record.
4144 * @param string $current_module - String value of the module being processed.
4145 * @param string $current_view - String value of the current view
4147 function track_view($user_id, $current_module, $current_view='')
4149 $trackerManager = TrackerManager::getInstance();
4150 if($monitor = $trackerManager->getMonitor('tracker')){
4151 $monitor->setValue('date_modified', $GLOBALS['timedate']->nowDb());
4152 $monitor->setValue('user_id', $user_id);
4153 $monitor->setValue('module_name', $current_module);
4154 $monitor->setValue('action', $current_view);
4155 $monitor->setValue('item_id', $this->id);
4156 $monitor->setValue('item_summary', $this->get_summary_text());
4157 $monitor->setValue('visible', $this->tracker_visibility);
4158 $trackerManager->saveMonitor($monitor);
4163 * Returns the summary text that should show up in the recent history list for this object.
4167 public function get_summary_text()
4169 return "Base Implementation. Should be overridden.";
4173 * This is designed to be overridden and add specific fields to each record.
4174 * This allows the generic query to fill in the major fields, and then targeted
4175 * queries to get related fields and add them to the record. The contact's
4176 * account for instance. This method is only used for populating extra fields
4179 function fill_in_additional_list_fields(){
4180 if(!empty($this->field_defs['parent_name']) && empty($this->parent_name)){
4181 $this->fill_in_additional_parent_fields();
4186 * This is designed to be overridden and add specific fields to each record.
4187 * This allows the generic query to fill in the major fields, and then targeted
4188 * queries to get related fields and add them to the record. The contact's
4189 * account for instance. This method is only used for populating extra fields
4190 * in the detail form
4192 function fill_in_additional_detail_fields()
4194 if(!empty($this->field_defs['assigned_user_name']) && !empty($this->assigned_user_id)){
4196 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
4199 if(!empty($this->field_defs['created_by']) && !empty($this->created_by))
4200 $this->created_by_name = get_assigned_user_name($this->created_by);
4201 if(!empty($this->field_defs['modified_user_id']) && !empty($this->modified_user_id))
4202 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
4204 if(!empty($this->field_defs['parent_name'])){
4205 $this->fill_in_additional_parent_fields();
4210 * This is desgined to be overridden or called from extending bean. This method
4211 * will fill in any parent_name fields.
4213 function fill_in_additional_parent_fields() {
4215 if(!empty($this->parent_id) && !empty($this->last_parent_id) && $this->last_parent_id == $this->parent_id){
4218 $this->parent_name = '';
4220 if(!empty($this->parent_type)) {
4221 $this->last_parent_id = $this->parent_id;
4222 $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'));
4223 if(!empty($this->parent_first_name) || !empty($this->parent_last_name) ){
4224 $this->parent_name = $GLOBALS['locale']->getLocaleFormattedName($this->parent_first_name, $this->parent_last_name);
4225 } else if(!empty($this->parent_document_name)){
4226 $this->parent_name = $this->parent_document_name;
4232 * Fill in a link field
4235 function fill_in_link_field( $linkFieldName )
4237 if ($this->load_relationship($linkFieldName))
4239 $list=$this->$linkFieldName->get();
4240 $this->$linkFieldName = '' ; // match up with null value in $this->populateFromRow()
4242 $this->$linkFieldName = $list[0];
4247 * Fill in fields where type = relate
4249 function fill_in_relationship_fields(){
4250 global $fill_in_rel_depth;
4251 if(empty($fill_in_rel_depth) || $fill_in_rel_depth < 0)
4252 $fill_in_rel_depth = 0;
4253 if($fill_in_rel_depth > 1)
4255 $fill_in_rel_depth++;
4257 foreach($this->field_defs as $field)
4259 if(0 == strcmp($field['type'],'relate') && !empty($field['module']))
4261 $name = $field['name'];
4262 if(empty($this->$name))
4264 // 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']
4265 $related_module = $field['module'];
4266 $id_name = $field['id_name'];
4267 if (empty($this->$id_name)){
4268 $this->fill_in_link_field($id_name);
4270 if(!empty($this->$id_name) && ( $this->object_name != $related_module || ( $this->object_name == $related_module && $this->$id_name != $this->id ))){
4271 if(isset($GLOBALS['beanList'][ $related_module])){
4272 $class = $GLOBALS['beanList'][$related_module];
4274 if(!empty($this->$id_name) && file_exists($GLOBALS['beanFiles'][$class]) && isset($this->$name)){
4275 require_once($GLOBALS['beanFiles'][$class]);
4276 $mod = new $class();
4277 $mod->retrieve($this->$id_name);
4278 if (!empty($field['rname'])) {
4279 $this->$name = $mod->$field['rname'];
4280 } else if (isset($mod->name)) {
4281 $this->$name = $mod->name;
4286 if(!empty($this->$id_name) && isset($this->$name))
4288 if(!isset($field['additionalFields']))
4289 $field['additionalFields'] = array();
4290 if(!empty($field['rname']))
4292 $field['additionalFields'][$field['rname']]= $name;
4296 $field['additionalFields']['name']= $name;
4298 $this->getRelatedFields($related_module, $this->$id_name, $field['additionalFields']);
4303 $fill_in_rel_depth--;
4307 * This is a helper function that is used to quickly created indexes when creating tables.
4309 function create_index($query)
4311 $GLOBALS['log']->info($query);
4313 $result = $this->db->query($query, true, "Error creating index:");
4317 * This function should be overridden in each module. It marks an item as deleted.
4319 * If it is not overridden, then marking this type of item is not allowed
4321 function mark_deleted($id)
4323 global $current_user;
4324 $date_modified = $GLOBALS['timedate']->nowDb();
4325 if(isset($_SESSION['show_deleted']))
4327 $this->mark_undeleted($id);
4331 // call the custom business logic
4332 $custom_logic_arguments['id'] = $id;
4333 $this->call_custom_logic("before_delete", $custom_logic_arguments);
4334 $this->mark_relationships_deleted($id);
4335 if ( isset($this->field_defs['modified_user_id']) ) {
4336 if (!empty($current_user)) {
4337 $this->modified_user_id = $current_user->id;
4339 $this->modified_user_id = 1;
4341 $query = "UPDATE $this->table_name set deleted=1 , date_modified = '$date_modified', modified_user_id = '$this->modified_user_id' where id='$id'";
4343 $query = "UPDATE $this->table_name set deleted=1 , date_modified = '$date_modified' where id='$id'";
4344 $this->db->query($query, true,"Error marking record deleted: ");
4347 SugarRelationship::resaveRelatedBeans();
4349 // Take the item off the recently viewed lists
4350 $tracker = new Tracker();
4351 $tracker->makeInvisibleForAll($id);
4353 // call the custom business logic
4354 $this->call_custom_logic("after_delete", $custom_logic_arguments);
4359 * Restores data deleted by call to mark_deleted() function.
4361 * Internal function, do not override.
4363 function mark_undeleted($id)
4365 // call the custom business logic
4366 $custom_logic_arguments['id'] = $id;
4367 $this->call_custom_logic("before_restore", $custom_logic_arguments);
4369 $date_modified = $GLOBALS['timedate']->nowDb();
4370 $query = "UPDATE $this->table_name set deleted=0 , date_modified = '$date_modified' where id='$id'";
4371 $this->db->query($query, true,"Error marking record undeleted: ");
4373 // call the custom business logic
4374 $this->call_custom_logic("after_restore", $custom_logic_arguments);
4378 * This function deletes relationships to this object. It should be overridden
4379 * to handle the relationships of the specific object.
4380 * This function is called when the item itself is being deleted.
4382 * @param int $id id of the relationship to delete
4384 function mark_relationships_deleted($id)
4386 $this->delete_linked($id);
4390 * This function is used to execute the query and create an array template objects
4391 * from the resulting ids from the query.
4392 * It is currently used for building sub-panel arrays.
4394 * @param string $query - the query that should be executed to build the list
4395 * @param object $template - The object that should be used to copy the records.
4396 * @param int $row_offset Optional, default 0
4397 * @param int $limit Optional, default -1
4400 function build_related_list($query, &$template, $row_offset = 0, $limit = -1)
4402 $GLOBALS['log']->debug("Finding linked records $this->object_name: ".$query);
4403 $db = &DBManagerFactory::getInstance('listviews');
4405 if(!empty($row_offset) && $row_offset != 0 && !empty($limit) && $limit != -1)
4407 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $template->object_name list: ");
4411 $result = $db->query($query, true);
4415 $isFirstTime = true;
4416 $class = get_class($template);
4417 while($row = $this->db->fetchByAssoc($result))
4421 $template = new $class();
4423 $isFirstTime = false;
4424 $record = $template->retrieve($row['id']);
4428 // this copies the object into the array
4429 $list[] = $template;
4436 * This function is used to execute the query and create an array template objects
4437 * from the resulting ids from the query.
4438 * It is currently used for building sub-panel arrays. It supports an additional
4439 * where clause that is executed as a filter on the results
4441 * @param string $query - the query that should be executed to build the list
4442 * @param object $template - The object that should be used to copy the records.
4444 function build_related_list_where($query, &$template, $where='', $in='', $order_by, $limit='', $row_offset = 0)
4446 $db = &DBManagerFactory::getInstance('listviews');
4447 // No need to do an additional query
4448 $GLOBALS['log']->debug("Finding linked records $this->object_name: ".$query);
4449 if(empty($in) && !empty($query))
4451 $idList = $this->build_related_in($query);
4452 $in = $idList['in'];
4454 // MFH - Added Support For Custom Fields in Searches
4456 if(isset($this->custom_fields)) {
4457 $custom_join = $this->custom_fields->getJOIN();
4460 $query = "SELECT id ";
4462 if (!empty($custom_join)) {
4463 $query .= $custom_join['select'];
4465 $query .= " FROM $this->table_name ";
4467 if (!empty($custom_join) && !empty($custom_join['join'])) {
4468 $query .= " " . $custom_join['join'];
4471 $query .= " WHERE deleted=0 AND id IN $in";
4474 $query .= " AND $where";
4478 if(!empty($order_by))
4480 $query .= "ORDER BY $order_by";
4484 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $this->object_name list: ");
4488 $result = $db->query($query, true);
4492 $isFirstTime = true;
4493 $class = get_class($template);
4495 $disable_security_flag = ($template->disable_row_level_security) ? true : false;
4496 while($row = $db->fetchByAssoc($result))
4500 $template = new $class();
4501 $template->disable_row_level_security = $disable_security_flag;
4503 $isFirstTime = false;
4504 $record = $template->retrieve($row['id']);
4507 // this copies the object into the array
4508 $list[] = $template;
4516 * Constructs an comma seperated list of ids from passed query results.
4518 * @param string @query query to be executed.
4521 function build_related_in($query)
4524 $result = $this->db->query($query, true);
4526 while($row = $this->db->fetchByAssoc($result))
4528 $idList[] = $row['id'];
4531 $ids = "('" . $row['id'] . "'";
4535 $ids .= ",'" . $row['id'] . "'";
4545 return array('list'=>$idList, 'in'=>$ids);
4549 * Optionally copies values from fetched row into the bean.
4551 * Internal function, do not override.
4553 * @param string $query - the query that should be executed to build the list
4554 * @param object $template - The object that should be used to copy the records
4555 * @param array $field_list List of fields.
4558 function build_related_list2($query, &$template, &$field_list)
4560 $GLOBALS['log']->debug("Finding linked values $this->object_name: ".$query);
4562 $result = $this->db->query($query, true);
4565 $isFirstTime = true;
4566 $class = get_class($template);
4567 while($row = $this->db->fetchByAssoc($result))
4569 // Create a blank copy
4573 $copy = new $class();
4575 $isFirstTime = false;
4576 foreach($field_list as $field)
4578 // Copy the relevant fields
4579 $copy->$field = $row[$field];
4583 // this copies the object into the array
4591 * Let implementing classes to fill in row specific columns of a list view form
4594 function list_view_parse_additional_sections(&$list_form)
4599 * Assigns all of the values into the template for the list view
4601 function get_list_view_array()
4603 static $cache = array();
4604 // cn: bug 12270 - sensitive fields being passed arbitrarily in listViews
4605 $sensitiveFields = array('user_hash' => '');
4607 $return_array = Array();
4608 global $app_list_strings, $mod_strings;
4609 foreach($this->field_defs as $field=>$value){
4611 if(isset($this->$field)){
4613 // cn: bug 12270 - sensitive fields being passed arbitrarily in listViews
4614 if(isset($sensitiveFields[$field]))
4616 if(!isset($cache[$field]))
4617 $cache[$field] = strtoupper($field);
4619 //Fields hidden by Dependent Fields
4620 if (isset($value['hidden']) && $value['hidden'] === true) {
4621 $return_array[$cache[$field]] = "";
4624 //cn: if $field is a _dom, detect and return VALUE not KEY
4625 //cl: empty function check for meta-data enum types that have values loaded from a function
4626 else if (((!empty($value['type']) && ($value['type'] == 'enum' || $value['type'] == 'radioenum') )) && empty($value['function'])){
4627 if(!empty($app_list_strings[$value['options']][$this->$field])){
4628 $return_array[$cache[$field]] = $app_list_strings[$value['options']][$this->$field];
4630 //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.
4631 elseif(!empty($mod_strings[$value['options']][$this->$field]))
4633 $return_array[$cache[$field]] = $mod_strings[$value['options']][$this->$field];
4636 $return_array[$cache[$field]] = $this->$field;
4639 // tjy: no need to do this str_replace as the changes in 29994 for ListViewGeneric.tpl for translation handle this now
4640 // }elseif(!empty($value['type']) && $value['type'] == 'multienum'&& empty($value['function'])){
4641 // $return_array[strtoupper($field)] = str_replace('^,^', ', ', $this->$field );
4642 }elseif(!empty($value['custom_module']) && $value['type'] != 'currency'){
4643 // $this->format_field($value);
4644 $return_array[$cache[$field]] = $this->$field;
4646 $return_array[$cache[$field]] = $this->$field;
4648 // handle "Assigned User Name"
4649 if($field == 'assigned_user_name'){
4650 $return_array['ASSIGNED_USER_NAME'] = get_assigned_user_name($this->assigned_user_id);
4654 return $return_array;
4657 * Override this function to set values in the array used to render list view data.
4660 function get_list_view_data()
4662 return $this->get_list_view_array();
4666 * Construct where clause from a list of name-value pairs.
4669 function get_where(&$fields_array)
4671 $where_clause = "WHERE ";
4673 foreach ($fields_array as $name=>$value)
4681 $where_clause .= " AND ";
4684 $where_clause .= "$name = '".$this->db->quote($value,false)."'";
4686 $where_clause .= " AND deleted=0";
4687 return $where_clause;
4692 * Constructs a select query and fetch 1 row using this query, and then process the row
4694 * Internal function, do not override.
4695 * @param array @fields_array array of name value pairs used to construct query.
4696 * @param boolean $encode Optional, default true, encode fetched data.
4697 * @return object Instance of this bean with fetched data.
4699 function retrieve_by_string_fields($fields_array, $encode=true)
4701 $where_clause = $this->get_where($fields_array);
4702 if(isset($this->custom_fields))
4703 $custom_join = $this->custom_fields->getJOIN();
4704 else $custom_join = false;
4707 $query = "SELECT $this->table_name.*". $custom_join['select']. " FROM $this->table_name " . $custom_join['join'];
4711 $query = "SELECT $this->table_name.* FROM $this->table_name ";
4713 $query .= " $where_clause";
4714 $GLOBALS['log']->debug("Retrieve $this->object_name: ".$query);
4715 //requireSingleResult has beeen deprecated.
4716 //$result = $this->db->requireSingleResult($query, true, "Retrieving record $where_clause:");
4717 $result = $this->db->limitQuery($query,0,1,true, "Retrieving record $where_clause:");
4724 if($this->db->getRowCount($result) > 1)
4726 $this->duplicates_found = true;
4728 $row = $this->db->fetchByAssoc($result, -1, $encode);
4733 $this->fetched_row = $row;
4734 $this->fromArray($row);
4735 $this->fill_in_additional_detail_fields();
4740 * This method is called during an import before inserting a bean
4741 * Define an associative array called $special_fields
4742 * the keys are user defined, and don't directly map to the bean's fields
4743 * the value is the method name within that bean that will do extra
4744 * processing for that field. example: 'full_name'=>'get_names_from_full_name'
4747 function process_special_fields()
4749 foreach ($this->special_functions as $func_name)
4751 if ( method_exists($this,$func_name) )
4753 $this->$func_name();
4759 * Override this function to build a where clause based on the search criteria set into bean .
4762 function build_generic_where_clause($value)
4766 function getRelatedFields($module, $id, $fields, $return_array = false){
4767 if(empty($GLOBALS['beanList'][$module]))return '';
4768 $object = $GLOBALS['beanList'][$module];
4769 if ($object == 'aCase') {
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 .= ' ,' .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] > 10)
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);
5012 /* When creating a custom field of type Dropdown, it creates an enum row in the DB.
5013 A typical get_list_view_array() result will have the *KEY* value from that drop-down.
5014 Since custom _dom objects are flat-files included in the $app_list_strings variable,
5015 We need to generate a key-key pair to get the true value like so:
5016 ([module]_cstm->fields_meta_data->$app_list_strings->*VALUE*)*/
5017 function getRealKeyFromCustomFieldAssignedKey($name)
5019 if ($this->custom_fields->avail_fields[$name]['ext1'])
5023 elseif ($this->custom_fields->avail_fields[$name]['ext2'])
5027 elseif ($this->custom_fields->avail_fields[$name]['ext3'])
5033 $GLOBALS['log']->fatal("SUGARBEAN: cannot find Real Key for custom field of type dropdown - cannot return Value.");
5038 return $this->custom_fields->avail_fields[$name][$realKey];
5042 function bean_implements($interface)
5047 * Check whether the user has access to a particular view for the current bean/module
5048 * @param $view string required, the view to determine access for i.e. DetailView, ListView...
5049 * @param $is_owner bool optional, this is part of the ACL check if the current user is an owner they will receive different access
5051 function ACLAccess($view,$is_owner='not_set')
5053 global $current_user;
5054 if($current_user->isAdminForModule($this->getACLCategory())) {
5058 if($is_owner == 'not_set')
5061 $is_owner = $this->isOwner($current_user->id);
5064 //if we don't implent acls return true
5065 if(!$this->bean_implements('ACL'))
5067 $view = strtolower($view);
5073 return ACLController::checkAccess($this->module_dir,'list', true);
5076 if( !$is_owner && $not_set && !empty($this->id)){
5077 $class = get_class($this);
5078 $temp = new $class();
5079 if(!empty($this->fetched_row) && !empty($this->fetched_row['id']) && !empty($this->fetched_row['assigned_user_id']) && !empty($this->fetched_row['created_by'])){
5080 $temp->populateFromRow($this->fetched_row);
5082 $temp->retrieve($this->id);
5084 $is_owner = $temp->isOwner($current_user->id);
5086 case 'popupeditview':
5088 return ACLController::checkAccess($this->module_dir,'edit', $is_owner, $this->acltype);
5092 return ACLController::checkAccess($this->module_dir,'view', $is_owner, $this->acltype);
5094 return ACLController::checkAccess($this->module_dir,'delete', $is_owner, $this->acltype);
5096 return ACLController::checkAccess($this->module_dir,'export', $is_owner, $this->acltype);
5098 return ACLController::checkAccess($this->module_dir,'import', true, $this->acltype);
5100 //if it is not one of the above views then it should be implemented on the page level
5104 * Returns true of false if the user_id passed is the owner
5106 * @param GUID $user_id
5109 function isOwner($user_id)
5111 //if we don't have an id we must be the owner as we are creating it
5112 if(!isset($this->id))
5116 //if there is an assigned_user that is the owner
5117 if(isset($this->assigned_user_id))
5119 if($this->assigned_user_id == $user_id) return true;
5124 //other wise if there is a created_by that is the owner
5125 if(isset($this->created_by) && $this->created_by == $user_id)
5133 * Gets there where statement for checking if a user is an owner
5135 * @param GUID $user_id
5138 function getOwnerWhere($user_id)
5140 if(isset($this->field_defs['assigned_user_id']))
5142 return " $this->table_name.assigned_user_id ='$user_id' ";
5144 if(isset($this->field_defs['created_by']))
5146 return " $this->table_name.created_by ='$user_id' ";
5153 * Used in order to manage ListView links and if they should
5154 * links or not based on the ACL permissions of the user
5156 * @return ARRAY of STRINGS
5158 function listviewACLHelper()
5160 $array_assign = array();
5161 if($this->ACLAccess('DetailView'))
5163 $array_assign['MAIN'] = 'a';
5167 $array_assign['MAIN'] = 'span';
5169 return $array_assign;
5173 * returns this bean as an array
5175 * @return array of fields with id, name, access and category
5177 function toArray($dbOnly = false, $stringOnly = false, $upperKeys=false)
5179 static $cache = array();
5182 foreach($this->field_defs as $field=>$data)
5184 if( !$dbOnly || !isset($data['source']) || $data['source'] == 'db')
5185 if(!$stringOnly || is_string($this->$field))
5188 if(!isset($cache[$field])){
5189 $cache[$field] = strtoupper($field);
5191 $arr[$cache[$field]] = $this->$field;
5195 if(isset($this->$field)){
5196 $arr[$field] = $this->$field;
5206 * Converts an array into an acl mapping name value pairs into files
5210 function fromArray($arr)
5212 foreach($arr as $name=>$value)
5214 $this->$name = $value;
5219 * Loads a row of data into instance of a bean. The data is passed as an array to this function
5221 * @param array $arr row of data fetched from the database.
5224 * Internal function do not override.
5226 function loadFromRow($arr)
5228 $this->populateFromRow($arr);
5229 $this->processed_dates_times = array();
5230 $this->check_date_relationships_load();
5232 $this->fill_in_additional_list_fields();
5234 if($this->hasCustomFields())$this->custom_fields->fill_relationships();
5235 $this->call_custom_logic("process_record");
5238 function hasCustomFields(){
5239 return !empty($GLOBALS['dictionary'][$this->object_name]['custom_fields']);
5243 * Ensure that fields within order by clauses are properly qualified with
5244 * their tablename. This qualification is a requirement for sql server support.
5246 * @param string $order_by original order by from the query
5247 * @param string $qualify prefix for columns in the order by list.
5250 * Internal function do not override.
5252 function create_qualified_order_by( $order_by, $qualify)
5253 { // 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
5254 if (empty($order_by))
5258 $order_by_clause = " ORDER BY ";
5259 $tmp = explode(",", $order_by);
5261 foreach ( $tmp as $stmp)
5263 $stmp = (substr_count($stmp, ".") > 0?trim($stmp):"$qualify." . trim($stmp));
5264 $order_by_clause .= $comma . $stmp;
5267 return $order_by_clause;
5271 * Combined the contents of street field 2 thru 4 into the main field
5273 * @param string $street_field
5276 function add_address_streets(
5280 $street_field_2 = $street_field.'_2';
5281 $street_field_3 = $street_field.'_3';
5282 $street_field_4 = $street_field.'_4';
5283 if ( isset($this->$street_field_2)) {
5284 $this->$street_field .= "\n". $this->$street_field_2;
5285 unset($this->$street_field_2);
5287 if ( isset($this->$street_field_3)) {
5288 $this->$street_field .= "\n". $this->$street_field_3;
5289 unset($this->$street_field_3);
5291 if ( isset($this->$street_field_4)) {
5292 $this->$street_field .= "\n". $this->$street_field_4;
5293 unset($this->$street_field_4);
5295 if ( isset($this->$street_field)) {
5296 $this->$street_field = trim($this->$street_field, "\n");
5300 * Encrpyt and base64 encode an 'encrypt' field type in the bean using Blowfish. The default system key is stored in cache/Blowfish/{keytype}
5301 * @param STRING value -plain text value of the bean field.
5304 function encrpyt_before_save($value)
5306 require_once("include/utils/encryption_utils.php");
5307 return blowfishEncode(blowfishGetKey('encrypt_field'),$value);
5311 * Decode and decrypt a base 64 encoded string with field type 'encrypt' in this bean using Blowfish.
5312 * @param STRING value - an encrypted and base 64 encoded string.
5315 function decrypt_after_retrieve($value)
5317 require_once("include/utils/encryption_utils.php");
5318 return blowfishDecode(blowfishGetKey('encrypt_field'), $value);
5322 * Moved from save() method, functionality is the same, but this is intended to handle
5323 * Optimistic locking functionality.
5325 private function _checkOptimisticLocking($action, $isUpdate){
5326 if($this->optimistic_lock && !isset($_SESSION['o_lock_fs'])){
5327 if(isset($_SESSION['o_lock_id']) && $_SESSION['o_lock_id'] == $this->id && $_SESSION['o_lock_on'] == $this->object_name)
5329 if($action == 'Save' && $isUpdate && isset($this->modified_user_id) && $this->has_been_modified_since($_SESSION['o_lock_dm'], $this->modified_user_id))
5331 $_SESSION['o_lock_class'] = get_class($this);
5332 $_SESSION['o_lock_module'] = $this->module_dir;
5333 $_SESSION['o_lock_object'] = $this->toArray();
5334 $saveform = "<form name='save' id='save' method='POST'>";
5335 foreach($_POST as $key=>$arg)
5337 $saveform .= "<input type='hidden' name='". addslashes($key) ."' value='". addslashes($arg) ."'>";
5339 $saveform .= "</form><script>document.getElementById('save').submit();</script>";
5340 $_SESSION['o_lock_save'] = $saveform;
5341 header('Location: index.php?module=OptimisticLock&action=LockResolve');
5346 unset ($_SESSION['o_lock_object']);
5347 unset ($_SESSION['o_lock_id']);
5348 unset ($_SESSION['o_lock_dm']);
5354 if(isset($_SESSION['o_lock_object'])) { unset ($_SESSION['o_lock_object']); }
5355 if(isset($_SESSION['o_lock_id'])) { unset ($_SESSION['o_lock_id']); }
5356 if(isset($_SESSION['o_lock_dm'])) { unset ($_SESSION['o_lock_dm']); }
5357 if(isset($_SESSION['o_lock_fs'])) { unset ($_SESSION['o_lock_fs']); }
5358 if(isset($_SESSION['o_lock_save'])) { unset ($_SESSION['o_lock_save']); }
5363 * Send assignment notifications and invites for meetings and calls
5365 private function _sendNotifications($check_notify){
5366 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.
5367 && !$this->isOwner($this->created_by) ) // cn: bug 42727 no need to send email to owner (within workflow)
5369 $admin = new Administration();
5370 $admin->retrieveSettings();
5371 $sendNotifications = false;
5373 if ($admin->settings['notify_on'])
5375 $GLOBALS['log']->info("Notifications: user assignment has changed, checking if user receives notifications");
5376 $sendNotifications = true;
5378 elseif(isset($_REQUEST['send_invites']) && $_REQUEST['send_invites'] == 1)
5380 // cn: bug 5795 Send Invites failing for Contacts
5381 $sendNotifications = true;
5385 $GLOBALS['log']->info("Notifications: not sending e-mail, notify_on is set to OFF");
5389 if($sendNotifications == true)
5391 $notify_list = $this->get_notification_recipients();
5392 foreach ($notify_list as $notify_user)
5394 $this->send_assignment_notifications($notify_user, $admin);
5402 * Called from ImportFieldSanitize::relate(), when creating a new bean in a related module. Will
5403 * copies fields over from the current bean into the related. Designed to be overriden in child classes.
5405 * @param SugarBean $newbean newly created related bean
5407 public function populateRelatedBean(
5414 * Called during the import process before a bean save, to handle any needed pre-save logic when
5415 * importing a record
5417 public function beforeImportSave()
5422 * Called during the import process after a bean save, to handle any needed post-save logic when
5423 * importing a record
5425 public function afterImportSave()
5430 * This function is designed to cache references to field arrays that were previously stored in the
5431 * bean files and have since been moved to seperate files. Was previously in include/CacheHandler.php
5434 * @param $module_dir string the module directory
5435 * @param $module string the name of the module
5436 * @param $key string the type of field array we are referencing, i.e. list_fields, column_fields, required_fields
5438 private function _loadCachedArray(
5444 static $moduleDefs = array();
5446 $fileName = 'field_arrays.php';
5448 $cache_key = "load_cached_array.$module_dir.$module.$key";
5449 $result = sugar_cache_retrieve($cache_key);
5452 // Use SugarCache::EXTERNAL_CACHE_NULL_VALUE to store null values in the cache.
5453 if($result == SugarCache::EXTERNAL_CACHE_NULL_VALUE)
5461 if(file_exists('modules/'.$module_dir.'/'.$fileName))
5463 // If the data was not loaded, try loading again....
5464 if(!isset($moduleDefs[$module]))
5466 include('modules/'.$module_dir.'/'.$fileName);
5467 $moduleDefs[$module] = $fields_array;
5469 // Now that we have tried loading, make sure it was loaded
5470 if(empty($moduleDefs[$module]) || empty($moduleDefs[$module][$module][$key]))
5472 // It was not loaded.... Fail. Cache null to prevent future repeats of this calculation
5473 sugar_cache_put($cache_key, SugarCache::EXTERNAL_CACHE_NULL_VALUE);
5477 // It has been loaded, cache the result.
5478 sugar_cache_put($cache_key, $moduleDefs[$module][$module][$key]);
5479 return $moduleDefs[$module][$module][$key];
5482 // It was not loaded.... Fail. Cache null to prevent future repeats of this calculation
5483 sugar_cache_put($cache_key, SugarCache::EXTERNAL_CACHE_NULL_VALUE);
5488 * Returns the ACL category for this module; defaults to the SugarBean::$acl_category if defined
5489 * otherwise it is SugarBean::$module_dir
5493 public function getACLCategory()
5495 return !empty($this->acl_category)?$this->acl_category:$this->module_dir;
5499 * Returns the query used for the export functionality for a module. Override this method if you wish
5500 * to have a custom query to pull this data together instead
5502 * @param string $order_by
5503 * @param string $where
5504 * @return string SQL query
5506 public function create_export_query($order_by, $where)
5508 return $this->create_new_list_query($order_by, $where, array(), array(), 0, '', false, $this, true, true);