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");
56 * SugarBean is the base class for all business objects in Sugar. It implements
57 * the primary functionality needed for manipulating business objects: create,
58 * retrieve, update, delete. It allows for searching and retrieving list of records.
59 * It allows for retrieving related objects (e.g. contacts related to a specific account).
61 * In the current implementation, there can only be one bean per folder.
62 * Naming convention has the bean name be the same as the module and folder name.
63 * All bean names should be singular (e.g. Contact). The primary table name for
64 * a bean should be plural (e.g. contacts).
70 * A pointer to the database object
77 * When createing a bean, you can specify a value in the id column as
78 * long as that value is unique. During save, if the system finds an
79 * id, it assumes it is an update. Setting new_with_id to true will
80 * make sure the system performs an insert instead of an update.
82 * @var BOOL -- default false
84 var $new_with_id = false;
88 * Disble vardefs. This should be set to true only for beans that do not have varders. Tracker is an example
90 * @var BOOL -- default false
92 var $disable_vardefs = false;
96 * holds the full name of the user that an item is assigned to. Only used if notifications
97 * are turned on and going to be sent out.
101 var $new_assigned_user_name;
104 * An array of booleans. This array is cleared out when data is loaded.
105 * As date/times are converted, a "1" is placed under the key, the field is converted.
107 * @var Array of booleans
109 var $processed_dates_times = array();
112 * Whether to process date/time fields for storage in the database in GMT
116 var $process_save_dates =true;
119 * This signals to the bean that it is being saved in a mass mode.
120 * Examples of this kind of save are import and mass update.
121 * We turn off notificaitons of this is the case to make things more efficient.
125 var $save_from_post = true;
128 * When running a query on related items using the method: retrieve_by_string_fields
129 * this value will be set to true if more than one item matches the search criteria.
133 var $duplicates_found = false;
136 * true if this bean has been deleted, false otherwise.
143 * Should the date modified column of the bean be updated during save?
144 * This is used for admin level functionality that should not be updating
145 * the date modified. This is only used by sync to allow for updates to be
146 * replicated in a way that will not cause them to be replicated back.
150 var $update_date_modified = true;
153 * Should the modified by column of the bean be updated during save?
154 * This is used for admin level functionality that should not be updating
155 * the modified by column. This is only used by sync to allow for updates to be
156 * replicated in a way that will not cause them to be replicated back.
160 var $update_modified_by = true;
163 * Setting this to true allows for updates to overwrite the date_entered
167 var $update_date_entered = false;
170 * This allows for seed data to be created without using the current uesr to set the id.
171 * This should be replaced by altering the current user before the call to save.
175 //TODO This should be replaced by altering the current user before the call to save.
176 var $set_created_by = true;
181 * The database table where records of this Bean are stored.
185 var $table_name = '';
188 * This is the singular name of the bean. (i.e. Contact).
192 var $object_name = '';
194 /** Set this to true if you query contains a sub-select and bean is converting both select statements
195 * into count queries.
197 var $ungreedy_count=false;
200 * The name of the module folder for this type of bean.
204 var $module_dir = '';
205 var $module_name = '';
209 var $column_fields = array();
210 var $list_fields = array();
211 var $additional_column_fields = array();
212 var $relationship_fields = array();
213 var $current_notify_user;
214 var $fetched_row=false;
216 var $force_load_details = false;
217 var $optimistic_lock = false;
218 var $disable_custom_fields = false;
219 var $number_formatting_done = false;
220 var $process_field_encrypted=false;
222 * The default ACL type
224 var $acltype = 'module';
227 var $additional_meta_fields = array();
230 * Set to true in the child beans if the module supports importing
232 var $importable = false;
235 * Set to true in the child beans if the module use the special notification template
237 var $special_notification = false;
240 * Set to true if the bean is being dealt with in a workflow
242 var $in_workflow = false;
246 * By default it will be true but if any module is to be kept non visible
247 * to tracker, then its value needs to be overriden in that particular module to false.
250 var $tracker_visibility = true;
253 * Used to pass inner join string to ListView Data.
255 var $listview_inner_join = array();
258 * Set to true in <modules>/Import/views/view.step4.php if a module is being imported
260 var $in_import = false;
262 * Constructor for the bean, it performs following tasks:
264 * 1. Initalized a database connections
265 * 2. Load the vardefs for the module implemeting the class. cache the entries
267 * 3. Setup row-level security preference
268 * All implementing classes must call this constructor using the parent::SugarBean() class.
273 global $dictionary, $current_user;
274 static $loaded_defs = array();
275 $this->db = DBManagerFactory::getInstance();
276 if (empty($this->module_name))
277 $this->module_name = $this->module_dir;
278 if((false == $this->disable_vardefs && empty($loaded_defs[$this->object_name])) || !empty($GLOBALS['reload_vardefs']))
280 VardefManager::loadVardef($this->module_dir, $this->object_name);
282 // build $this->column_fields from the field_defs if they exist
283 if (!empty($dictionary[$this->object_name]['fields'])) {
284 foreach ($dictionary[$this->object_name]['fields'] as $key=>$value_array) {
285 $column_fields[] = $key;
286 if(!empty($value_array['required']) && !empty($value_array['name'])) {
287 $this->required_fields[$value_array['name']] = 1;
290 $this->column_fields = $column_fields;
293 //setup custom fields
294 if(!isset($this->custom_fields) &&
295 empty($this->disable_custom_fields))
297 $this->setupCustomFields($this->module_dir);
299 //load up field_arrays from CacheHandler;
300 if(empty($this->list_fields))
301 $this->list_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'list_fields');
302 if(empty($this->column_fields))
303 $this->column_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'column_fields');
304 if(empty($this->required_fields))
305 $this->required_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'required_fields');
307 if(isset($GLOBALS['dictionary'][$this->object_name]) && !$this->disable_vardefs)
309 $this->field_name_map = $dictionary[$this->object_name]['fields'];
310 $this->field_defs = $dictionary[$this->object_name]['fields'];
312 if(!empty($dictionary[$this->object_name]['optimistic_locking']))
314 $this->optimistic_lock=true;
317 $loaded_defs[$this->object_name]['column_fields'] =& $this->column_fields;
318 $loaded_defs[$this->object_name]['list_fields'] =& $this->list_fields;
319 $loaded_defs[$this->object_name]['required_fields'] =& $this->required_fields;
320 $loaded_defs[$this->object_name]['field_name_map'] =& $this->field_name_map;
321 $loaded_defs[$this->object_name]['field_defs'] =& $this->field_defs;
325 $this->column_fields =& $loaded_defs[$this->object_name]['column_fields'] ;
326 $this->list_fields =& $loaded_defs[$this->object_name]['list_fields'];
327 $this->required_fields =& $loaded_defs[$this->object_name]['required_fields'];
328 $this->field_name_map =& $loaded_defs[$this->object_name]['field_name_map'];
329 $this->field_defs =& $loaded_defs[$this->object_name]['field_defs'];
330 $this->added_custom_field_defs = true;
332 if(!isset($this->custom_fields) &&
333 empty($this->disable_custom_fields))
335 $this->setupCustomFields($this->module_dir, false);
337 if(!empty($dictionary[$this->object_name]['optimistic_locking']))
339 $this->optimistic_lock=true;
343 if($this->bean_implements('ACL') && !empty($GLOBALS['current_user'])){
344 $this->acl_fields = (isset($dictionary[$this->object_name]['acl_fields']) && $dictionary[$this->object_name]['acl_fields'] === false)?false:true;
346 $this->populateDefaultValues();
351 * Returns the object name. If object_name is not set, table_name is returned.
353 * All implementing classes must set a value for the object_name variable.
355 * @param array $arr row of data fetched from the database.
359 function getObjectName()
361 if ($this->object_name)
362 return $this->object_name;
364 // This is a quick way out. The generated metadata files have the table name
365 // as the key. The correct way to do this is to override this function
366 // in bean and return the object name. That requires changing all the beans
367 // as well as put the object name in the generator.
368 return $this->table_name;
372 * Returns a list of fields with their definitions that have the audited property set to true.
373 * Before calling this function, check whether audit has been enabled for the table/module or not.
374 * You would set the audit flag in the implemting module's vardef file.
376 * @return an array of
377 * @see is_AuditEnabled
379 * Internal function, do not override.
381 function getAuditEnabledFieldDefinitions()
383 $aclcheck = $this->bean_implements('ACL');
384 $is_owner = $this->isOwner($GLOBALS['current_user']->id);
385 if (!isset($this->audit_enabled_fields))
388 $this->audit_enabled_fields=array();
389 foreach ($this->field_defs as $field => $properties)
394 !empty($properties['Audited']) || !empty($properties['audited']))
398 $this->audit_enabled_fields[$field]=$properties;
403 return $this->audit_enabled_fields;
407 * Return true if auditing is enabled for this object
408 * You would set the audit flag in the implemting module's vardef file.
412 * Internal function, do not override.
414 function is_AuditEnabled()
417 if (isset($dictionary[$this->getObjectName()]['audited']))
419 return $dictionary[$this->getObjectName()]['audited'];
430 * Returns the name of the audit table.
431 * Audit table's name is based on implementing class' table name.
433 * @return String Audit table name.
435 * Internal function, do not override.
437 function get_audit_table_name()
439 return $this->getTableName().'_audit';
443 * If auditing is enabled, create the audit table.
445 * Function is used by the install scripts and a repair utility in the admin panel.
447 * Internal function, do not override.
449 function create_audit_table()
452 $table_name=$this->get_audit_table_name();
454 require('metadata/audit_templateMetaData.php');
456 $fieldDefs = $dictionary['audit']['fields'];
457 $indices = $dictionary['audit']['indices'];
458 // '0' stands for the first index for all the audit tables
459 $indices[0]['name'] = 'idx_' . strtolower($this->getTableName()) . '_' . $indices[0]['name'];
460 $indices[1]['name'] = 'idx_' . strtolower($this->getTableName()) . '_' . $indices[1]['name'];
462 if(isset($dictionary['audit']['engine'])) {
463 $engine = $dictionary['audit']['engine'];
464 } else if(isset($dictionary[$this->getObjectName()]['engine'])) {
465 $engine = $dictionary[$this->getObjectName()]['engine'];
468 $sql=$this->db->createTableSQLParams($table_name, $fieldDefs, $indices, $engine);
470 $msg = "Error creating table: ".$table_name. ":";
471 $this->db->query($sql,true,$msg);
475 * Returns the implementing class' table name.
477 * All implementing classes set a value for the table_name variable. This value is returned as the
478 * table name. If not set, table name is extracted from the implementing module's vardef.
480 * @return String Table name.
482 * Internal function, do not override.
484 public function getTableName()
486 if(isset($this->table_name))
488 return $this->table_name;
491 return $dictionary[$this->getObjectName()]['table'];
495 * Returns field definitions for the implementing module.
497 * The definitions were loaded in the constructor.
499 * @return Array Field definitions.
501 * Internal function, do not override.
503 function getFieldDefinitions()
505 return $this->field_defs;
509 * Returns index definitions for the implementing module.
511 * The definitions were loaded in the constructor.
513 * @return Array Index definitions.
515 * Internal function, do not override.
517 function getIndices()
520 if(isset($dictionary[$this->getObjectName()]['indices']))
522 return $dictionary[$this->getObjectName()]['indices'];
528 * Returns field definition for the requested field name.
530 * The definitions were loaded in the constructor.
532 * @param string field name,
533 * @return Array Field properties or boolean false if the field doesn't exist
535 * Internal function, do not override.
537 function getFieldDefinition($name)
539 if ( !isset($this->field_defs[$name]) )
542 return $this->field_defs[$name];
546 * Returnss definition for the id field name.
548 * The definitions were loaded in the constructor.
550 * @return Array Field properties.
552 * Internal function, do not override.
554 function getPrimaryFieldDefinition()
556 $def = $this->getFieldDefinition("id");
558 $def = $this->getFieldDefinition(0);
561 $defs = $this->field_defs;
563 $def = current($defs);
568 * Returns the value for the requested field.
570 * When a row of data is fetched using the bean, all fields are created as variables in the context
571 * of the bean and then fetched values are set in these variables.
573 * @param string field name,
574 * @return varies Field value.
576 * Internal function, do not override.
578 function getFieldValue($name)
580 if (!isset($this->$name)){
583 if($this->$name === TRUE){
586 if($this->$name === FALSE){
593 * Basically undoes the effects of SugarBean::populateDefaultValues(); this method is best called right after object
596 public function unPopulateDefaultValues()
598 if ( !is_array($this->field_defs) )
601 foreach ($this->field_defs as $field => $value) {
602 if( !empty($this->$field)
603 && ((isset($value['default']) && $this->$field == $value['default']) || (!empty($value['display_default']) && $this->$field == $value['display_default']))
605 $this->$field = null;
608 if(!empty($this->$field) && !empty($value['display_default']) && in_array($value['type'], array('date', 'datetime', 'datetimecombo')) &&
609 $this->$field == $this->parseDateDefault($value['display_default'], ($value['type'] != 'date'))) {
610 $this->$field = null;
616 * Create date string from default value
618 * @param string $value
619 * @param bool $time Should be expect time set too?
622 protected function parseDateDefault($value, $time = false)
626 $dtAry = explode('&', $value, 2);
627 $dateValue = $timedate->getNow(true)->modify($dtAry[0]);
628 if(!empty($dtAry[1])) {
629 $timeValue = $timedate->fromString($dtAry[1]);
630 $dateValue->setTime($timeValue->hour, $timeValue->min, $timeValue->sec);
632 return $timedate->asUser($dateValue);
634 return $timedate->asUserDate($timedate->getNow(true)->modify($value));
638 function populateDefaultValues($force=false){
639 if ( !is_array($this->field_defs) )
641 foreach($this->field_defs as $field=>$value){
642 if((isset($value['default']) || !empty($value['display_default'])) && ($force || empty($this->$field))){
643 $type = $value['type'];
647 if(!empty($value['display_default'])){
648 $this->$field = $this->parseDateDefault($value['display_default']);
652 case 'datetimecombo':
653 if(!empty($value['display_default'])){
654 $this->$field = $this->parseDateDefault($value['display_default'], true);
658 if(empty($value['default']) && !empty($value['display_default']))
659 $this->$field = $value['display_default'];
661 $this->$field = $value['default'];
664 if(isset($this->$field)){
668 if ( isset($value['default']) && $value['default'] !== '' ) {
669 $this->$field = htmlentities($value['default'], ENT_QUOTES, 'UTF-8');
680 * Removes relationship metadata cache.
682 * Every module that has relationships defined with other modules, has this meta data cached. The cache is
683 * stores in 2 locations: relationships table and file system. This method clears the cache from both locations.
685 * @param string $key module whose meta cache is to be cleared.
686 * @param string $db database handle.
687 * @param string $tablename table name
688 * @param string $dictionary vardef for the module
689 * @param string $module_dir name of subdirectory where module is installed.
694 * Internal function, do not override.
696 function removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir)
698 //load the module dictionary if not supplied.
699 if ((!isset($dictionary) or empty($dictionary)) && !empty($module_dir))
701 $filename='modules/'. $module_dir . '/vardefs.php';
702 if(file_exists($filename))
707 if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
709 $GLOBALS['log']->fatal("removeRelationshipMeta: Metadata for table ".$tablename. " does not exist");
710 display_notice("meta data absent for table ".$tablename." keyed to $key ");
714 if (isset($dictionary[$key]['relationships']))
716 $RelationshipDefs = $dictionary[$key]['relationships'];
717 foreach ($RelationshipDefs as $rel_name)
719 Relationship::delete($rel_name,$db);
727 * This method has been deprecated.
729 * @see removeRelationshipMeta()
730 * @deprecated 4.5.1 - Nov 14, 2006
733 function remove_relationship_meta($key,$db,$log,$tablename,$dictionary,$module_dir)
735 SugarBean::removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
740 * Populates the relationship meta for a module.
742 * It is called during setup/install. It is used statically to create relationship meta data for many-to-many tables.
744 * @param string $key name of the object.
745 * @param object $db database handle.
746 * @param string $tablename table, meta data is being populated for.
747 * @param array dictionary vardef dictionary for the object. *
748 * @param string module_dir name of subdirectory where module is installed.
749 * @param boolean $iscustom Optional,set to true if module is installed in a custom directory. Default value is false.
752 * Internal function, do not override.
754 function createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir,$iscustom=false)
756 //load the module dictionary if not supplied.
757 if (empty($dictionary) && !empty($module_dir))
761 $filename='custom/modules/' . $module_dir . '/Ext/Vardefs/vardefs.ext.php';
767 // a very special case for the Employees module
768 // this must be done because the Employees/vardefs.php does an include_once on
770 $filename='modules/Users/vardefs.php';
774 $filename='modules/'. $module_dir . '/vardefs.php';
778 if(file_exists($filename))
781 // cn: bug 7679 - dictionary entries defined as $GLOBALS['name'] not found
782 if(empty($dictionary) || !empty($GLOBALS['dictionary'][$key]))
784 $dictionary = $GLOBALS['dictionary'];
789 $GLOBALS['log']->debug("createRelationshipMeta: no metadata file found" . $filename);
794 if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
796 $GLOBALS['log']->fatal("createRelationshipMeta: Metadata for table ".$tablename. " does not exist");
797 display_notice("meta data absent for table ".$tablename." keyed to $key ");
801 if (isset($dictionary[$key]['relationships']))
804 $RelationshipDefs = $dictionary[$key]['relationships'];
808 $beanList_ucase=array_change_key_case ( $beanList ,CASE_UPPER);
809 foreach ($RelationshipDefs as $rel_name=>$rel_def)
811 if (isset($rel_def['lhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['lhs_module'])])) {
812 $GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' lhs module is missing ' . $rel_def['lhs_module']);
815 if (isset($rel_def['rhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['rhs_module'])])) {
816 $GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' rhs module is missing ' . $rel_def['rhs_module']);
821 //check whether relationship exists or not first.
822 if (Relationship::exists($rel_name,$db))
824 $GLOBALS['log']->debug('Skipping, reltionship already exists '.$rel_name);
828 $seed = BeanFactory::getBean("Relationships");
829 $keys = array_keys($seed->field_defs);
831 foreach($keys as $key)
835 $toInsert[$key] = create_guid();
837 else if ($key == "relationship_name")
839 $toInsert[$key] = $rel_name;
841 else if (isset($rel_def[$key]))
843 $toInsert[$key] = $rel_def[$key];
845 //todo specify defaults if meta not defined.
849 $column_list = implode(",", array_keys($toInsert));
850 $value_list = "'" . implode("','", array_values($toInsert)) . "'";
852 //create the record. todo add error check.
853 $insert_string = "INSERT into relationships (" .$column_list. ") values (".$value_list.")";
854 $db->query($insert_string, true);
861 //log informational message stating no relationships meta was set for this bean.
867 * This method has been deprecated.
868 * @see createRelationshipMeta()
869 * @deprecated 4.5.1 - Nov 14, 2006
872 function create_relationship_meta($key,&$db,&$log,$tablename,$dictionary,$module_dir)
874 SugarBean::createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
879 * Loads the request relationship. This method should be called before performing any operations on the related data.
881 * This method searches the vardef array for the requested attribute's definition. If the attribute is of the type
882 * link then it creates a similary named variable and loads the relationship definition.
884 * @param string $rel_name relationship/attribute name.
887 function load_relationship($rel_name)
889 $GLOBALS['log']->debug("SugarBean[{$this->object_name}].load_relationships, Loading relationship (".$rel_name.").");
891 if (empty($rel_name))
893 $GLOBALS['log']->error("SugarBean.load_relationships, Null relationship name passed.");
896 $fieldDefs = $this->getFieldDefinitions();
898 //find all definitions of type link.
899 if (!empty($fieldDefs[$rel_name]))
901 //initialize a variable of type Link
902 require_once('data/Link2.php');
903 $class = load_link_class($fieldDefs[$rel_name]);
904 if (isset($this->$rel_name) && $this->$rel_name instanceof $class) {
907 //if rel_name is provided, search the fieldef array keys by name.
908 if (isset($fieldDefs[$rel_name]['type']) && $fieldDefs[$rel_name]['type'] == 'link')
910 if ($class == "Link2")
911 $this->$rel_name = new $class($rel_name, $this);
913 $this->$rel_name = new $class($fieldDefs[$rel_name]['relationship'], $this, $fieldDefs[$rel_name]);
915 if (empty($this->$rel_name) ||
916 (method_exists($this->$rel_name, "loadedSuccesfully") && !$this->$rel_name->loadedSuccesfully()))
918 unset($this->$rel_name);
924 $GLOBALS['log']->debug("SugarBean.load_relationships, Error Loading relationship (".$rel_name.")");
929 * Loads all attributes of type link.
931 * DO NOT CALL THIS FUNCTION IF YOU CAN AVOID IT. Please use load_relationship directly instead.
933 * Method searches the implmenting module's vardef file for attributes of type link, and for each attribute
934 * create a similary named variable and load the relationship definition.
938 * Internal function, do not override.
940 function load_relationships()
942 $GLOBALS['log']->debug("SugarBean.load_relationships, Loading all relationships of type link.");
943 $linked_fields=$this->get_linked_fields();
944 foreach($linked_fields as $name=>$properties)
946 $this->load_relationship($name);
951 * Returns an array of beans of related data.
953 * For instance, if an account is related to 10 contacts , this function will return an array of contacts beans (10)
954 * with each bean representing a contact record.
955 * Method will load the relationship if not done so already.
957 * @param string $field_name relationship to be loaded.
958 * @param string $bean name class name of the related bean.
959 * @param array $sort_array optional, unused
960 * @param int $begin_index Optional, default 0, unused.
961 * @param int $end_index Optional, default -1
962 * @param int $deleted Optional, Default 0, 0 adds deleted=0 filter, 1 adds deleted=1 filter.
963 * @param string $optional_where, Optional, default empty.
965 * Internal function, do not override.
967 function get_linked_beans($field_name,$bean_name, $sort_array = array(), $begin_index = 0, $end_index = -1,
968 $deleted=0, $optional_where="")
970 //if bean_name is Case then use aCase
971 if($bean_name=="Case")
972 $bean_name = "aCase";
974 if($this->load_relationship($field_name)) {
975 if ($this->$field_name instanceof Link) {
976 // some classes are still based on Link, e.g. TeamSetLink
977 return array_values($this->$field_name->getBeans(new $bean_name(), $sort_array, $begin_index, $end_index, $deleted, $optional_where));
980 return array_values($this->$field_name->getBeans());
988 * Returns an array of fields that are of type link.
990 * @return array List of fields.
992 * Internal function, do not override.
994 function get_linked_fields()
997 $linked_fields=array();
999 // require_once('data/Link.php');
1001 $fieldDefs = $this->getFieldDefinitions();
1003 //find all definitions of type link.
1004 if (!empty($fieldDefs))
1006 foreach ($fieldDefs as $name=>$properties)
1008 if (array_search('link',$properties) === 'type')
1010 $linked_fields[$name]=$properties;
1015 return $linked_fields;
1019 * Returns an array of fields that are able to be Imported into
1020 * i.e. 'importable' not set to 'false'
1022 * @return array List of fields.
1024 * Internal function, do not override.
1026 function get_importable_fields()
1028 $importableFields = array();
1030 $fieldDefs= $this->getFieldDefinitions();
1032 if (!empty($fieldDefs)) {
1033 foreach ($fieldDefs as $key=>$value_array) {
1034 if ( (isset($value_array['importable'])
1035 && (is_string($value_array['importable']) && $value_array['importable'] == 'false'
1036 || is_bool($value_array['importable']) && $value_array['importable'] == false))
1037 || (isset($value_array['type']) && $value_array['type'] == 'link')
1038 || (isset($value_array['auto_increment'])
1039 && ($value_array['type'] == true || $value_array['type'] == 'true')) ) {
1040 // only allow import if we force it
1041 if (isset($value_array['importable'])
1042 && (is_string($value_array['importable']) && $value_array['importable'] == 'true'
1043 || is_bool($value_array['importable']) && $value_array['importable'] == true)) {
1044 $importableFields[$key]=$value_array;
1048 $importableFields[$key]=$value_array;
1053 return $importableFields;
1057 * Returns an array of fields that are of type relate.
1059 * @return array List of fields.
1061 * Internal function, do not override.
1063 function get_related_fields()
1066 $related_fields=array();
1068 // require_once('data/Link.php');
1070 $fieldDefs = $this->getFieldDefinitions();
1072 //find all definitions of type link.
1073 if (!empty($fieldDefs))
1075 foreach ($fieldDefs as $name=>$properties)
1077 if (array_search('relate',$properties) === 'type')
1079 $related_fields[$name]=$properties;
1084 return $related_fields;
1088 * Returns an array of fields that are required for import
1092 function get_import_required_fields()
1094 $importable_fields = $this->get_importable_fields();
1095 $required_fields = array();
1097 foreach ( $importable_fields as $name => $properties ) {
1098 if ( isset($properties['importable']) && is_string($properties['importable']) && $properties['importable'] == 'required' ) {
1099 $required_fields[$name] = $properties;
1103 return $required_fields;
1107 * Iterates through all the relationships and deletes all records for reach relationship.
1109 * @param string $id Primary key value of the parent reocrd
1111 function delete_linked($id)
1113 $linked_fields=$this->get_linked_fields();
1114 foreach ($linked_fields as $name => $value)
1116 if ($this->load_relationship($name))
1118 $this->$name->delete($id);
1122 $GLOBALS['log']->fatal("error loading relationship $name");
1128 * Creates tables for the module implementing the class.
1129 * If you override this function make sure that your code can handles table creation.
1132 function create_tables()
1136 $key = $this->getObjectName();
1137 if (!array_key_exists($key, $dictionary))
1139 $GLOBALS['log']->fatal("create_tables: Metadata for table ".$this->table_name. " does not exist");
1140 display_notice("meta data absent for table ".$this->table_name." keyed to $key ");
1144 if(!$this->db->tableExists($this->table_name))
1146 $this->db->createTable($this);
1147 if($this->bean_implements('ACL')){
1148 if(!empty($this->acltype)){
1149 ACLAction::addActions($this->getACLCategory(), $this->acltype);
1151 ACLAction::addActions($this->getACLCategory());
1157 echo "Table already exists : $this->table_name<br>";
1159 if($this->is_AuditEnabled()){
1160 if (!$this->db->tableExists($this->get_audit_table_name())) {
1161 $this->create_audit_table();
1169 * Delete the primary table for the module implementing the class.
1170 * If custom fields were added to this table/module, the custom table will be removed too, along with the cache
1171 * entries that define the custom fields.
1174 function drop_tables()
1177 $key = $this->getObjectName();
1178 if (!array_key_exists($key, $dictionary))
1180 $GLOBALS['log']->fatal("drop_tables: Metadata for table ".$this->table_name. " does not exist");
1181 echo "meta data absent for table ".$this->table_name."<br>\n";
1183 if(empty($this->table_name))return;
1184 if ($this->db->tableExists($this->table_name))
1186 $this->db->dropTable($this);
1187 if ($this->db->tableExists($this->table_name. '_cstm'))
1189 $this->db->dropTableName($this->table_name. '_cstm');
1190 DynamicField::deleteCache();
1192 if ($this->db->tableExists($this->get_audit_table_name())) {
1193 $this->db->dropTableName($this->get_audit_table_name());
1202 * Loads the definition of custom fields defined for the module.
1203 * Local file system cache is created as needed.
1205 * @param string $module_name setting up custom fields for this module.
1206 * @param boolean $clean_load Optional, default true, rebuilds the cache if set to true.
1208 function setupCustomFields($module_name, $clean_load=true)
1210 $this->custom_fields = new DynamicField($module_name);
1211 $this->custom_fields->setup($this);
1216 * Cleans char, varchar, text, etc. fields of XSS type materials
1218 function cleanBean() {
1219 foreach($this->field_defs as $key => $def) {
1221 if (isset($def['type'])) {
1224 if(isset($def['dbType']))
1225 $type .= $def['dbType'];
1227 if((strpos($type, 'char') !== false ||
1228 strpos($type, 'text') !== false ||
1232 $str = from_html($this->$key);
1233 // Julian's XSS cleaner
1234 $potentials = clean_xss($str, false);
1236 if(is_array($potentials) && !empty($potentials)) {
1237 foreach($potentials as $bad) {
1238 $str = str_replace($bad, "", $str);
1240 $this->$key = to_html($str);
1247 * Implements a generic insert and update logic for any SugarBean
1248 * This method only works for subclasses that implement the same variable names.
1249 * This method uses the presence of an id field that is not null to signify and update.
1250 * The id field should not be set otherwise.
1252 * @param boolean $check_notify Optional, default false, if set to true assignee of the record is notified via email.
1253 * @todo Add support for field type validation and encoding of parameters.
1255 function save($check_notify = FALSE)
1257 $this->in_save = true;
1258 // cn: SECURITY - strip XSS potential vectors
1260 // This is used so custom/3rd-party code can be upgraded with fewer issues, this will be removed in a future release
1261 $this->fixUpFormatting();
1263 global $current_user, $action;
1266 if(empty($this->id))
1271 if ( $this->new_with_id == true )
1275 if(empty($this->date_modified) || $this->update_date_modified)
1277 $this->date_modified = $GLOBALS['timedate']->nowDb();
1280 $this->_checkOptimisticLocking($action, $isUpdate);
1282 if(!empty($this->modified_by_name)) $this->old_modified_by_name = $this->modified_by_name;
1283 if($this->update_modified_by)
1285 $this->modified_user_id = 1;
1287 if (!empty($current_user))
1289 $this->modified_user_id = $current_user->id;
1290 $this->modified_by_name = $current_user->user_name;
1293 if ($this->deleted != 1)
1297 if (empty($this->date_entered))
1299 $this->date_entered = $this->date_modified;
1301 if($this->set_created_by == true)
1303 // created by should always be this user
1304 $this->created_by = (isset($current_user)) ? $current_user->id : "";
1306 if( $this->new_with_id == false)
1308 $this->id = create_guid();
1314 require_once("data/BeanFactory.php");
1315 BeanFactory::registerBean($this->module_name, $this);
1317 if (empty($GLOBALS['updating_relationships']) && empty($GLOBALS['saving_relationships']) && empty ($GLOBALS['resavingRelatedBeans']))
1319 $GLOBALS['saving_relationships'] = true;
1320 // let subclasses save related field changes
1321 $this->save_relationship_changes($isUpdate);
1322 $GLOBALS['saving_relationships'] = false;
1324 if($isUpdate && !$this->update_date_entered)
1326 unset($this->date_entered);
1328 // call the custom business logic
1329 $custom_logic_arguments['check_notify'] = $check_notify;
1332 $this->call_custom_logic("before_save", $custom_logic_arguments);
1333 unset($custom_logic_arguments);
1335 if(isset($this->custom_fields))
1337 $this->custom_fields->bean = $this;
1338 $this->custom_fields->save($isUpdate);
1341 // use the db independent query generator
1342 $this->preprocess_fields_on_save();
1344 //construct the SQL to create the audit record if auditing is enabled.
1345 $dataChanges=array();
1346 if ($this->is_AuditEnabled()) {
1347 if ($isUpdate && !isset($this->fetched_row)) {
1348 $GLOBALS['log']->debug('Auditing: Retrieve was not called, audit record will not be created.');
1350 $dataChanges=$this->db->getDataChanges($this);
1354 $this->_sendNotifications($check_notify);
1357 $this->db->update($this);
1359 $this->db->insert($this);
1362 if (!empty($dataChanges) && is_array($dataChanges))
1364 foreach ($dataChanges as $change)
1366 $this->db->save_audit_records($this,$change);
1371 if (empty($GLOBALS['resavingRelatedBeans'])){
1372 SugarRelationship::resaveRelatedBeans();
1376 //If we aren't in setup mode and we have a current user and module, then we track
1377 if(isset($GLOBALS['current_user']) && isset($this->module_dir))
1379 $this->track_view($current_user->id, $this->module_dir, 'save');
1382 $this->call_custom_logic('after_save', '');
1384 //Now that the record has been saved, we don't want to insert again on further saves
1385 $this->new_with_id = false;
1386 $this->in_save = false;
1392 * Performs a check if the record has been modified since the specified date
1394 * @param date $date Datetime for verification
1395 * @param string $modified_user_id User modified by
1397 function has_been_modified_since($date, $modified_user_id)
1399 global $current_user;
1400 $date = $this->db->convert($this->db->quoted($date), 'datetime');
1401 if (isset($current_user))
1403 $query = "SELECT date_modified FROM $this->table_name WHERE id='$this->id' AND modified_user_id != '$current_user->id'
1404 AND (modified_user_id != '$modified_user_id' OR date_modified > $date)";
1405 $result = $this->db->query($query);
1407 if($this->db->fetchByAssoc($result))
1416 * Determines which users receive a notification
1418 function get_notification_recipients() {
1419 $notify_user = new User();
1420 $notify_user->retrieve($this->assigned_user_id);
1421 $this->new_assigned_user_name = $notify_user->full_name;
1423 $GLOBALS['log']->info("Notifications: recipient is $this->new_assigned_user_name");
1425 $user_list = array($notify_user);
1428 //send notifications to followers, but ensure to not query for the assigned_user.
1429 return SugarFollowing::getFollowers($this, $notify_user);
1434 * Handles sending out email notifications when items are first assigned to users
1436 * @param string $notify_user user to notify
1437 * @param string $admin the admin user that sends out the notification
1439 function send_assignment_notifications($notify_user, $admin)
1441 global $current_user;
1443 if(($this->object_name == 'Meeting' || $this->object_name == 'Call') || $notify_user->receive_notifications)
1445 $sendToEmail = $notify_user->emailAddress->getPrimaryAddress($notify_user);
1447 if(empty($sendToEmail)) {
1448 $GLOBALS['log']->warn("Notifications: no e-mail address set for user {$notify_user->user_name}, cancelling send");
1452 $notify_mail = $this->create_notification_email($notify_user);
1453 $notify_mail->setMailerForSystem();
1455 if(empty($admin->settings['notify_send_from_assigning_user'])) {
1456 $notify_mail->From = $admin->settings['notify_fromaddress'];
1457 $notify_mail->FromName = (empty($admin->settings['notify_fromname'])) ? "" : $admin->settings['notify_fromname'];
1459 // Send notifications from the current user's e-mail (ifset)
1460 $fromAddress = $current_user->emailAddress->getReplyToAddress($current_user);
1461 $fromAddress = !empty($fromAddress) ? $fromAddress : $admin->settings['notify_fromaddress'];
1462 $notify_mail->From = $fromAddress;
1463 //Use the users full name is available otherwise default to system name
1464 $from_name = !empty($admin->settings['notify_fromname']) ? $admin->settings['notify_fromname'] : "";
1465 $from_name = !empty($current_user->full_name) ? $current_user->full_name : $from_name;
1466 $notify_mail->FromName = $from_name;
1469 $oe = new OutboundEmail();
1470 $oe = $oe->getUserMailerSettings($current_user);
1471 //only send if smtp server is defined
1473 $smtpVerified = false;
1475 //first check the user settings
1476 if(!empty($oe->mail_smtpserver)){
1477 $smtpVerified = true;
1480 //if still not verified, check against the system settings
1481 if (!$smtpVerified){
1482 $oe = $oe->getSystemMailerSettings();
1483 if(!empty($oe->mail_smtpserver)){
1484 $smtpVerified = true;
1487 //if smtp was not verified against user or system, then do not send out email
1488 if (!$smtpVerified){
1489 $GLOBALS['log']->fatal("Notifications: error sending e-mail, smtp server was not found ");
1494 if(!$notify_mail->Send()) {
1495 $GLOBALS['log']->fatal("Notifications: error sending e-mail (method: {$notify_mail->Mailer}), (error: {$notify_mail->ErrorInfo})");
1497 $GLOBALS['log']->fatal("Notifications: e-mail successfully sent");
1505 * This function handles create the email notifications email.
1506 * @param string $notify_user the user to send the notification email to
1508 function create_notification_email($notify_user) {
1509 global $sugar_version;
1510 global $sugar_config;
1511 global $app_list_strings;
1512 global $current_user;
1515 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
1518 require_once("include/SugarPHPMailer.php");
1520 $notify_address = $notify_user->emailAddress->getPrimaryAddress($notify_user);
1521 $notify_name = $notify_user->full_name;
1522 $GLOBALS['log']->debug("Notifications: user has e-mail defined");
1524 $notify_mail = new SugarPHPMailer();
1525 $notify_mail->AddAddress($notify_address,$locale->translateCharsetMIME(trim($notify_name), 'UTF-8', $OBCharset));
1527 if(empty($_SESSION['authenticated_user_language'])) {
1528 $current_language = $sugar_config['default_language'];
1530 $current_language = $_SESSION['authenticated_user_language'];
1532 $xtpl = new XTemplate(get_notify_template_file($current_language));
1533 if($this->module_dir == "Cases") {
1534 $template_name = "Case"; //we should use Case, you can refer to the en_us.notify_template.html.
1537 $template_name = $beanList[$this->module_dir]; //bug 20637, in workflow this->object_name = strange chars.
1540 $this->current_notify_user = $notify_user;
1542 if(in_array('set_notification_body', get_class_methods($this))) {
1543 $xtpl = $this->set_notification_body($xtpl, $this);
1545 $xtpl->assign("OBJECT", $this->object_name);
1546 $template_name = "Default";
1548 if(!empty($_SESSION["special_notification"]) && $_SESSION["special_notification"]) {
1549 $template_name = $beanList[$this->module_dir].'Special';
1551 if($this->special_notification) {
1552 $template_name = $beanList[$this->module_dir].'Special';
1554 $xtpl->assign("ASSIGNED_USER", $this->new_assigned_user_name);
1555 $xtpl->assign("ASSIGNER", $current_user->name);
1558 if(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
1559 $port = $_SERVER['SERVER_PORT'];
1562 if (!isset($_SERVER['HTTP_HOST'])) {
1563 $_SERVER['HTTP_HOST'] = '';
1566 $httpHost = $_SERVER['HTTP_HOST'];
1568 if($colon = strpos($httpHost, ':')) {
1569 $httpHost = substr($httpHost, 0, $colon);
1572 $parsedSiteUrl = parse_url($sugar_config['site_url']);
1573 $host = $parsedSiteUrl['host'];
1574 if(!isset($parsedSiteUrl['port'])) {
1575 $parsedSiteUrl['port'] = 80;
1578 $port = ($parsedSiteUrl['port'] != 80) ? ":".$parsedSiteUrl['port'] : '';
1579 $path = !empty($parsedSiteUrl['path']) ? $parsedSiteUrl['path'] : "";
1580 $cleanUrl = "{$parsedSiteUrl['scheme']}://{$host}{$port}{$path}";
1582 $xtpl->assign("URL", $cleanUrl."/index.php?module={$this->module_dir}&action=DetailView&record={$this->id}");
1583 $xtpl->assign("SUGAR", "Sugar v{$sugar_version}");
1584 $xtpl->parse($template_name);
1585 $xtpl->parse($template_name . "_Subject");
1587 $notify_mail->Body = from_html(trim($xtpl->text($template_name)));
1588 $notify_mail->Subject = from_html($xtpl->text($template_name . "_Subject"));
1590 // cn: bug 8568 encode notify email in User's outbound email encoding
1591 $notify_mail->prepForOutbound();
1593 return $notify_mail;
1597 * This function is a good location to save changes that have been made to a relationship.
1598 * This should be overriden in subclasses that have something to save.
1600 * @param $is_update true if this save is an update.
1602 function save_relationship_changes($is_update, $exclude=array())
1604 $new_rel_id = false;
1605 $new_rel_link = false;
1607 //this allows us to dynamically relate modules without adding it to the relationship_fields array
1608 if(!empty($_REQUEST['relate_id']) && !empty($_REQUEST['relate_to']) && !in_array($_REQUEST['relate_to'], $exclude) && $_REQUEST['relate_id'] != $this->id){
1609 $new_rel_id = $_REQUEST['relate_id'];
1610 $new_rel_relname = $_REQUEST['relate_to'];
1611 if(!empty($this->in_workflow) && !empty($this->not_use_rel_in_req)) {
1612 $new_rel_id = !empty($this->new_rel_id) ? $this->new_rel_id : '';
1613 $new_rel_relname = !empty($this->new_rel_relname) ? $this->new_rel_relname : '';
1615 $new_rel_link = $new_rel_relname;
1616 //Try to find the link in this bean based on the relationship
1617 foreach ( $this->field_defs as $key => $def ) {
1618 if (isset($def['type']) && $def['type'] == 'link'
1619 && isset($def['relationship']) && $def['relationship'] == $new_rel_relname) {
1620 $new_rel_link = $key;
1626 // First we handle the preset fields listed in the fixed relationship_fields array hardcoded into the OOB beans
1627 // TODO: remove this mechanism and replace with mechanism exclusively based on the vardefs
1628 if (isset($this->relationship_fields) && is_array($this->relationship_fields))
1630 foreach ($this->relationship_fields as $id=>$rel_name)
1633 if(in_array($id, $exclude))continue;
1635 if(!empty($this->$id))
1637 $GLOBALS['log']->debug('save_relationship_changes(): From relationship_field array - adding a relationship record: '.$rel_name . ' = ' . $this->$id);
1638 //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
1639 if($this->$id == $new_rel_id){
1640 $new_rel_id = false;
1642 $this->load_relationship($rel_name);
1643 $this->$rel_name->add($this->$id);
1648 //if before value is not empty then attempt to delete relationship
1649 if(!empty($this->rel_fields_before_value[$id]))
1651 $GLOBALS['log']->debug('save_relationship_changes(): From relationship_field array - attempting to remove the relationship record, using relationship attribute'.$rel_name);
1652 $this->load_relationship($rel_name);
1653 $this->$rel_name->delete($this->id,$this->rel_fields_before_value[$id]);
1659 /* Next, we'll attempt to update all of the remaining relate fields in the vardefs that have 'save' set in their field_def
1660 Only the 'save' fields should be saved as some vardef entries today are not for display only purposes and break the application if saved
1661 If the vardef has entries for field <a> of type relate, where a->id_name = <b> and field <b> of type link
1662 then we receive a value for b from the MVC in the _REQUEST, and it should be set in the bean as $this->$b
1665 foreach ( $this->field_defs as $def )
1667 if ($def [ 'type' ] == 'relate' && isset ( $def [ 'id_name'] ) && isset ( $def [ 'link'] ) && isset ( $def[ 'save' ]) )
1669 if ( in_array( $def['id_name'], $exclude) || in_array( $def['id_name'], $this->relationship_fields ) )
1670 continue ; // continue to honor the exclude array and exclude any relationships that will be handled by the relationship_fields mechanism
1672 $linkField = $def [ 'link' ] ;
1673 if (isset( $this->field_defs[$linkField ] ))
1675 $linkfield = $this->field_defs[$linkField] ;
1677 if ($this->load_relationship ( $linkField))
1679 $idName = $def['id_name'];
1681 if (!empty($this->rel_fields_before_value[$idName]) && empty($this->$idName))
1683 //if before value is not empty then attempt to delete relationship
1684 $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' ]]}");
1685 $this->$def ['link' ]->delete($this->id, $this->rel_fields_before_value[$def [ 'id_name' ]] );
1688 if (!empty($this->$idName) && is_string($this->$idName))
1690 $GLOBALS['log']->debug("save_relationship_changes(): From field_defs - attempting to add a relationship record - {$def [ 'link' ]} = {$this->$def [ 'id_name' ]}" );
1692 $this->$linkField->add($this->$idName);
1695 $GLOBALS['log']->fatal("Failed to load relationship {$linkField} while saving {$this->module_dir}");
1701 // Finally, we update a field listed in the _REQUEST['*/relate_id']/_REQUEST['relate_to'] mechanism (if it hasn't already been updated above)
1702 if(!empty($new_rel_id)){
1704 if($this->load_relationship($new_rel_link)){
1705 $this->$new_rel_link->add($new_rel_id);
1708 $lower_link = strtolower($new_rel_link);
1709 if($this->load_relationship($lower_link)){
1710 $this->$lower_link->add($new_rel_id);
1713 require_once('data/Link2.php');
1714 $rel = Relationship::retrieve_by_modules($new_rel_link, $this->module_dir, $GLOBALS['db'], 'many-to-many');
1717 foreach($this->field_defs as $field=>$def){
1718 if($def['type'] == 'link' && !empty($def['relationship']) && $def['relationship'] == $rel){
1719 $this->load_relationship($field);
1720 $this->$field->add($new_rel_id);
1726 //ok so we didn't find it in the field defs let's save it anyway if we have the relationshp
1728 $this->$rel=new Link2($rel, $this, array());
1729 $this->$rel->add($new_rel_id);
1738 * This function retrieves a record of the appropriate type from the DB.
1739 * It fills in all of the fields from the DB into the object it was called on.
1741 * @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.
1742 * @return this - The object that it was called apon or null if exactly 1 record was not found.
1746 function check_date_relationships_load()
1748 global $disable_date_format;
1750 if (empty($timedate))
1751 $timedate=TimeDate::getInstance();
1753 if(empty($this->field_defs))
1757 foreach($this->field_defs as $fieldDef)
1759 $field = $fieldDef['name'];
1760 if(!isset($this->processed_dates_times[$field]))
1762 $this->processed_dates_times[$field] = '1';
1763 if(empty($this->$field)) continue;
1764 if($field == 'date_modified' || $field == 'date_entered')
1766 $this->$field = $this->db->fromConvert($this->$field, 'datetime');
1767 if(empty($disable_date_format)) {
1768 $this->$field = $timedate->to_display_date_time($this->$field);
1771 elseif(isset($this->field_name_map[$field]['type']))
1773 $type = $this->field_name_map[$field]['type'];
1775 if($type == 'relate' && isset($this->field_name_map[$field]['custom_module']))
1777 $type = $this->field_name_map[$field]['type'];
1782 if($this->$field == '0000-00-00')
1785 } elseif(!empty($this->field_name_map[$field]['rel_field']))
1787 $rel_field = $this->field_name_map[$field]['rel_field'];
1789 if(!empty($this->$rel_field))
1791 if(empty($disable_date_format)) {
1792 $mergetime = $timedate->merge_date_time($this->$field,$this->$rel_field);
1793 $this->$field = $timedate->to_display_date($mergetime);
1794 $this->$rel_field = $timedate->to_display_time($mergetime);
1800 if(empty($disable_date_format)) {
1801 $this->$field = $timedate->to_display_date($this->$field, false);
1804 } elseif($type == 'datetime' || $type == 'datetimecombo')
1806 if($this->$field == '0000-00-00 00:00:00')
1812 if(empty($disable_date_format)) {
1813 $this->$field = $timedate->to_display_date_time($this->$field, true, true);
1816 } elseif($type == 'time')
1818 if($this->$field == '00:00:00')
1823 //$this->$field = from_db_convert($this->$field, 'time');
1824 if(empty($this->field_name_map[$field]['rel_field']) && empty($disable_date_format))
1826 $this->$field = $timedate->to_display_time($this->$field,true, false);
1829 } elseif($type == 'encrypt' && empty($disable_date_format)){
1830 $this->$field = $this->decrypt_after_retrieve($this->$field);
1838 * This function processes the fields before save.
1839 * Interal function, do not override.
1841 function preprocess_fields_on_save()
1843 $GLOBALS['log']->deprecated('SugarBean.php: preprocess_fields_on_save() is deprecated');
1847 * Removes formatting from values posted from the user interface.
1848 * It only unformats numbers. Function relies on user/system prefernce for format strings.
1850 * Internal Function, do not override.
1852 function unformat_all_fields()
1854 $GLOBALS['log']->deprecated('SugarBean.php: unformat_all_fields() is deprecated');
1858 * This functions adds formatting to all number fields before presenting them to user interface.
1860 * Internal function, do not override.
1862 function format_all_fields()
1864 $GLOBALS['log']->deprecated('SugarBean.php: format_all_fields() is deprecated');
1867 function format_field($fieldDef)
1869 $GLOBALS['log']->deprecated('SugarBean.php: format_field() is deprecated');
1873 * Function corrects any bad formatting done by 3rd party/custom code
1875 * 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
1877 function fixUpFormatting()
1880 static $boolean_false_values = array('off', 'false', '0', 'no');
1883 foreach($this->field_defs as $field=>$def)
1885 if ( !isset($this->$field) ) {
1888 if ( (isset($def['source'])&&$def['source']=='non-db') || $field == 'deleted' ) {
1891 if ( isset($this->fetched_row[$field]) && $this->$field == $this->fetched_row[$field] ) {
1892 // Don't hand out warnings because the field was untouched between retrieval and saving, most database drivers hand pretty much everything back as strings.
1895 $reformatted = false;
1896 switch($def['type']) {
1898 case 'datetimecombo':
1899 if(empty($this->$field)) break;
1900 if ($this->$field == 'NULL') {
1904 if ( ! preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/',$this->$field) ) {
1905 // This appears to be formatted in user date/time
1906 $this->$field = $timedate->to_db($this->$field);
1907 $reformatted = true;
1911 if(empty($this->$field)) break;
1912 if ($this->$field == 'NULL') {
1916 if ( ! preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$this->$field) ) {
1917 // This date appears to be formatted in the user's format
1918 $this->$field = $timedate->to_db_date($this->$field, false);
1919 $reformatted = true;
1923 if(empty($this->$field)) break;
1924 if ($this->$field == 'NULL') {
1928 if ( preg_match('/(am|pm)/i',$this->$field) ) {
1929 // This time appears to be formatted in the user's format
1930 $this->$field = $timedate->fromUserTime($this->$field)->format(TimeDate::DB_TIME_FORMAT);
1931 $reformatted = true;
1938 if ( $this->$field === '' || $this->$field == NULL || $this->$field == 'NULL') {
1941 if ( is_string($this->$field) ) {
1942 $this->$field = (float)unformat_number($this->$field);
1943 $reformatted = true;
1952 if ( $this->$field === '' || $this->$field == NULL || $this->$field == 'NULL') {
1955 if ( is_string($this->$field) ) {
1956 $this->$field = (int)unformat_number($this->$field);
1957 $reformatted = true;
1961 if (empty($this->$field)) {
1962 $this->$field = false;
1963 } else if(true === $this->$field || 1 == $this->$field) {
1964 $this->$field = true;
1965 } else if(in_array(strval($this->$field), $boolean_false_values)) {
1966 $this->$field = false;
1967 $reformatted = true;
1969 $this->$field = true;
1970 $reformatted = true;
1974 $this->$field = $this->encrpyt_before_save($this->$field);
1977 if ( $reformatted ) {
1978 $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');
1985 * Function fetches a single row of data given the primary key value.
1987 * The fetched data is then set into the bean. The function also processes the fetched data by formattig
1988 * date/time and numeric values.
1990 * @param string $id Optional, default -1, is set to -1 id value from the bean is used, else, passed value is used
1991 * @param boolean $encode Optional, default true, encodes the values fetched from the database.
1992 * @param boolean $deleted Optional, default true, if set to false deleted filter will not be added.
1994 * Internal function, do not override.
1996 function retrieve($id = -1, $encode=true,$deleted=true)
1999 $custom_logic_arguments['id'] = $id;
2000 $this->call_custom_logic('before_retrieve', $custom_logic_arguments);
2006 if(isset($this->custom_fields))
2008 $custom_join = $this->custom_fields->getJOIN();
2011 $custom_join = false;
2015 $query = "SELECT $this->table_name.*". $custom_join['select']. " FROM $this->table_name ";
2019 $query = "SELECT $this->table_name.* FROM $this->table_name ";
2024 $query .= ' ' . $custom_join['join'];
2026 $query .= " WHERE $this->table_name.id = ".$this->db->quoted($id);
2027 if ($deleted) $query .= " AND $this->table_name.deleted=0";
2028 $GLOBALS['log']->debug("Retrieve $this->object_name : ".$query);
2029 $result = $this->db->limitQuery($query,0,1,true, "Retrieving record by id $this->table_name:$id found ");
2035 $row = $this->db->fetchByAssoc($result, $encode);
2041 //make copy of the fetched row for construction of audit record and for business logic/workflow
2042 $row = $this->convertRow($row);
2043 $this->fetched_row=$row;
2044 $this->populateFromRow($row);
2046 global $module, $action;
2047 //Just to get optimistic locking working for this release
2048 if($this->optimistic_lock && $module == $this->module_dir && $action =='EditView' )
2050 $_SESSION['o_lock_id']= $id;
2051 $_SESSION['o_lock_dm']= $this->date_modified;
2052 $_SESSION['o_lock_on'] = $this->object_name;
2054 $this->processed_dates_times = array();
2055 $this->check_date_relationships_load();
2059 $this->custom_fields->fill_relationships();
2062 $this->fill_in_additional_detail_fields();
2063 $this->fill_in_relationship_fields();
2064 //make a copy of fields in the relatiosnhip_fields array. these field values will be used to
2065 //clear relatioship.
2066 foreach ( $this->field_defs as $key => $def )
2068 if ($def [ 'type' ] == 'relate' && isset ( $def [ 'id_name'] ) && isset ( $def [ 'link'] ) && isset ( $def[ 'save' ])) {
2069 if (isset($this->$key)) {
2070 $this->rel_fields_before_value[$key]=$this->$key;
2071 if (isset($this->$def [ 'id_name']))
2072 $this->rel_fields_before_value[$def [ 'id_name']]=$this->$def [ 'id_name'];
2075 $this->rel_fields_before_value[$key]=null;
2078 if (isset($this->relationship_fields) && is_array($this->relationship_fields))
2080 foreach ($this->relationship_fields as $rel_id=>$rel_name)
2082 if (isset($this->$rel_id))
2083 $this->rel_fields_before_value[$rel_id]=$this->$rel_id;
2085 $this->rel_fields_before_value[$rel_id]=null;
2089 // call the custom business logic
2090 $custom_logic_arguments['id'] = $id;
2091 $custom_logic_arguments['encode'] = $encode;
2092 $this->call_custom_logic("after_retrieve", $custom_logic_arguments);
2093 unset($custom_logic_arguments);
2098 * Sets value from fetched row into the bean.
2100 * @param array $row Fetched row
2101 * @todo loop through vardefs instead
2102 * @internal runs into an issue when populating from field_defs for users - corrupts user prefs
2104 * Internal function, do not override.
2106 function populateFromRow($row)
2109 foreach($this->field_defs as $field=>$field_value)
2111 if($field == 'user_preferences' && $this->module_dir == 'Users')
2113 if(isset($row[$field]))
2115 $this->$field = $row[$field];
2116 $owner = $field . '_owner';
2117 if(!empty($row[$owner])){
2118 $this->$owner = $row[$owner];
2123 $this->$field = $nullvalue;
2131 * Add any required joins to the list count query. The joins are required if there
2132 * is a field in the $where clause that needs to be joined.
2134 * @param string $query
2135 * @param string $where
2137 * Internal Function, do Not override.
2139 function add_list_count_joins(&$query, $where)
2141 $custom_join = $this->custom_fields->getJOIN();
2144 $query .= $custom_join['join'];
2150 * Changes the select expression of the given query to be 'count(*)' so you
2151 * can get the number of items the query will return. This is used to
2152 * populate the upper limit on ListViews.
2154 * @param string $query Select query string
2155 * @return string count query
2157 * Internal function, do not override.
2159 function create_list_count_query($query)
2161 // remove the 'order by' clause which is expected to be at the end of the query
2162 $pattern = '/\sORDER BY.*/is'; // ignores the case
2164 $query = preg_replace($pattern, $replacement, $query);
2165 //handle distinct clause
2167 if(substr_count(strtolower($query), 'distinct')){
2168 if (!empty($this->seed) && !empty($this->seed->table_name ))
2169 $star = 'DISTINCT ' . $this->seed->table_name . '.id';
2171 $star = 'DISTINCT ' . $this->table_name . '.id';
2175 // change the select expression to 'count(*)'
2176 $pattern = '/SELECT(.*?)(\s){1}FROM(\s){1}/is'; // ignores the case
2177 $replacement = 'SELECT count(' . $star . ') c FROM ';
2179 //if the passed query has union clause then replace all instances of the pattern.
2180 //this is very rare. I have seen this happening only from projects module.
2181 //in addition to this added a condition that has union clause and uses
2183 if (strstr($query," UNION ALL ") !== false) {
2185 //seperate out all the queries.
2186 $union_qs=explode(" UNION ALL ", $query);
2187 foreach ($union_qs as $key=>$union_query) {
2189 preg_match($pattern, $union_query, $matches);
2190 if (!empty($matches)) {
2191 if (stristr($matches[0], "distinct")) {
2192 if (!empty($this->seed) && !empty($this->seed->table_name ))
2193 $star = 'DISTINCT ' . $this->seed->table_name . '.id';
2195 $star = 'DISTINCT ' . $this->table_name . '.id';
2198 $replacement = 'SELECT count(' . $star . ') c FROM ';
2199 $union_qs[$key] = preg_replace($pattern, $replacement, $union_query,1);
2201 $modified_select_query=implode(" UNION ALL ",$union_qs);
2203 $modified_select_query = preg_replace($pattern, $replacement, $query,1);
2207 return $modified_select_query;
2211 * This function returns a paged list of the current object type. It is intended to allow for
2212 * hopping back and forth through pages of data. It only retrieves what is on the current page.
2214 * @internal This method must be called on a new instance. It trashes the values of all the fields in the current one.
2215 * @param string $order_by
2216 * @param string $where Additional where clause
2217 * @param int $row_offset Optaional,default 0, starting row number
2218 * @param init $limit Optional, default -1
2219 * @param int $max Optional, default -1
2220 * @param boolean $show_deleted Optional, default 0, if set to 1 system will show deleted records.
2221 * @return array Fetched data.
2223 * Internal function, do not override.
2226 function get_list($order_by = "", $where = "", $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $singleSelect=false, $select_fields = array())
2228 $GLOBALS['log']->debug("get_list: order_by = '$order_by' and where = '$where' and limit = '$limit'");
2229 if(isset($_SESSION['show_deleted']))
2233 $order_by=$this->process_order_by($order_by);
2235 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2237 global $current_user;
2238 $owner_where = $this->getOwnerWhere($current_user->id);
2240 //rrs - because $this->getOwnerWhere() can return '' we need to be sure to check for it and
2241 //handle it properly else you could get into a situation where you are create a where stmt like
2243 if(!empty($owner_where)){
2245 $where = $owner_where;
2247 $where .= ' AND '. $owner_where;
2251 $query = $this->create_new_list_query($order_by, $where,$select_fields,array(), $show_deleted,'',false,null,$singleSelect);
2252 return $this->process_list_query($query, $row_offset, $limit, $max, $where);
2256 * Prefixes column names with this bean's table name.
2258 * @param string $order_by Order by clause to be processed
2259 * @param SugarBean $submodule name of the module this order by clause is for
2260 * @return string Processed order by clause
2262 * Internal function, do not override.
2264 function process_order_by ($order_by, $submodule = null)
2266 if (empty($order_by))
2268 //submodule is empty,this is for list object in focus
2269 if (empty($submodule))
2271 $bean_queried = $this;
2275 //submodule is set, so this is for subpanel, use submodule
2276 $bean_queried = $submodule;
2278 $elements = explode(',',$order_by);
2279 foreach ($elements as $key=>$value)
2281 if (strchr($value,'.') === false)
2283 //value might have ascending and descending decorations
2284 $list_column = explode(' ',trim($value));
2285 if (isset($list_column[0]))
2287 $list_column_name=trim($list_column[0]);
2288 if (isset($bean_queried->field_defs[$list_column_name]))
2290 $source=isset($bean_queried->field_defs[$list_column_name]['source']) ? $bean_queried->field_defs[$list_column_name]['source']:'db';
2291 if (empty($bean_queried->field_defs[$list_column_name]['table']) && $source=='db')
2293 $list_column[0] = $bean_queried->table_name .".".$list_column[0] ;
2295 if (empty($bean_queried->field_defs[$list_column_name]['table']) && $source=='custom_fields')
2297 $list_column[0] = $bean_queried->table_name ."_cstm.".$list_column[0] ;
2299 // Bug 38803 - Use CONVERT() function when doing an order by on ntext, text, and image fields
2300 if ($source != 'non-db' && $this->db->isTextType($this->db->getFieldType($bean_queried->field_defs[$list_column_name]))) {
2301 $list_column[0] = $this->db->convert($list_column[0], "text2char");
2303 $value = implode(' ',$list_column);
2305 $GLOBALS['log']->debug("process_order_by: ($list_column[0]) does not have a vardef entry.");
2309 $elements[$key]=$value;
2311 return implode(',', $elements);
2317 * Returns a detail object like retrieving of the current object type.
2319 * It is intended for use in navigation buttons on the DetailView. It will pass an offset and limit argument to the sql query.
2320 * @internal This method must be called on a new instance. It overrides the values of all the fields in the current one.
2322 * @param string $order_by
2323 * @param string $where Additional where clause
2324 * @param int $row_offset Optaional,default 0, starting row number
2325 * @param init $limit Optional, default -1
2326 * @param int $max Optional, default -1
2327 * @param boolean $show_deleted Optioanl, default 0, if set to 1 system will show deleted records.
2328 * @return array Fetched data.
2330 * Internal function, do not override.
2332 function get_detail($order_by = "", $where = "", $offset = 0, $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)
2334 $GLOBALS['log']->debug("get_detail: order_by = '$order_by' and where = '$where' and limit = '$limit' and offset = '$offset'");
2335 if(isset($_SESSION['show_deleted']))
2340 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2342 global $current_user;
2343 $owner_where = $this->getOwnerWhere($current_user->id);
2347 $where = $owner_where;
2351 $where .= ' AND '. $owner_where;
2354 $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted, $offset);
2356 //Add Limit and Offset to query
2357 //$query .= " LIMIT 1 OFFSET $offset";
2359 return $this->process_detail_query($query, $row_offset, $limit, $max, $where, $offset);
2363 * Fetches data from all related tables.
2365 * @param object $child_seed
2366 * @param string $related_field_name relation to fetch data for
2367 * @param string $order_by Optional, default empty
2368 * @param string $where Optional, additional where clause
2369 * @return array Fetched data.
2371 * Internal function, do not override.
2373 function get_related_list($child_seed,$related_field_name, $order_by = "", $where = "",
2374 $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)
2376 global $layout_edit_mode;
2377 if(isset($layout_edit_mode) && $layout_edit_mode)
2379 $response = array();
2380 $child_seed->assign_display_fields($child_seed->module_dir);
2381 $response['list'] = array($child_seed);
2382 $response['row_count'] = 1;
2383 $response['next_offset'] = 0;
2384 $response['previous_offset'] = 0;
2388 $GLOBALS['log']->debug("get_related_list: order_by = '$order_by' and where = '$where' and limit = '$limit'");
2389 if(isset($_SESSION['show_deleted']))
2394 $this->load_relationship($related_field_name);
2395 $query_array = $this->$related_field_name->getQuery(true);
2396 $entire_where = $query_array['where'];
2399 if(empty($entire_where))
2401 $entire_where = ' WHERE ' . $where;
2405 $entire_where .= ' AND ' . $where;
2409 $query = 'SELECT '.$child_seed->table_name.'.* ' . $query_array['from'] . ' ' . $entire_where;
2410 if(!empty($order_by))
2412 $query .= " ORDER BY " . $order_by;
2415 return $child_seed->process_list_query($query, $row_offset, $limit, $max, $where);
2419 protected static function build_sub_queries_for_union($subpanel_list, $subpanel_def, $parentbean, $order_by)
2421 global $layout_edit_mode, $beanFiles, $beanList;
2422 $subqueries = array();
2423 foreach($subpanel_list as $this_subpanel)
2425 if(!$this_subpanel->isDatasourceFunction() || ($this_subpanel->isDatasourceFunction()
2426 && isset($this_subpanel->_instance_properties['generate_select'])
2427 && $this_subpanel->_instance_properties['generate_select']==true))
2429 //the custom query function must return an array with
2430 if ($this_subpanel->isDatasourceFunction()) {
2431 $shortcut_function_name = $this_subpanel->get_data_source_name();
2432 $parameters=$this_subpanel->get_function_parameters();
2433 if (!empty($parameters))
2435 //if the import file function is set, then import the file to call the custom function from
2436 if (is_array($parameters) && isset($parameters['import_function_file'])){
2437 //this call may happen multiple times, so only require if function does not exist
2438 if(!function_exists($shortcut_function_name)){
2439 require_once($parameters['import_function_file']);
2441 //call function from required file
2442 $query_array = $shortcut_function_name($parameters);
2444 //call function from parent bean
2445 $query_array = $parentbean->$shortcut_function_name($parameters);
2450 $query_array = $parentbean->$shortcut_function_name();
2453 $related_field_name = $this_subpanel->get_data_source_name();
2454 if (!$parentbean->load_relationship($related_field_name)){
2455 unset ($parentbean->$related_field_name);
2458 $query_array = $parentbean->$related_field_name->getSubpanelQuery(array(), true);
2460 $table_where = $this_subpanel->get_where();
2461 $where_definition = $query_array['where'];
2463 if(!empty($table_where))
2465 if(empty($where_definition))
2467 $where_definition = $table_where;
2471 $where_definition .= ' AND ' . $table_where;
2475 $submodulename = $this_subpanel->_instance_properties['module'];
2476 $submoduleclass = $beanList[$submodulename];
2477 //require_once($beanFiles[$submoduleclass]);
2478 $submodule = new $submoduleclass();
2479 $subwhere = $where_definition;
2483 $subwhere = str_replace('WHERE', '', $subwhere);
2484 $list_fields = $this_subpanel->get_list_fields();
2485 foreach($list_fields as $list_key=>$list_field)
2487 if(isset($list_field['usage']) && $list_field['usage'] == 'display_only')
2489 unset($list_fields[$list_key]);
2494 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'))
2496 $order_by = $submodule->table_name .'.'. $order_by;
2498 $table_name = $this_subpanel->table_name;
2499 $panel_name=$this_subpanel->name;
2501 $params['distinct'] = $this_subpanel->distinct_query();
2503 $params['joined_tables'] = $query_array['join_tables'];
2504 $params['include_custom_fields'] = !$subpanel_def->isCollection();
2505 $params['collection_list'] = $subpanel_def->get_inst_prop_value('collection_list');
2507 $subquery = $submodule->create_new_list_query('',$subwhere ,$list_fields,$params, 0,'', true,$parentbean);
2509 $subquery['select'] = $subquery['select']." , '$panel_name' panel_name ";
2510 $subquery['from'] = $subquery['from'].$query_array['join'];
2511 $subquery['query_array'] = $query_array;
2512 $subquery['params'] = $params;
2514 $subqueries[] = $subquery;
2521 * Constructs a query to fetch data for supanels and list views
2523 * It constructs union queries for activities subpanel.
2525 * @param SugarBean $parentbean constructing queries for link attributes in this bean
2526 * @param string $order_by Optional, order by clause
2527 * @param string $sort_order Optional, sort order
2528 * @param string $where Optional, additional where clause
2530 * Internal Function, do not overide.
2532 function get_union_related_list($parentbean, $order_by = "", $sort_order='', $where = "",
2533 $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $subpanel_def)
2535 $secondary_queries = array();
2536 global $layout_edit_mode, $beanFiles, $beanList;
2538 if(isset($_SESSION['show_deleted']))
2543 $final_query_rows = '';
2544 $subpanel_list=array();
2545 if ($subpanel_def->isCollection())
2547 $subpanel_def->load_sub_subpanels();
2548 $subpanel_list=$subpanel_def->sub_subpanels;
2552 $subpanel_list[]=$subpanel_def;
2557 //Breaking the building process into two loops. The first loop gets a list of all the sub-queries.
2558 //The second loop merges the queries and forces them to select the same number of columns
2559 //All columns in a sub-subpanel group must have the same aliases
2560 //If the subpanel is a datasource function, it can't be a collection so we just poll that function for the and return that
2561 foreach($subpanel_list as $this_subpanel)
2563 if($this_subpanel->isDatasourceFunction() && empty($this_subpanel->_instance_properties['generate_select']))
2565 $shortcut_function_name = $this_subpanel->get_data_source_name();
2566 $parameters=$this_subpanel->get_function_parameters();
2567 if (!empty($parameters))
2569 //if the import file function is set, then import the file to call the custom function from
2570 if (is_array($parameters) && isset($parameters['import_function_file'])){
2571 //this call may happen multiple times, so only require if function does not exist
2572 if(!function_exists($shortcut_function_name)){
2573 require_once($parameters['import_function_file']);
2575 //call function from required file
2576 $tmp_final_query = $shortcut_function_name($parameters);
2578 //call function from parent bean
2579 $tmp_final_query = $parentbean->$shortcut_function_name($parameters);
2582 $tmp_final_query = $parentbean->$shortcut_function_name();
2586 $final_query_rows .= ' UNION ALL ( '.$parentbean->create_list_count_query($tmp_final_query, $parameters) . ' )';
2587 $final_query .= ' UNION ALL ( '.$tmp_final_query . ' )';
2589 $final_query_rows = '(' . $parentbean->create_list_count_query($tmp_final_query, $parameters) . ')';
2590 $final_query = '(' . $tmp_final_query . ')';
2595 //If final_query is still empty, its time to build the sub-queries
2596 if (empty($final_query))
2598 $subqueries = SugarBean::build_sub_queries_for_union($subpanel_list, $subpanel_def, $parentbean, $order_by);
2599 $all_fields = array();
2600 foreach($subqueries as $i => $subquery)
2602 $query_fields = $GLOBALS['db']->getSelectFieldsFromQuery($subquery['select']);
2603 foreach($query_fields as $field => $select)
2605 if (!in_array($field, $all_fields))
2606 $all_fields[] = $field;
2608 $subqueries[$i]['query_fields'] = $query_fields;
2611 //Now ensure the queries have the same set of fields in the same order.
2612 foreach($subqueries as $subquery)
2614 $subquery['select'] = "SELECT";
2615 foreach($all_fields as $field)
2617 if (!isset($subquery['query_fields'][$field]))
2619 $subquery['select'] .= " ' ' $field,";
2623 $subquery['select'] .= " {$subquery['query_fields'][$field]},";
2626 $subquery['select'] = substr($subquery['select'], 0 , strlen($subquery['select']) - 1);
2627 //Put the query into the final_query
2628 $query = $subquery['select'] . " " . $subquery['from'] . " " . $subquery['where'];
2631 $query = ' UNION ALL ( '.$query . ' )';
2632 $final_query_rows .= " UNION ALL ";
2634 $query = '(' . $query . ')';
2637 $query_array = $subquery['query_array'];
2638 $select_position=strpos($query_array['select'],"SELECT");
2639 $distinct_position=strpos($query_array['select'],"DISTINCT");
2640 if ($select_position !== false && $distinct_position!= false)
2642 $query_rows = "( ".substr_replace($query_array['select'],"SELECT count(",$select_position,6). ")" . $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2646 //resort to default behavior.
2647 $query_rows = "( SELECT count(*)". $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2649 if(!empty($subquery['secondary_select']))
2652 $subquerystring= $subquery['secondary_select'] . $subquery['secondary_from'].$query_array['join']. $subquery['where'];
2653 if (!empty($subquery['secondary_where']))
2655 if (empty($subquery['where']))
2657 $subquerystring.=" WHERE " .$subquery['secondary_where'];
2661 $subquerystring.=" AND " .$subquery['secondary_where'];
2664 $secondary_queries[]=$subquerystring;
2666 $final_query .= $query;
2667 $final_query_rows .= $query_rows;
2671 if(!empty($order_by))
2674 if(!$subpanel_def->isCollection())
2676 $submodulename = $subpanel_def->_instance_properties['module'];
2677 $submoduleclass = $beanList[$submodulename];
2678 $submodule = new $submoduleclass();
2680 if(!empty($submodule) && !empty($submodule->table_name))
2682 $final_query .= " ORDER BY " .$parentbean->process_order_by($order_by, $submodule);
2687 $final_query .= " ORDER BY ". $order_by . ' ';
2689 if(!empty($sort_order))
2691 $final_query .= ' ' .$sort_order;
2696 if(isset($layout_edit_mode) && $layout_edit_mode)
2698 $response = array();
2699 if(!empty($submodule))
2701 $submodule->assign_display_fields($submodule->module_dir);
2702 $response['list'] = array($submodule);
2706 $response['list'] = array();
2708 $response['parent_data'] = array();
2709 $response['row_count'] = 1;
2710 $response['next_offset'] = 0;
2711 $response['previous_offset'] = 0;
2716 return $parentbean->process_union_list_query($parentbean, $final_query, $row_offset, $limit, $max, '',$subpanel_def, $final_query_rows, $secondary_queries);
2721 * Returns a full (ie non-paged) list of the current object type.
2723 * @param string $order_by the order by SQL parameter. defaults to ""
2724 * @param string $where where clause. defaults to ""
2725 * @param boolean $check_dates. defaults to false
2726 * @param int $show_deleted show deleted records. defaults to 0
2728 function get_full_list($order_by = "", $where = "", $check_dates=false, $show_deleted = 0)
2730 $GLOBALS['log']->debug("get_full_list: order_by = '$order_by' and where = '$where'");
2731 if(isset($_SESSION['show_deleted']))
2735 $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted);
2736 return $this->process_full_list_query($query, $check_dates);
2740 * Return the list query used by the list views and export button. Next generation of create_new_list_query function.
2742 * Override this function to return a custom query.
2744 * @param string $order_by custom order by clause
2745 * @param string $where custom where clause
2746 * @param array $filter Optioanal
2747 * @param array $params Optional *
2748 * @param int $show_deleted Optional, default 0, show deleted records is set to 1.
2749 * @param string $join_type
2750 * @param boolean $return_array Optional, default false, response as array
2751 * @param object $parentbean creating a subquery for this bean.
2752 * @param boolean $singleSelect Optional, default false.
2753 * @return String select query string, optionally an array value will be returned if $return_array= true.
2755 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)
2757 global $beanFiles, $beanList;
2758 $selectedFields = array();
2759 $secondarySelectedFields = array();
2760 $ret_array = array();
2762 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2764 global $current_user;
2765 $owner_where = $this->getOwnerWhere($current_user->id);
2768 $where = $owner_where;
2772 $where .= ' AND '. $owner_where;
2775 if(!empty($params['distinct']))
2777 $distinct = ' DISTINCT ';
2781 $ret_array['select'] = " SELECT $distinct $this->table_name.* ";
2785 $ret_array['select'] = " SELECT $distinct $this->table_name.id ";
2787 $ret_array['from'] = " FROM $this->table_name ";
2788 $ret_array['from_min'] = $ret_array['from'];
2789 $ret_array['secondary_from'] = $ret_array['from'] ;
2790 $ret_array['where'] = '';
2791 $ret_array['order_by'] = '';
2792 //secondary selects are selects that need to be run after the primarty query to retrieve additional info on main
2795 $ret_array['secondary_select']=& $ret_array['select'];
2796 $ret_array['secondary_from'] = & $ret_array['from'];
2800 $ret_array['secondary_select'] = '';
2802 $custom_join = false;
2803 if((!isset($params['include_custom_fields']) || $params['include_custom_fields']) && isset($this->custom_fields))
2806 $custom_join = $this->custom_fields->getJOIN( empty($filter)? true: $filter );
2809 $ret_array['select'] .= ' ' .$custom_join['select'];
2814 $ret_array['from'] .= ' ' . $custom_join['join'];
2817 //LOOP AROUND FOR FIXIN VARDEF ISSUES
2818 require('include/VarDefHandler/listvardefoverride.php');
2819 $joined_tables = array();
2820 if(!empty($params['joined_tables']))
2822 foreach($params['joined_tables'] as $table)
2824 $joined_tables[$table] = 1;
2830 $filterKeys = array_keys($filter);
2831 if(is_numeric($filterKeys[0]))
2834 foreach($filter as $field)
2836 $field = strtolower($field);
2837 //remove out id field so we don't duplicate it
2838 if ( $field == 'id' && !empty($filter) ) {
2841 if(isset($this->field_defs[$field]))
2843 $fields[$field]= $this->field_defs[$field];
2847 $fields[$field] = array('force_exists'=>true);
2856 $fields = $this->field_defs;
2859 $used_join_key = array();
2861 foreach($fields as $field=>$value)
2863 //alias is used to alias field names
2865 if (isset($value['alias']))
2867 $alias =' as ' . $value['alias'] . ' ';
2870 if(empty($this->field_defs[$field]) || !empty($value['force_blank']) )
2872 if(!empty($filter) && isset($filter[$field]['force_exists']) && $filter[$field]['force_exists'])
2874 if ( isset($filter[$field]['force_default']) )
2875 $ret_array['select'] .= ", {$filter[$field]['force_default']} $field ";
2877 //spaces are a fix for length issue problem with unions. The union only returns the maximum number of characters from the first select statemtn.
2878 $ret_array['select'] .= ", ' ' $field ";
2884 $data = $this->field_defs[$field];
2887 //ignore fields that are a part of the collection and a field has been removed as a result of
2888 //layout customization.. this happens in subpanel customizations, use case, from the contacts subpanel
2889 //in opportunities module remove the contact_role/opportunity_role field.
2890 $process_field=true;
2891 if (isset($data['relationship_fields']) and !empty($data['relationship_fields']))
2893 foreach ($data['relationship_fields'] as $field_name)
2895 if (!isset($fields[$field_name]))
2897 $process_field=false;
2901 if (!$process_field)
2906 if( (!isset($data['source']) || $data['source'] == 'db') && (!empty($alias) || !empty($filter) ))
2908 $ret_array['select'] .= ", $this->table_name.$field $alias";
2909 $selectedFields["$this->table_name.$field"] = true;
2914 if($data['type'] != 'relate' && isset($data['db_concat_fields']))
2916 $ret_array['select'] .= ", " . $this->db->concat($this->table_name, $data['db_concat_fields']) . " as $field";
2917 $selectedFields[$this->db->concat($this->table_name, $data['db_concat_fields'])] = true;
2919 //Custom relate field or relate fields built in module builder which have no link field associated.
2920 if ($data['type'] == 'relate' && (isset($data['custom_module']) || isset($data['ext2']))) {
2921 $joinTableAlias = 'jt' . $jtcount;
2922 $relateJoinInfo = $this->custom_fields->getRelateJoin($data, $joinTableAlias);
2923 $ret_array['select'] .= $relateJoinInfo['select'];
2924 $ret_array['from'] .= $relateJoinInfo['from'];
2925 //Replace any references to the relationship in the where clause with the new alias
2926 //If the link isn't set, assume that search used the local table for the field
2927 $searchTable = isset($data['link']) ? $relateJoinInfo['rel_table'] : $this->table_name;
2928 $field_name = $relateJoinInfo['rel_table'] . '.' . !empty($data['name'])?$data['name']:'name';
2929 $where = preg_replace('/(^|[\s(])' . $field_name . '/' , '${1}' . $relateJoinInfo['name_field'], $where);
2933 if ($data['type'] == 'parent') {
2934 //See if we need to join anything by inspecting the where clause
2935 $match = preg_match('/(^|[\s(])parent_(\w+)_(\w+)\.name/', $where, $matches);
2937 $joinTableAlias = 'jt' . $jtcount;
2938 $joinModule = $matches[2];
2939 $joinTable = $matches[3];
2940 $localTable = $this->table_name;
2941 if (!empty($data['custom_module'])) {
2942 $localTable .= '_cstm';
2944 global $beanFiles, $beanList, $module;
2945 require_once($beanFiles[$beanList[$joinModule]]);
2946 $rel_mod = new $beanList[$joinModule]();
2947 $nameField = "$joinTableAlias.name";
2948 if (isset($rel_mod->field_defs['name']))
2950 $name_field_def = $rel_mod->field_defs['name'];
2951 if(isset($name_field_def['db_concat_fields']))
2953 $nameField = $this->db->concat($joinTableAlias, $name_field_def['db_concat_fields']);
2956 $ret_array['select'] .= ", $nameField {$data['name']} ";
2957 $ret_array['from'] .= " LEFT JOIN $joinTable $joinTableAlias
2958 ON $localTable.{$data['id_name']} = $joinTableAlias.id";
2959 //Replace any references to the relationship in the where clause with the new alias
2960 $where = preg_replace('/(^|[\s(])parent_' . $joinModule . '_' . $joinTable . '\.name/', '${1}' . $nameField, $where);
2964 if($data['type'] == 'relate' && isset($data['link']))
2966 $this->load_relationship($data['link']);
2967 if(!empty($this->$data['link']))
2970 if(empty($join_type))
2972 $params['join_type'] = ' LEFT JOIN ';
2976 $params['join_type'] = $join_type;
2978 if(isset($data['join_name']))
2980 $params['join_table_alias'] = $data['join_name'];
2984 $params['join_table_alias'] = 'jt' . $jtcount;
2987 if(isset($data['join_link_name']))
2989 $params['join_table_link_alias'] = $data['join_link_name'];
2993 $params['join_table_link_alias'] = 'jtl' . $jtcount;
2995 $join_primary = !isset($data['join_primary']) || $data['join_primary'];
2997 $join = $this->$data['link']->getJoin($params, true);
2998 $used_join_key[] = $join['rel_key'];
2999 $rel_module = $this->$data['link']->getRelatedModuleName();
3000 $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');
3002 //if rnanme is set to 'name', and bean files exist, then check if field should be a concatenated name
3003 global $beanFiles, $beanList;
3004 if($data['rname'] && !empty($beanFiles[$beanList[$rel_module]])) {
3006 //create an instance of the related bean
3007 require_once($beanFiles[$beanList[$rel_module]]);
3008 $rel_mod = new $beanList[$rel_module]();
3009 //if bean has first and last name fields, then name should be concatenated
3010 if(isset($rel_mod->field_name_map['first_name']) && isset($rel_mod->field_name_map['last_name'])){
3011 $data['db_concat_fields'] = array(0=>'first_name', 1=>'last_name');
3016 if($join['type'] == 'many-to-many')
3018 if(empty($ret_array['secondary_select']))
3020 $ret_array['secondary_select'] = " SELECT $this->table_name.id ref_id ";
3022 if(!empty($beanFiles[$beanList[$rel_module]]) && $join_primary)
3024 require_once($beanFiles[$beanList[$rel_module]]);
3025 $rel_mod = new $beanList[$rel_module]();
3026 if(isset($rel_mod->field_defs['assigned_user_id']))
3028 $ret_array['secondary_select'].= " , ". $params['join_table_alias'] . ".assigned_user_id {$field}_owner, '$rel_module' {$field}_mod";
3032 if(isset($rel_mod->field_defs['created_by']))
3034 $ret_array['secondary_select'].= " , ". $params['join_table_alias'] . ".created_by {$field}_owner , '$rel_module' {$field}_mod";
3040 if(isset($data['db_concat_fields']))
3042 $ret_array['secondary_select'] .= ' , ' . $this->db->concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
3046 if(!isset($data['relationship_fields']))
3048 $ret_array['secondary_select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
3053 $ret_array['select'] .= ", ' ' $field ";
3056 foreach($used_join_key as $used_key) {
3057 if($used_key == $join['rel_key']) $count_used++;
3059 if($count_used <= 1) {//27416, the $ret_array['secondary_select'] should always generate, regardless the dbtype
3060 // add rel_key only if it was not aready added
3063 $ret_array['select'] .= ", ' ' " . $join['rel_key'] . ' ';
3065 $ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'].'.'. $join['rel_key'] .' ' . $join['rel_key'];
3067 if(isset($data['relationship_fields']))
3069 foreach($data['relationship_fields'] as $r_name=>$alias_name)
3071 if(!empty( $secondarySelectedFields[$alias_name]))continue;
3072 $ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'].'.'. $r_name .' ' . $alias_name;
3073 $secondarySelectedFields[$alias_name] = true;
3078 $ret_array['secondary_from'] .= ' ' . $join['join']. ' AND ' . $params['join_table_alias'].'.deleted=0';
3079 if (isset($data['link_type']) && $data['link_type'] == 'relationship_info' && ($parentbean instanceOf SugarBean))
3081 $ret_array['secondary_where'] = $params['join_table_link_alias'] . '.' . $join['rel_key']. "='" .$parentbean->id . "'";
3087 if(isset($data['db_concat_fields']))
3089 $ret_array['select'] .= ' , ' . $this->db->concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
3093 $ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
3095 if(isset($data['additionalFields'])){
3096 foreach($data['additionalFields'] as $k=>$v){
3097 $ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $k . ' ' . $v;
3102 $ret_array['from'] .= ' ' . $join['join']. ' AND ' . $params['join_table_alias'].'.deleted=0';
3103 if(!empty($beanList[$rel_module]) && !empty($beanFiles[$beanList[$rel_module]]))
3105 require_once($beanFiles[$beanList[$rel_module]]);
3106 $rel_mod = new $beanList[$rel_module]();
3107 if(isset($value['target_record_key']) && !empty($filter))
3109 $selectedFields[$this->table_name.'.'.$value['target_record_key']] = true;
3110 $ret_array['select'] .= " , $this->table_name.{$value['target_record_key']} ";
3112 if(isset($rel_mod->field_defs['assigned_user_id']))
3114 $ret_array['select'] .= ' , ' .$params['join_table_alias'] . '.assigned_user_id ' . $field . '_owner';
3118 $ret_array['select'] .= ' , ' .$params['join_table_alias'] . '.created_by ' . $field . '_owner';
3120 $ret_array['select'] .= " , '".$rel_module ."' " . $field . '_mod';
3125 // To fix SOAP stuff where we are trying to retrieve all the accounts data where accounts.id = ..
3126 // and this code changes accounts to jt4 as there is a self join with the accounts table.
3128 if(isset($data['db_concat_fields'])){
3129 $buildWhere = false;
3130 if(in_array('first_name', $data['db_concat_fields']) && in_array('last_name', $data['db_concat_fields']))
3132 $exp = '/\(\s*?'.$data['name'].'.*?\%\'\s*?\)/';
3133 if(preg_match($exp, $where, $matches))
3135 $search_expression = $matches[0];
3136 //Create three search conditions - first + last, first, last
3137 $first_name_search = str_replace($data['name'], $params['join_table_alias'] . '.first_name', $search_expression);
3138 $last_name_search = str_replace($data['name'], $params['join_table_alias'] . '.last_name', $search_expression);
3139 $full_name_search = str_replace($data['name'], $this->db->concat($params['join_table_alias'], $data['db_concat_fields']), $search_expression);
3141 $where = str_replace($search_expression, '(' . $full_name_search . ' OR ' . $first_name_search . ' OR ' . $last_name_search . ')', $where);
3147 $db_field = $this->db->concat($params['join_table_alias'], $data['db_concat_fields']);
3148 $where = preg_replace('/'.$data['name'].'/', $db_field, $where);
3151 $where = preg_replace('/(^|[\s(])' . $data['name'] . '/', '${1}' . $params['join_table_alias'] . '.'.$data['rname'], $where);
3155 $joined_tables[$params['join_table_alias']]=1;
3156 $joined_tables[$params['join_table_link_alias']]=1;
3165 if(isset($this->field_defs['assigned_user_id']) && empty($selectedFields[$this->table_name.'.assigned_user_id']))
3167 $ret_array['select'] .= ", $this->table_name.assigned_user_id ";
3169 else if(isset($this->field_defs['created_by']) && empty($selectedFields[$this->table_name.'.created_by']))
3171 $ret_array['select'] .= ", $this->table_name.created_by ";
3173 if(isset($this->field_defs['system_id']) && empty($selectedFields[$this->table_name.'.system_id']))
3175 $ret_array['select'] .= ", $this->table_name.system_id ";
3180 if ($ifListForExport) {
3181 if(isset($this->field_defs['email1'])) {
3182 $ret_array['select'].= " ,email_addresses.email_address email1";
3183 $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 ";
3187 $where_auto = '1=1';
3188 if($show_deleted == 0)
3190 $where_auto = "$this->table_name.deleted=0";
3191 }else if($show_deleted == 1)
3193 $where_auto = "$this->table_name.deleted=1";
3196 $ret_array['where'] = " where ($where) AND $where_auto";
3198 $ret_array['where'] = " where $where_auto";
3199 if(!empty($order_by))
3201 //make call to process the order by clause
3202 $ret_array['order_by'] = " ORDER BY ". $this->process_order_by($order_by);
3206 unset($ret_array['secondary_where']);
3207 unset($ret_array['secondary_from']);
3208 unset($ret_array['secondary_select']);
3216 return $ret_array['select'] . $ret_array['from'] . $ret_array['where']. $ret_array['order_by'];
3219 * Returns parent record data for objects that store relationship information
3221 * @param array $type_info
3223 * Interal function, do not override.
3225 function retrieve_parent_fields($type_info)
3228 global $beanList, $beanFiles;
3229 $templates = array();
3230 $parent_child_map = array();
3231 foreach($type_info as $children_info)
3233 foreach($children_info as $child_info)
3235 if($child_info['type'] == 'parent')
3237 if(empty($templates[$child_info['parent_type']]))
3239 //Test emails will have an invalid parent_type, don't try to load the non-existant parent bean
3240 if ($child_info['parent_type'] == 'test') {
3243 $class = $beanList[$child_info['parent_type']];
3244 // Added to avoid error below; just silently fail and write message to log
3245 if ( empty($beanFiles[$class]) ) {
3246 $GLOBALS['log']->error($this->object_name.'::retrieve_parent_fields() - cannot load class "'.$class.'", skip loading.');
3249 require_once($beanFiles[$class]);
3250 $templates[$child_info['parent_type']] = new $class();
3253 if(empty($queries[$child_info['parent_type']]))
3255 $queries[$child_info['parent_type']] = "SELECT id ";
3256 $field_def = $templates[$child_info['parent_type']]->field_defs['name'];
3257 if(isset($field_def['db_concat_fields']))
3259 $queries[$child_info['parent_type']] .= ' , ' . $this->db->concat($templates[$child_info['parent_type']]->table_name, $field_def['db_concat_fields']) . ' parent_name';
3263 $queries[$child_info['parent_type']] .= ' , name parent_name';
3265 if(isset($templates[$child_info['parent_type']]->field_defs['assigned_user_id']))
3267 $queries[$child_info['parent_type']] .= ", assigned_user_id parent_name_owner , '{$child_info['parent_type']}' parent_name_mod";;
3268 }else if(isset($templates[$child_info['parent_type']]->field_defs['created_by']))
3270 $queries[$child_info['parent_type']] .= ", created_by parent_name_owner, '{$child_info['parent_type']}' parent_name_mod";
3272 $queries[$child_info['parent_type']] .= " FROM " . $templates[$child_info['parent_type']]->table_name ." WHERE id IN ('{$child_info['parent_id']}'";
3276 if(empty($parent_child_map[$child_info['parent_id']]))
3277 $queries[$child_info['parent_type']] .= " ,'{$child_info['parent_id']}'";
3279 $parent_child_map[$child_info['parent_id']][] = $child_info['child_id'];
3284 foreach($queries as $query)
3286 $result = $this->db->query($query . ')');
3287 while($row = $this->db->fetchByAssoc($result))
3289 $results[$row['id']] = $row;
3293 $child_results = array();
3294 foreach($parent_child_map as $parent_key=>$parent_child)
3296 foreach($parent_child as $child)
3298 if(isset( $results[$parent_key]))
3300 $child_results[$child] = $results[$parent_key];
3304 return $child_results;
3308 * Processes the list query and return fetched row.
3310 * Internal function, do not override.
3311 * @param string $query select query to be processed.
3312 * @param int $row_offset starting position
3313 * @param int $limit Optioanl, default -1
3314 * @param int $max_per_page Optional, default -1
3315 * @param string $where Optional, additional filter criteria.
3316 * @return array Fetched data
3318 function process_list_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '')
3320 global $sugar_config;
3321 $db = DBManagerFactory::getInstance('listviews');
3323 * if the row_offset is set to 'end' go to the end of the list
3325 $toEnd = strval($row_offset) == 'end';
3326 $GLOBALS['log']->debug("process_list_query: ".$query);
3327 if($max_per_page == -1)
3329 $max_per_page = $sugar_config['list_max_entries_per_page'];
3331 // Check to see if we have a count query available.
3332 if(empty($sugar_config['disable_count_query']) || $toEnd)
3334 $count_query = $this->create_list_count_query($query);
3335 if(!empty($count_query) && (empty($limit) || $limit == -1))
3337 // We have a count query. Run it and get the results.
3338 $result = $db->query($count_query, true, "Error running count query for $this->object_name List: ");
3339 $assoc = $db->fetchByAssoc($result);
3340 if(!empty($assoc['c']))
3342 $rows_found = $assoc['c'];
3343 $limit = $sugar_config['list_max_entries_per_page'];
3347 $row_offset = (floor(($rows_found -1) / $limit)) * $limit;
3353 if((empty($limit) || $limit == -1))
3355 $limit = $max_per_page + 1;
3356 $max_per_page = $limit;
3361 if(empty($row_offset))
3365 if(!empty($limit) && $limit != -1 && $limit != -99)
3367 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $this->object_name list: ");
3371 $result = $db->query($query,true,"Error retrieving $this->object_name list: ");
3376 $previous_offset = $row_offset - $max_per_page;
3377 $next_offset = $row_offset + $max_per_page;
3379 $class = get_class($this);
3380 //FIXME: Bug? we should remove the magic number -99
3381 //use -99 to return all
3382 $index = $row_offset;
3383 while ($max_per_page == -99 || ($index < $row_offset + $max_per_page))
3385 $row = $db->fetchByAssoc($result);
3386 if (empty($row)) break;
3388 //instantiate a new class each time. This is because php5 passes
3389 //by reference by default so if we continually update $this, we will
3390 //at the end have a list of all the same objects
3391 $temp = new $class();
3393 foreach($this->field_defs as $field=>$value)
3395 if (isset($row[$field]))
3397 $temp->$field = $row[$field];
3398 $owner_field = $field . '_owner';
3399 if(isset($row[$owner_field]))
3401 $temp->$owner_field = $row[$owner_field];
3404 $GLOBALS['log']->debug("$temp->object_name({$row['id']}): ".$field." = ".$temp->$field);
3405 }else if (isset($row[$this->table_name .'.'.$field]))
3407 $temp->$field = $row[$this->table_name .'.'.$field];
3415 $temp->check_date_relationships_load();
3416 $temp->fill_in_additional_list_fields();
3417 if($temp->hasCustomFields()) $temp->custom_fields->fill_relationships();
3418 $temp->call_custom_logic("process_record");
3424 if(!empty($sugar_config['disable_count_query']) && !empty($limit))
3427 $rows_found = $row_offset + count($list);
3429 unset($list[$limit - 1]);
3435 } else if(!isset($rows_found)){
3436 $rows_found = $row_offset + count($list);
3439 $response = Array();
3440 $response['list'] = $list;
3441 $response['row_count'] = $rows_found;
3442 $response['next_offset'] = $next_offset;
3443 $response['previous_offset'] = $previous_offset;
3444 $response['current_offset'] = $row_offset ;
3449 * Returns the number of rows that the given SQL query should produce
3451 * Internal function, do not override.
3452 * @param string $query valid select query
3453 * @param boolean $is_count_query Optional, Default false, set to true if passed query is a count query.
3454 * @return int count of rows found
3456 function _get_num_rows_in_query($query, $is_count_query=false)
3458 $num_rows_in_query = 0;
3459 if (!$is_count_query)
3461 $count_query = SugarBean::create_list_count_query($query);
3463 $count_query=$query;
3465 $result = $this->db->query($count_query, true, "Error running count query for $this->object_name List: ");
3467 while($row = $this->db->fetchByAssoc($result, true))
3469 $num_rows_in_query += current($row);
3472 return $num_rows_in_query;
3476 * Applies pagination window to union queries used by list view and subpanels,
3477 * executes the query and returns fetched data.
3479 * Internal function, do not override.
3480 * @param object $parent_bean
3481 * @param string $query query to be processed.
3482 * @param int $row_offset
3483 * @param int $limit optional, default -1
3484 * @param int $max_per_page Optional, default -1
3485 * @param string $where Custom where clause.
3486 * @param array $subpanel_def definition of sub-panel to be processed
3487 * @param string $query_row_count
3488 * @param array $seconday_queries
3489 * @return array Fetched data.
3491 function process_union_list_query($parent_bean, $query,
3492 $row_offset, $limit= -1, $max_per_page = -1, $where = '', $subpanel_def, $query_row_count='', $secondary_queries = array())
3495 $db = DBManagerFactory::getInstance('listviews');
3497 * if the row_offset is set to 'end' go to the end of the list
3499 $toEnd = strval($row_offset) == 'end';
3500 global $sugar_config;
3501 $use_count_query=false;
3502 $processing_collection=$subpanel_def->isCollection();
3504 $GLOBALS['log']->debug("process_union_list_query: ".$query);
3505 if($max_per_page == -1)
3507 $max_per_page = $sugar_config['list_max_entries_per_subpanel'];
3509 if(empty($query_row_count))
3511 $query_row_count = $query;
3513 $distinct_position=strpos($query_row_count,"DISTINCT");
3515 if ($distinct_position!= false)
3517 $use_count_query=true;
3519 $performSecondQuery = true;
3520 if(empty($sugar_config['disable_count_query']) || $toEnd)
3522 $rows_found = $this->_get_num_rows_in_query($query_row_count,$use_count_query);
3525 $performSecondQuery = false;
3527 if(!empty($rows_found) && (empty($limit) || $limit == -1))
3529 $limit = $sugar_config['list_max_entries_per_subpanel'];
3533 $row_offset = (floor(($rows_found -1) / $limit)) * $limit;
3539 if((empty($limit) || $limit == -1))
3541 $limit = $max_per_page + 1;
3542 $max_per_page = $limit;
3546 if(empty($row_offset))
3551 $previous_offset = $row_offset - $max_per_page;
3552 $next_offset = $row_offset + $max_per_page;
3554 if($performSecondQuery)
3556 if(!empty($limit) && $limit != -1 && $limit != -99)
3558 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $parent_bean->object_name list: ");
3562 $result = $db->query($query,true,"Error retrieving $this->object_name list: ");
3564 //use -99 to return all
3566 // get the current row
3567 $index = $row_offset;
3568 $row = $db->fetchByAssoc($result);
3570 $post_retrieve = array();
3571 $isFirstTime = true;
3574 $function_fields = array();
3575 if(($index < $row_offset + $max_per_page || $max_per_page == -99))
3577 if ($processing_collection)
3579 $current_bean =$subpanel_def->sub_subpanels[$row['panel_name']]->template_instance;
3582 $class = get_class($subpanel_def->sub_subpanels[$row['panel_name']]->template_instance);
3583 $current_bean = new $class();
3586 $current_bean=$subpanel_def->template_instance;
3589 $class = get_class($subpanel_def->template_instance);
3590 $current_bean = new $class();
3593 $isFirstTime = false;
3594 //set the panel name in the bean instance.
3595 if (isset($row['panel_name']))
3597 $current_bean->panel_name=$row['panel_name'];
3599 foreach($current_bean->field_defs as $field=>$value)
3602 if (isset($row[$field]))
3604 $current_bean->$field = $this->convertField($row[$field], $value);
3605 unset($row[$field]);
3607 else if (isset($row[$this->table_name .'.'.$field]))
3609 $current_bean->$field = $this->convertField($row[$this->table_name .'.'.$field], $value);
3610 unset($row[$this->table_name .'.'.$field]);
3614 $current_bean->$field = "";
3615 unset($row[$field]);
3617 if(isset($value['source']) && $value['source'] == 'function')
3619 $function_fields[]=$field;
3622 foreach($row as $key=>$value)
3624 $current_bean->$key = $value;
3626 foreach($function_fields as $function_field)
3628 $value = $current_bean->field_defs[$function_field];
3629 $can_execute = true;
3630 $execute_params = array();
3631 $execute_function = array();
3632 if(!empty($value['function_class']))
3634 $execute_function[] = $value['function_class'];
3635 $execute_function[] = $value['function_name'];
3639 $execute_function = $value['function_name'];
3641 foreach($value['function_params'] as $param )
3643 if (empty($value['function_params_source']) or $value['function_params_source']=='parent')
3645 if(empty($this->$param))
3647 $can_execute = false;
3648 } else if($param == '$this') {
3649 $execute_params[] = $this;
3653 $execute_params[] = $this->$param;
3655 } else if ($value['function_params_source']=='this')
3657 if(empty($current_bean->$param))
3659 $can_execute = false;
3660 } else if($param == '$this') {
3661 $execute_params[] = $current_bean;
3665 $execute_params[] = $current_bean->$param;
3670 $can_execute = false;
3676 if(!empty($value['function_require']))
3678 require_once($value['function_require']);
3680 $current_bean->$function_field = call_user_func_array($execute_function, $execute_params);
3683 if(!empty($current_bean->parent_type) && !empty($current_bean->parent_id))
3685 if(!isset($post_retrieve[$current_bean->parent_type]))
3687 $post_retrieve[$current_bean->parent_type] = array();
3689 $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');
3691 //$current_bean->fill_in_additional_list_fields();
3692 $list[$current_bean->id] = $current_bean;
3694 // go to the next row
3696 $row = $db->fetchByAssoc($result);
3698 //now handle retrieving many-to-many relationships
3701 foreach($secondary_queries as $query2)
3703 $result2 = $db->query($query2);
3705 $row2 = $db->fetchByAssoc($result2);
3708 $id_ref = $row2['ref_id'];
3710 if(isset($list[$id_ref]))
3712 foreach($row2 as $r2key=>$r2value)
3714 if($r2key != 'ref_id')
3716 $list[$id_ref]->$r2key = $r2value;
3720 $row2 = $db->fetchByAssoc($result2);
3726 if(isset($post_retrieve))
3728 $parent_fields = $this->retrieve_parent_fields($post_retrieve);
3732 $parent_fields = array();
3734 if(!empty($sugar_config['disable_count_query']) && !empty($limit))
3736 //C.L. Bug 43535 - Use the $index value to set the $rows_found value here
3737 $rows_found = isset($index) ? $index : $row_offset + count($list);
3739 if(count($list) >= $limit)
3753 $parent_fields = array();
3755 $response = array();
3756 $response['list'] = $list;
3757 $response['parent_data'] = $parent_fields;
3758 $response['row_count'] = $rows_found;
3759 $response['next_offset'] = $next_offset;
3760 $response['previous_offset'] = $previous_offset;
3761 $response['current_offset'] = $row_offset ;
3762 $response['query'] = $query;
3768 * Applies pagination window to select queries used by detail view,
3769 * executes the query and returns fetched data.
3771 * Internal function, do not override.
3772 * @param string $query query to be processed.
3773 * @param int $row_offset
3774 * @param int $limit optional, default -1
3775 * @param int $max_per_page Optional, default -1
3776 * @param string $where Custom where clause.
3777 * @param int $offset Optional, default 0
3778 * @return array Fetched data.
3781 function process_detail_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '', $offset = 0)
3783 global $sugar_config;
3784 $GLOBALS['log']->debug("process_detail_query: ".$query);
3785 if($max_per_page == -1)
3787 $max_per_page = $sugar_config['list_max_entries_per_page'];
3790 // Check to see if we have a count query available.
3791 $count_query = $this->create_list_count_query($query);
3793 if(!empty($count_query) && (empty($limit) || $limit == -1))
3795 // We have a count query. Run it and get the results.
3796 $result = $this->db->query($count_query, true, "Error running count query for $this->object_name List: ");
3797 $assoc = $this->db->fetchByAssoc($result);
3798 if(!empty($assoc['c']))
3800 $total_rows = $assoc['c'];
3804 if(empty($row_offset))
3809 $result = $this->db->limitQuery($query, $offset, 1, true,"Error retrieving $this->object_name list: ");
3811 $previous_offset = $row_offset - $max_per_page;
3812 $next_offset = $row_offset + $max_per_page;
3814 $row = $this->db->fetchByAssoc($result);
3815 $this->retrieve($row['id']);
3817 $response = Array();
3818 $response['bean'] = $this;
3819 if (empty($total_rows))
3821 $response['row_count'] = $total_rows;
3822 $response['next_offset'] = $next_offset;
3823 $response['previous_offset'] = $previous_offset;
3829 * Processes fetched list view data
3831 * Internal function, do not override.
3832 * @param string $query query to be processed.
3833 * @param boolean $check_date Optional, default false. if set to true date time values are processed.
3834 * @return array Fetched data.
3837 function process_full_list_query($query, $check_date=false)
3840 $GLOBALS['log']->debug("process_full_list_query: query is ".$query);
3841 $result = $this->db->query($query, false);
3842 $GLOBALS['log']->debug("process_full_list_query: result is ".print_r($result,true));
3843 $class = get_class($this);
3844 $isFirstTime = true;
3845 $bean = new $class();
3847 // We have some data.
3848 while (($row = $bean->db->fetchByAssoc($result)) != null)
3850 $row = $this->convertRow($row);
3853 $bean = new $class();
3855 $isFirstTime = false;
3857 foreach($bean->field_defs as $field=>$value)
3859 if (isset($row[$field]))
3861 $bean->$field = $row[$field];
3862 $GLOBALS['log']->debug("process_full_list: $bean->object_name({$row['id']}): ".$field." = ".$bean->$field);
3871 $bean->processed_dates_times = array();
3872 $bean->check_date_relationships_load();
3874 $bean->fill_in_additional_list_fields();
3875 $bean->call_custom_logic("process_record");
3876 $bean->fetched_row = $row;
3881 if (isset($list)) return $list;
3886 * Tracks the viewing of a detail record.
3887 * This leverages get_summary_text() which is object specific.
3889 * Internal function, do not override.
3890 * @param string $user_id - String value of the user that is viewing the record.
3891 * @param string $current_module - String value of the module being processed.
3892 * @param string $current_view - String value of the current view
3894 function track_view($user_id, $current_module, $current_view='')
3896 $trackerManager = TrackerManager::getInstance();
3897 if($monitor = $trackerManager->getMonitor('tracker')){
3898 $monitor->setValue('date_modified', $GLOBALS['timedate']->nowDb());
3899 $monitor->setValue('user_id', $user_id);
3900 $monitor->setValue('module_name', $current_module);
3901 $monitor->setValue('action', $current_view);
3902 $monitor->setValue('item_id', $this->id);
3903 $monitor->setValue('item_summary', $this->get_summary_text());
3904 $monitor->setValue('visible', $this->tracker_visibility);
3905 $trackerManager->saveMonitor($monitor);
3910 * Returns the summary text that should show up in the recent history list for this object.
3914 public function get_summary_text()
3916 return "Base Implementation. Should be overridden.";
3920 * This is designed to be overridden and add specific fields to each record.
3921 * This allows the generic query to fill in the major fields, and then targeted
3922 * queries to get related fields and add them to the record. The contact's
3923 * account for instance. This method is only used for populating extra fields
3926 function fill_in_additional_list_fields(){
3927 if(!empty($this->field_defs['parent_name']) && empty($this->parent_name)){
3928 $this->fill_in_additional_parent_fields();
3933 * This is designed to be overridden and add specific fields to each record.
3934 * This allows the generic query to fill in the major fields, and then targeted
3935 * queries to get related fields and add them to the record. The contact's
3936 * account for instance. This method is only used for populating extra fields
3937 * in the detail form
3939 function fill_in_additional_detail_fields()
3941 if(!empty($this->field_defs['assigned_user_name']) && !empty($this->assigned_user_id)){
3943 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
3946 if(!empty($this->field_defs['created_by']) && !empty($this->created_by))
3947 $this->created_by_name = get_assigned_user_name($this->created_by);
3948 if(!empty($this->field_defs['modified_user_id']) && !empty($this->modified_user_id))
3949 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
3951 if(!empty($this->field_defs['parent_name'])){
3952 $this->fill_in_additional_parent_fields();
3957 * This is desgined to be overridden or called from extending bean. This method
3958 * will fill in any parent_name fields.
3960 function fill_in_additional_parent_fields() {
3962 if(!empty($this->parent_id) && !empty($this->last_parent_id) && $this->last_parent_id == $this->parent_id){
3965 $this->parent_name = '';
3967 if(!empty($this->parent_type)) {
3968 $this->last_parent_id = $this->parent_id;
3969 $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'));
3970 if(!empty($this->parent_first_name) || !empty($this->parent_last_name) ){
3971 $this->parent_name = $GLOBALS['locale']->getLocaleFormattedName($this->parent_first_name, $this->parent_last_name);
3972 } else if(!empty($this->parent_document_name)){
3973 $this->parent_name = $this->parent_document_name;
3979 * Fill in a link field
3982 // fguerra@dri and jmorais@dri - fill in link fields not working
3983 function fill_in_link_field( $linkFieldName, $fieldName )
3985 if ($this->load_relationship($linkFieldName))
3987 $list=$this->$linkFieldName->get();
3988 $this->$fieldName = '' ; // match up with null value in $this->populateFromRow()
3990 $this->$fieldName = $list[0];
3995 * Fill in fields where type = relate
3997 function fill_in_relationship_fields(){
3998 global $fill_in_rel_depth;
3999 if(empty($fill_in_rel_depth) || $fill_in_rel_depth < 0)
4000 $fill_in_rel_depth = 0;
4001 if($fill_in_rel_depth > 1)
4003 $fill_in_rel_depth++;
4005 foreach($this->field_defs as $field)
4007 if(0 == strcmp($field['type'],'relate') && !empty($field['module']))
4009 $name = $field['name'];
4010 if(empty($this->$name))
4012 // 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']
4013 $related_module = $field['module'];
4014 $id_name = $field['id_name'];
4015 // fguerra@dri and jmorais@dri - fill in link fields not working
4016 if (empty($this->$id_name) && array_key_exists('link', $field)){
4017 $this->fill_in_link_field($field['link'], $id_name);
4019 // ~ fguerra@dri and jmorais@dri
4020 if(!empty($this->$id_name) && ( $this->object_name != $related_module || ( $this->object_name == $related_module && $this->$id_name != $this->id ))){
4021 if(isset($GLOBALS['beanList'][ $related_module])){
4022 $class = $GLOBALS['beanList'][$related_module];
4024 if(!empty($this->$id_name) && file_exists($GLOBALS['beanFiles'][$class]) && isset($this->$name)){
4025 require_once($GLOBALS['beanFiles'][$class]);
4026 $mod = new $class();
4027 $mod->retrieve($this->$id_name);
4028 if (!empty($field['rname'])) {
4029 $this->$name = $mod->$field['rname'];
4030 } else if (isset($mod->name)) {
4031 $this->$name = $mod->name;
4036 if(!empty($this->$id_name) && isset($this->$name))
4038 if(!isset($field['additionalFields']))
4039 $field['additionalFields'] = array();
4040 if(!empty($field['rname']))
4042 $field['additionalFields'][$field['rname']]= $name;
4046 $field['additionalFields']['name']= $name;
4048 $this->getRelatedFields($related_module, $this->$id_name, $field['additionalFields']);
4053 $fill_in_rel_depth--;
4057 * This is a helper function that is used to quickly created indexes when creating tables.
4059 function create_index($query)
4061 $GLOBALS['log']->info("create_index: $query");
4063 $result = $this->db->query($query, true, "Error creating index:");
4067 * This function should be overridden in each module. It marks an item as deleted.
4069 * If it is not overridden, then marking this type of item is not allowed
4071 function mark_deleted($id)
4073 global $current_user;
4074 $date_modified = $GLOBALS['timedate']->nowDb();
4075 if(isset($_SESSION['show_deleted']))
4077 $this->mark_undeleted($id);
4081 // call the custom business logic
4082 $custom_logic_arguments['id'] = $id;
4083 $this->call_custom_logic("before_delete", $custom_logic_arguments);
4085 $this->mark_relationships_deleted($id);
4086 if ( isset($this->field_defs['modified_user_id']) ) {
4087 if (!empty($current_user)) {
4088 $this->modified_user_id = $current_user->id;
4090 $this->modified_user_id = 1;
4092 $query = "UPDATE $this->table_name set deleted=1 , date_modified = '$date_modified', modified_user_id = '$this->modified_user_id' where id='$id'";
4094 $query = "UPDATE $this->table_name set deleted=1 , date_modified = '$date_modified' where id='$id'";
4096 $this->db->query($query, true,"Error marking record deleted: ");
4098 SugarRelationship::resaveRelatedBeans();
4100 // Take the item off the recently viewed lists
4101 $tracker = new Tracker();
4102 $tracker->makeInvisibleForAll($id);
4104 // call the custom business logic
4105 $this->call_custom_logic("after_delete", $custom_logic_arguments);
4110 * Restores data deleted by call to mark_deleted() function.
4112 * Internal function, do not override.
4114 function mark_undeleted($id)
4116 // call the custom business logic
4117 $custom_logic_arguments['id'] = $id;
4118 $this->call_custom_logic("before_restore", $custom_logic_arguments);
4120 $date_modified = $GLOBALS['timedate']->nowDb();
4121 $query = "UPDATE $this->table_name set deleted=0 , date_modified = '$date_modified' where id='$id'";
4122 $this->db->query($query, true,"Error marking record undeleted: ");
4124 // call the custom business logic
4125 $this->call_custom_logic("after_restore", $custom_logic_arguments);
4129 * This function deletes relationships to this object. It should be overridden
4130 * to handle the relationships of the specific object.
4131 * This function is called when the item itself is being deleted.
4133 * @param int $id id of the relationship to delete
4135 function mark_relationships_deleted($id)
4137 $this->delete_linked($id);
4141 * This function is used to execute the query and create an array template objects
4142 * from the resulting ids from the query.
4143 * It is currently used for building sub-panel arrays.
4145 * @param string $query - the query that should be executed to build the list
4146 * @param object $template - The object that should be used to copy the records.
4147 * @param int $row_offset Optional, default 0
4148 * @param int $limit Optional, default -1
4151 function build_related_list($query, &$template, $row_offset = 0, $limit = -1)
4153 $GLOBALS['log']->debug("Finding linked records $this->object_name: ".$query);
4154 $db = DBManagerFactory::getInstance('listviews');
4156 if(!empty($row_offset) && $row_offset != 0 && !empty($limit) && $limit != -1)
4158 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $template->object_name list: ");
4162 $result = $db->query($query, true);
4166 $isFirstTime = true;
4167 $class = get_class($template);
4168 while($row = $this->db->fetchByAssoc($result))
4172 $template = new $class();
4174 $isFirstTime = false;
4175 $record = $template->retrieve($row['id']);
4179 // this copies the object into the array
4180 $list[] = $template;
4187 * This function is used to execute the query and create an array template objects
4188 * from the resulting ids from the query.
4189 * It is currently used for building sub-panel arrays. It supports an additional
4190 * where clause that is executed as a filter on the results
4192 * @param string $query - the query that should be executed to build the list
4193 * @param object $template - The object that should be used to copy the records.
4195 function build_related_list_where($query, &$template, $where='', $in='', $order_by, $limit='', $row_offset = 0)
4197 $db = DBManagerFactory::getInstance('listviews');
4198 // No need to do an additional query
4199 $GLOBALS['log']->debug("Finding linked records $this->object_name: ".$query);
4200 if(empty($in) && !empty($query))
4202 $idList = $this->build_related_in($query);
4203 $in = $idList['in'];
4205 // MFH - Added Support For Custom Fields in Searches
4207 if(isset($this->custom_fields)) {
4208 $custom_join = $this->custom_fields->getJOIN();
4211 $query = "SELECT id ";
4213 if (!empty($custom_join)) {
4214 $query .= $custom_join['select'];
4216 $query .= " FROM $this->table_name ";
4218 if (!empty($custom_join) && !empty($custom_join['join'])) {
4219 $query .= " " . $custom_join['join'];
4222 $query .= " WHERE deleted=0 AND id IN $in";
4225 $query .= " AND $where";
4229 if(!empty($order_by))
4231 $query .= "ORDER BY $order_by";
4235 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $this->object_name list: ");
4239 $result = $db->query($query, true);
4243 $isFirstTime = true;
4244 $class = get_class($template);
4246 $disable_security_flag = ($template->disable_row_level_security) ? true : false;
4247 while($row = $db->fetchByAssoc($result))
4251 $template = new $class();
4252 $template->disable_row_level_security = $disable_security_flag;
4254 $isFirstTime = false;
4255 $record = $template->retrieve($row['id']);
4258 // this copies the object into the array
4259 $list[] = $template;
4267 * Constructs an comma seperated list of ids from passed query results.
4269 * @param string @query query to be executed.
4272 function build_related_in($query)
4275 $result = $this->db->query($query, true);
4277 while($row = $this->db->fetchByAssoc($result))
4279 $idList[] = $row['id'];
4282 $ids = "('" . $row['id'] . "'";
4286 $ids .= ",'" . $row['id'] . "'";
4296 return array('list'=>$idList, 'in'=>$ids);
4300 * Optionally copies values from fetched row into the bean.
4302 * Internal function, do not override.
4304 * @param string $query - the query that should be executed to build the list
4305 * @param object $template - The object that should be used to copy the records
4306 * @param array $field_list List of fields.
4309 function build_related_list2($query, &$template, &$field_list)
4311 $GLOBALS['log']->debug("Finding linked values $this->object_name: ".$query);
4313 $result = $this->db->query($query, true);
4316 $isFirstTime = true;
4317 $class = get_class($template);
4318 while($row = $this->db->fetchByAssoc($result))
4320 // Create a blank copy
4324 $copy = new $class();
4326 $isFirstTime = false;
4327 foreach($field_list as $field)
4329 // Copy the relevant fields
4330 $copy->$field = $row[$field];
4334 // this copies the object into the array
4342 * Let implementing classes to fill in row specific columns of a list view form
4345 function list_view_parse_additional_sections(&$list_form)
4350 * Assigns all of the values into the template for the list view
4352 function get_list_view_array()
4354 static $cache = array();
4355 // cn: bug 12270 - sensitive fields being passed arbitrarily in listViews
4356 $sensitiveFields = array('user_hash' => '');
4358 $return_array = Array();
4359 global $app_list_strings, $mod_strings;
4360 foreach($this->field_defs as $field=>$value){
4362 if(isset($this->$field)){
4364 // cn: bug 12270 - sensitive fields being passed arbitrarily in listViews
4365 if(isset($sensitiveFields[$field]))
4367 if(!isset($cache[$field]))
4368 $cache[$field] = strtoupper($field);
4370 //Fields hidden by Dependent Fields
4371 if (isset($value['hidden']) && $value['hidden'] === true) {
4372 $return_array[$cache[$field]] = "";
4375 //cn: if $field is a _dom, detect and return VALUE not KEY
4376 //cl: empty function check for meta-data enum types that have values loaded from a function
4377 else if (((!empty($value['type']) && ($value['type'] == 'enum' || $value['type'] == 'radioenum') )) && empty($value['function'])){
4378 if(!empty($app_list_strings[$value['options']][$this->$field])){
4379 $return_array[$cache[$field]] = $app_list_strings[$value['options']][$this->$field];
4381 //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.
4382 elseif(!empty($mod_strings[$value['options']][$this->$field]))
4384 $return_array[$cache[$field]] = $mod_strings[$value['options']][$this->$field];
4387 $return_array[$cache[$field]] = $this->$field;
4390 // tjy: no need to do this str_replace as the changes in 29994 for ListViewGeneric.tpl for translation handle this now
4391 // }elseif(!empty($value['type']) && $value['type'] == 'multienum'&& empty($value['function'])){
4392 // $return_array[strtoupper($field)] = str_replace('^,^', ', ', $this->$field );
4393 }elseif(!empty($value['custom_module']) && $value['type'] != 'currency'){
4394 // $this->format_field($value);
4395 $return_array[$cache[$field]] = $this->$field;
4397 $return_array[$cache[$field]] = $this->$field;
4399 // handle "Assigned User Name"
4400 if($field == 'assigned_user_name'){
4401 $return_array['ASSIGNED_USER_NAME'] = get_assigned_user_name($this->assigned_user_id);
4405 return $return_array;
4408 * Override this function to set values in the array used to render list view data.
4411 function get_list_view_data()
4413 return $this->get_list_view_array();
4417 * Construct where clause from a list of name-value pairs.
4418 * @param array $fields_array Name/value pairs for column checks
4419 * @return string The WHERE clause
4421 function get_where($fields_array)
4424 foreach ($fields_array as $name=>$value)
4426 if (!empty($where_clause)) {
4427 $where_clause .= " AND ";
4429 $name = $this->db->getValidDBName($name);
4431 $where_clause .= "$name = ".$this->db->quoted($value,false);
4433 if(!empty($where_clause)) {
4434 return "WHERE $where_clause AND deleted=0";
4436 return "WHERE deteled=0";
4442 * Constructs a select query and fetch 1 row using this query, and then process the row
4444 * Internal function, do not override.
4445 * @param array @fields_array array of name value pairs used to construct query.
4446 * @param boolean $encode Optional, default true, encode fetched data.
4447 * @return object Instance of this bean with fetched data.
4449 function retrieve_by_string_fields($fields_array, $encode=true)
4451 $where_clause = $this->get_where($fields_array);
4452 if(isset($this->custom_fields))
4453 $custom_join = $this->custom_fields->getJOIN();
4454 else $custom_join = false;
4457 $query = "SELECT $this->table_name.*". $custom_join['select']. " FROM $this->table_name " . $custom_join['join'];
4461 $query = "SELECT $this->table_name.* FROM $this->table_name ";
4463 $query .= " $where_clause";
4464 $GLOBALS['log']->debug("Retrieve $this->object_name: ".$query);
4465 //requireSingleResult has beeen deprecated.
4466 //$result = $this->db->requireSingleResult($query, true, "Retrieving record $where_clause:");
4467 $result = $this->db->limitQuery($query,0,1,true, "Retrieving record $where_clause:");
4474 $row = $this->db->fetchByAssoc($result, $encode);
4479 // Removed getRowCount-if-clause earlier and insert duplicates_found here as it seems that we have found something
4480 // if we didn't return null in the previous clause.
4481 $this->duplicates_found = true;
4482 $row = $this->convertRow($row);
4483 $this->fetched_row = $row;
4484 $this->fromArray($row);
4485 $this->fill_in_additional_detail_fields();
4490 * This method is called during an import before inserting a bean
4491 * Define an associative array called $special_fields
4492 * the keys are user defined, and don't directly map to the bean's fields
4493 * the value is the method name within that bean that will do extra
4494 * processing for that field. example: 'full_name'=>'get_names_from_full_name'
4497 function process_special_fields()
4499 foreach ($this->special_functions as $func_name)
4501 if ( method_exists($this,$func_name) )
4503 $this->$func_name();
4509 * Override this function to build a where clause based on the search criteria set into bean .
4512 function build_generic_where_clause($value)
4516 function getRelatedFields($module, $id, $fields, $return_array = false){
4517 if(empty($GLOBALS['beanList'][$module]))return '';
4518 $object = BeanFactory::getObjectName($module);
4520 VardefManager::loadVardef($module, $object);
4521 if(empty($GLOBALS['dictionary'][$object]['table']))return '';
4522 $table = $GLOBALS['dictionary'][$object]['table'];
4523 $query = 'SELECT id';
4524 foreach($fields as $field=>$alias){
4525 if(!empty($GLOBALS['dictionary'][$object]['fields'][$field]['db_concat_fields'])){
4526 $query .= ' ,' .$this->db->concat($table, $GLOBALS['dictionary'][$object]['fields'][$field]['db_concat_fields']) . ' as ' . $alias ;
4527 }else if(!empty($GLOBALS['dictionary'][$object]['fields'][$field]) &&
4528 (empty($GLOBALS['dictionary'][$object]['fields'][$field]['source']) ||
4529 $GLOBALS['dictionary'][$object]['fields'][$field]['source'] != "non-db"))
4531 $query .= ' ,' .$table . '.' . $field . ' as ' . $alias;
4533 if(!$return_array)$this->$alias = '';
4535 if($query == 'SELECT id' || empty($id)){
4540 if(isset($GLOBALS['dictionary'][$object]['fields']['assigned_user_id']))
4542 $query .= " , ". $table . ".assigned_user_id owner";
4545 else if(isset($GLOBALS['dictionary'][$object]['fields']['created_by']))
4547 $query .= " , ". $table . ".created_by owner";
4550 $query .= ' FROM ' . $table . ' WHERE deleted=0 AND id=';
4551 $result = $GLOBALS['db']->query($query . "'$id'" );
4552 $row = $GLOBALS['db']->fetchByAssoc($result);
4556 $owner = (empty($row['owner']))?'':$row['owner'];
4557 foreach($fields as $alias){
4558 $this->$alias = (!empty($row[$alias]))? $row[$alias]: '';
4559 $alias = $alias .'_owner';
4560 $this->$alias = $owner;
4561 $a_mod = $alias .'_mod';
4562 $this->$a_mod = $module;
4569 function &parse_additional_headers(&$list_form, $xTemplateSection)
4574 function assign_display_fields($currentModule)
4577 foreach($this->column_fields as $field)
4579 if(isset($this->field_name_map[$field]) && empty($this->$field))
4581 if($this->field_name_map[$field]['type'] != 'date' && $this->field_name_map[$field]['type'] != 'enum')
4582 $this->$field = $field;
4583 if($this->field_name_map[$field]['type'] == 'date')
4585 $this->$field = $timedate->to_display_date('1980-07-09');
4587 if($this->field_name_map[$field]['type'] == 'enum')
4589 $dom = $this->field_name_map[$field]['options'];
4590 global $current_language, $app_list_strings;
4591 $mod_strings = return_module_language($current_language, $currentModule);
4593 if(isset($mod_strings[$dom]))
4595 $options = $mod_strings[$dom];
4596 foreach($options as $key=>$value)
4598 if(!empty($key) && empty($this->$field ))
4600 $this->$field = $key;
4604 if(isset($app_list_strings[$dom]))
4606 $options = $app_list_strings[$dom];
4607 foreach($options as $key=>$value)
4609 if(!empty($key) && empty($this->$field ))
4611 $this->$field = $key;
4623 * RELATIONSHIP HANDLING
4626 function set_relationship($table, $relate_values, $check_duplicates = true,$do_update=false,$data_values=null)
4630 // make sure there is a date modified
4631 $date_modified = $this->db->convert("'".$GLOBALS['timedate']->nowDb()."'", 'datetime');
4634 if($check_duplicates)
4636 $query = "SELECT * FROM $table ";
4637 $where = "WHERE deleted = '0' ";
4638 foreach($relate_values as $name=>$value)
4640 $where .= " AND $name = '$value' ";
4643 $result = $this->db->query($query, false, "Looking For Duplicate Relationship:" . $query);
4644 $row=$this->db->fetchByAssoc($result);
4647 if(!$check_duplicates || empty($row) )
4649 unset($relate_values['id']);
4650 if ( isset($data_values))
4652 $relate_values = array_merge($relate_values,$data_values);
4654 $query = "INSERT INTO $table (id, ". implode(',', array_keys($relate_values)) . ", date_modified) VALUES ('" . create_guid() . "', " . "'" . implode("', '", $relate_values) . "', ".$date_modified.")" ;
4656 $this->db->query($query, false, "Creating Relationship:" . $query);
4658 else if ($do_update)
4661 foreach($data_values as $key=>$value)
4663 array_push($conds,$key."='".$this->db->quote($value)."'");
4665 $query = "UPDATE $table SET ". implode(',', $conds).",date_modified=".$date_modified." ".$where;
4666 $this->db->query($query, false, "Updating Relationship:" . $query);
4670 function retrieve_relationships($table, $values, $select_id)
4672 $query = "SELECT $select_id FROM $table WHERE deleted = 0 ";
4673 foreach($values as $name=>$value)
4675 $query .= " AND $name = '$value' ";
4677 $query .= " ORDER BY $select_id ";
4678 $result = $this->db->query($query, false, "Retrieving Relationship:" . $query);
4680 while($row = $this->db->fetchByAssoc($result))
4687 // TODO: this function needs adjustment
4688 function loadLayoutDefs()
4690 global $layout_defs;
4691 if(empty( $this->layout_def) && file_exists('modules/'. $this->module_dir . '/layout_defs.php'))
4693 include_once('modules/'. $this->module_dir . '/layout_defs.php');
4694 if(file_exists('custom/modules/'. $this->module_dir . '/Ext/Layoutdefs/layoutdefs.ext.php'))
4696 include_once('custom/modules/'. $this->module_dir . '/Ext/Layoutdefs/layoutdefs.ext.php');
4698 if ( empty( $layout_defs[get_class($this)]))
4700 echo "\$layout_defs[" . get_class($this) . "]; does not exist";
4703 $this->layout_def = $layout_defs[get_class($this)];
4708 * Trigger custom logic for this module that is defined for the provided hook
4709 * The custom logic file is located under custom/modules/[CURRENT_MODULE]/logic_hooks.php.
4710 * That file should define the $hook_version that should be used.
4711 * It should also define the $hook_array. The $hook_array will be a two dimensional array
4712 * the first dimension is the name of the event, the second dimension is the information needed
4713 * to fire the hook. Each entry in the top level array should be defined on a single line to make it
4714 * easier to automatically replace this file. There should be no contents of this file that are not replacable.
4716 * $hook_array['before_save'][] = Array(1, testtype, 'custom/modules/Leads/test12.php', 'TestClass', 'lead_before_save_1');
4717 * This sample line creates a before_save hook. The hooks are procesed in the order in which they
4718 * are added to the array. The second dimension is an array of:
4719 * processing index (for sorting before exporting the array)
4722 * php file to include
4723 * php class the method is in
4724 * php method to call
4726 * The method signature for version 1 hooks is:
4727 * function NAME(&$bean, $event, $arguments)
4728 * $bean - $this bean passed in by reference.
4729 * $event - The string for the current event (i.e. before_save)
4730 * $arguments - An array of arguments that are specific to the event.
4732 function call_custom_logic($event, $arguments = null)
4734 if(!isset($this->processed) || $this->processed == false){
4735 //add some logic to ensure we do not get into an infinite loop
4736 if(!empty($this->logicHookDepth[$event])) {
4737 if($this->logicHookDepth[$event] > 10)
4740 $this->logicHookDepth[$event] = 0;
4742 //we have to put the increment operator here
4743 //otherwise we may never increase the depth for that event in the case
4744 //where one event will trigger another as in the case of before_save and after_save
4745 //Also keeping the depth per event allow any number of hooks to be called on the bean
4746 //and we only will return if one event gets caught in a loop. We do not increment globally
4747 //for each event called.
4748 $this->logicHookDepth[$event]++;
4750 //method defined in 'include/utils/LogicHook.php'
4752 $logicHook = new LogicHook();
4753 $logicHook->setBean($this);
4754 $logicHook->call_custom_logic($this->module_dir, $event, $arguments);
4759 /* When creating a custom field of type Dropdown, it creates an enum row in the DB.
4760 A typical get_list_view_array() result will have the *KEY* value from that drop-down.
4761 Since custom _dom objects are flat-files included in the $app_list_strings variable,
4762 We need to generate a key-key pair to get the true value like so:
4763 ([module]_cstm->fields_meta_data->$app_list_strings->*VALUE*)*/
4764 function getRealKeyFromCustomFieldAssignedKey($name)
4766 if ($this->custom_fields->avail_fields[$name]['ext1'])
4770 elseif ($this->custom_fields->avail_fields[$name]['ext2'])
4774 elseif ($this->custom_fields->avail_fields[$name]['ext3'])
4780 $GLOBALS['log']->fatal("SUGARBEAN: cannot find Real Key for custom field of type dropdown - cannot return Value.");
4785 return $this->custom_fields->avail_fields[$name][$realKey];
4789 function bean_implements($interface)
4794 * Check whether the user has access to a particular view for the current bean/module
4795 * @param $view string required, the view to determine access for i.e. DetailView, ListView...
4796 * @param $is_owner bool optional, this is part of the ACL check if the current user is an owner they will receive different access
4798 function ACLAccess($view,$is_owner='not_set')
4800 global $current_user;
4801 if($current_user->isAdminForModule($this->getACLCategory())) {
4805 if($is_owner == 'not_set')
4808 $is_owner = $this->isOwner($current_user->id);
4811 //if we don't implent acls return true
4812 if(!$this->bean_implements('ACL'))
4814 $view = strtolower($view);
4820 return ACLController::checkAccess($this->module_dir,'list', true);
4823 if( !$is_owner && $not_set && !empty($this->id)){
4824 $class = get_class($this);
4825 $temp = new $class();
4826 if(!empty($this->fetched_row) && !empty($this->fetched_row['id']) && !empty($this->fetched_row['assigned_user_id']) && !empty($this->fetched_row['created_by'])){
4827 $temp->populateFromRow($this->fetched_row);
4829 $temp->retrieve($this->id);
4831 $is_owner = $temp->isOwner($current_user->id);
4833 case 'popupeditview':
4835 return ACLController::checkAccess($this->module_dir,'edit', $is_owner, $this->acltype);
4839 return ACLController::checkAccess($this->module_dir,'view', $is_owner, $this->acltype);
4841 return ACLController::checkAccess($this->module_dir,'delete', $is_owner, $this->acltype);
4843 return ACLController::checkAccess($this->module_dir,'export', $is_owner, $this->acltype);
4845 return ACLController::checkAccess($this->module_dir,'import', true, $this->acltype);
4847 //if it is not one of the above views then it should be implemented on the page level
4851 * Returns true of false if the user_id passed is the owner
4853 * @param GUID $user_id
4856 function isOwner($user_id)
4858 //if we don't have an id we must be the owner as we are creating it
4859 if(!isset($this->id))
4863 //if there is an assigned_user that is the owner
4864 if(isset($this->assigned_user_id))
4866 if($this->assigned_user_id == $user_id) return true;
4871 //other wise if there is a created_by that is the owner
4872 if(isset($this->created_by) && $this->created_by == $user_id)
4880 * Gets there where statement for checking if a user is an owner
4882 * @param GUID $user_id
4885 function getOwnerWhere($user_id)
4887 if(isset($this->field_defs['assigned_user_id']))
4889 return " $this->table_name.assigned_user_id ='$user_id' ";
4891 if(isset($this->field_defs['created_by']))
4893 return " $this->table_name.created_by ='$user_id' ";
4900 * Used in order to manage ListView links and if they should
4901 * links or not based on the ACL permissions of the user
4903 * @return ARRAY of STRINGS
4905 function listviewACLHelper()
4907 $array_assign = array();
4908 if($this->ACLAccess('DetailView'))
4910 $array_assign['MAIN'] = 'a';
4914 $array_assign['MAIN'] = 'span';
4916 return $array_assign;
4920 * returns this bean as an array
4922 * @return array of fields with id, name, access and category
4924 function toArray($dbOnly = false, $stringOnly = false, $upperKeys=false)
4926 static $cache = array();
4929 foreach($this->field_defs as $field=>$data)
4931 if( !$dbOnly || !isset($data['source']) || $data['source'] == 'db')
4932 if(!$stringOnly || is_string($this->$field))
4935 if(!isset($cache[$field])){
4936 $cache[$field] = strtoupper($field);
4938 $arr[$cache[$field]] = $this->$field;
4942 if(isset($this->$field)){
4943 $arr[$field] = $this->$field;
4953 * Converts an array into an acl mapping name value pairs into files
4957 function fromArray($arr)
4959 foreach($arr as $name=>$value)
4961 $this->$name = $value;
4966 * Convert row data from DB format to internal format
4967 * Mostly useful for dates/times
4969 * @return array $row
4971 public function convertRow($row)
4973 foreach($this->field_defs as $name => $fieldDef)
4975 // skip empty fields and non-db fields
4976 if (isset($name) && !empty($row[$name])) {
4977 $row[$name] = $this->convertField($row[$name], $fieldDef);
4984 * Converts the field value based on the provided fieldDef
4985 * @param $fieldvalue
4989 public function convertField($fieldvalue, $fieldDef)
4991 if (!empty($fieldvalue)) {
4992 if (!(isset($fieldDef['source']) &&
4993 !in_array($fieldDef['source'], array('db', 'custom_fields', 'relate'))
4994 && !isset($fieldDef['dbType']))
4996 // fromConvert other fields
4997 $fieldvalue = $this->db->fromConvert($fieldvalue, $this->db->getFieldType($fieldDef));
5004 * Loads a row of data into instance of a bean. The data is passed as an array to this function
5006 * @param array $arr row of data fetched from the database.
5009 * Internal function do not override.
5011 function loadFromRow($arr)
5013 $this->populateFromRow($arr);
5014 $this->processed_dates_times = array();
5015 $this->check_date_relationships_load();
5017 $this->fill_in_additional_list_fields();
5019 if($this->hasCustomFields())$this->custom_fields->fill_relationships();
5020 $this->call_custom_logic("process_record");
5023 function hasCustomFields()
5025 return !empty($GLOBALS['dictionary'][$this->object_name]['custom_fields']);
5029 * Ensure that fields within order by clauses are properly qualified with
5030 * their tablename. This qualification is a requirement for sql server support.
5032 * @param string $order_by original order by from the query
5033 * @param string $qualify prefix for columns in the order by list.
5036 * Internal function do not override.
5038 function create_qualified_order_by( $order_by, $qualify)
5039 { // 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
5040 if (empty($order_by))
5044 $order_by_clause = " ORDER BY ";
5045 $tmp = explode(",", $order_by);
5047 foreach ( $tmp as $stmp)
5049 $stmp = (substr_count($stmp, ".") > 0?trim($stmp):"$qualify." . trim($stmp));
5050 $order_by_clause .= $comma . $stmp;
5053 return $order_by_clause;
5057 * Combined the contents of street field 2 thru 4 into the main field
5059 * @param string $street_field
5062 function add_address_streets(
5066 $street_field_2 = $street_field.'_2';
5067 $street_field_3 = $street_field.'_3';
5068 $street_field_4 = $street_field.'_4';
5069 if ( isset($this->$street_field_2)) {
5070 $this->$street_field .= "\n". $this->$street_field_2;
5071 unset($this->$street_field_2);
5073 if ( isset($this->$street_field_3)) {
5074 $this->$street_field .= "\n". $this->$street_field_3;
5075 unset($this->$street_field_3);
5077 if ( isset($this->$street_field_4)) {
5078 $this->$street_field .= "\n". $this->$street_field_4;
5079 unset($this->$street_field_4);
5081 if ( isset($this->$street_field)) {
5082 $this->$street_field = trim($this->$street_field, "\n");
5086 * Encrpyt and base64 encode an 'encrypt' field type in the bean using Blowfish. The default system key is stored in cache/Blowfish/{keytype}
5087 * @param STRING value -plain text value of the bean field.
5090 function encrpyt_before_save($value)
5092 require_once("include/utils/encryption_utils.php");
5093 return blowfishEncode(blowfishGetKey('encrypt_field'),$value);
5097 * Decode and decrypt a base 64 encoded string with field type 'encrypt' in this bean using Blowfish.
5098 * @param STRING value - an encrypted and base 64 encoded string.
5101 function decrypt_after_retrieve($value)
5103 require_once("include/utils/encryption_utils.php");
5104 return blowfishDecode(blowfishGetKey('encrypt_field'), $value);
5108 * Moved from save() method, functionality is the same, but this is intended to handle
5109 * Optimistic locking functionality.
5111 private function _checkOptimisticLocking($action, $isUpdate){
5112 if($this->optimistic_lock && !isset($_SESSION['o_lock_fs'])){
5113 if(isset($_SESSION['o_lock_id']) && $_SESSION['o_lock_id'] == $this->id && $_SESSION['o_lock_on'] == $this->object_name)
5115 if($action == 'Save' && $isUpdate && isset($this->modified_user_id) && $this->has_been_modified_since($_SESSION['o_lock_dm'], $this->modified_user_id))
5117 $_SESSION['o_lock_class'] = get_class($this);
5118 $_SESSION['o_lock_module'] = $this->module_dir;
5119 $_SESSION['o_lock_object'] = $this->toArray();
5120 $saveform = "<form name='save' id='save' method='POST'>";
5121 foreach($_POST as $key=>$arg)
5123 $saveform .= "<input type='hidden' name='". addslashes($key) ."' value='". addslashes($arg) ."'>";
5125 $saveform .= "</form><script>document.getElementById('save').submit();</script>";
5126 $_SESSION['o_lock_save'] = $saveform;
5127 header('Location: index.php?module=OptimisticLock&action=LockResolve');
5132 unset ($_SESSION['o_lock_object']);
5133 unset ($_SESSION['o_lock_id']);
5134 unset ($_SESSION['o_lock_dm']);
5140 if(isset($_SESSION['o_lock_object'])) { unset ($_SESSION['o_lock_object']); }
5141 if(isset($_SESSION['o_lock_id'])) { unset ($_SESSION['o_lock_id']); }
5142 if(isset($_SESSION['o_lock_dm'])) { unset ($_SESSION['o_lock_dm']); }
5143 if(isset($_SESSION['o_lock_fs'])) { unset ($_SESSION['o_lock_fs']); }
5144 if(isset($_SESSION['o_lock_save'])) { unset ($_SESSION['o_lock_save']); }
5149 * Send assignment notifications and invites for meetings and calls
5151 private function _sendNotifications($check_notify){
5152 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.
5153 && !$this->isOwner($this->created_by) ) // cn: bug 42727 no need to send email to owner (within workflow)
5155 $admin = new Administration();
5156 $admin->retrieveSettings();
5157 $sendNotifications = false;
5159 if ($admin->settings['notify_on'])
5161 $GLOBALS['log']->info("Notifications: user assignment has changed, checking if user receives notifications");
5162 $sendNotifications = true;
5164 elseif(isset($_REQUEST['send_invites']) && $_REQUEST['send_invites'] == 1)
5166 // cn: bug 5795 Send Invites failing for Contacts
5167 $sendNotifications = true;
5171 $GLOBALS['log']->info("Notifications: not sending e-mail, notify_on is set to OFF");
5175 if($sendNotifications == true)
5177 $notify_list = $this->get_notification_recipients();
5178 foreach ($notify_list as $notify_user)
5180 $this->send_assignment_notifications($notify_user, $admin);
5188 * Called from ImportFieldSanitize::relate(), when creating a new bean in a related module. Will
5189 * copies fields over from the current bean into the related. Designed to be overriden in child classes.
5191 * @param SugarBean $newbean newly created related bean
5193 public function populateRelatedBean(
5200 * Called during the import process before a bean save, to handle any needed pre-save logic when
5201 * importing a record
5203 public function beforeImportSave()
5208 * Called during the import process after a bean save, to handle any needed post-save logic when
5209 * importing a record
5211 public function afterImportSave()
5216 * This function is designed to cache references to field arrays that were previously stored in the
5217 * bean files and have since been moved to seperate files. Was previously in include/CacheHandler.php
5220 * @param $module_dir string the module directory
5221 * @param $module string the name of the module
5222 * @param $key string the type of field array we are referencing, i.e. list_fields, column_fields, required_fields
5224 private function _loadCachedArray(
5230 static $moduleDefs = array();
5232 $fileName = 'field_arrays.php';
5234 $cache_key = "load_cached_array.$module_dir.$module.$key";
5235 $result = sugar_cache_retrieve($cache_key);
5238 // Use SugarCache::EXTERNAL_CACHE_NULL_VALUE to store null values in the cache.
5239 if($result == SugarCache::EXTERNAL_CACHE_NULL_VALUE)
5247 if(file_exists('modules/'.$module_dir.'/'.$fileName))
5249 // If the data was not loaded, try loading again....
5250 if(!isset($moduleDefs[$module]))
5252 include('modules/'.$module_dir.'/'.$fileName);
5253 $moduleDefs[$module] = $fields_array;
5255 // Now that we have tried loading, make sure it was loaded
5256 if(empty($moduleDefs[$module]) || empty($moduleDefs[$module][$module][$key]))
5258 // It was not loaded.... Fail. Cache null to prevent future repeats of this calculation
5259 sugar_cache_put($cache_key, SugarCache::EXTERNAL_CACHE_NULL_VALUE);
5263 // It has been loaded, cache the result.
5264 sugar_cache_put($cache_key, $moduleDefs[$module][$module][$key]);
5265 return $moduleDefs[$module][$module][$key];
5268 // It was not loaded.... Fail. Cache null to prevent future repeats of this calculation
5269 sugar_cache_put($cache_key, SugarCache::EXTERNAL_CACHE_NULL_VALUE);
5274 * Returns the ACL category for this module; defaults to the SugarBean::$acl_category if defined
5275 * otherwise it is SugarBean::$module_dir
5279 public function getACLCategory()
5281 return !empty($this->acl_category)?$this->acl_category:$this->module_dir;
5285 * Returns the query used for the export functionality for a module. Override this method if you wish
5286 * to have a custom query to pull this data together instead
5288 * @param string $order_by
5289 * @param string $where
5290 * @return string SQL query
5292 public function create_export_query($order_by, $where)
5294 return $this->create_new_list_query($order_by, $where, array(), array(), 0, '', false, $this, true, true);