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);
562 * Returns the value for the requested field.
564 * When a row of data is fetched using the bean, all fields are created as variables in the context
565 * of the bean and then fetched values are set in these variables.
567 * @param string field name,
568 * @return varies Field value.
570 * Internal function, do not override.
572 function getFieldValue($name)
574 if (!isset($this->$name)){
577 if($this->$name === TRUE){
580 if($this->$name === FALSE){
587 * Basically undoes the effects of SugarBean::populateDefaultValues(); this method is best called right after object
590 public function unPopulateDefaultValues()
592 if ( !is_array($this->field_defs) )
595 foreach ($this->field_defs as $field => $value) {
596 if( !empty($this->$field)
597 && ((isset($value['default']) && $this->$field == $value['default']) || (!empty($value['display_default']) && $this->$field == $value['display_default']))
599 $this->$field = null;
602 if(!empty($this->$field) && !empty($value['display_default']) && in_array($value['type'], array('date', 'datetime', 'datetimecombo')) &&
603 $this->$field == $this->parseDateDefault($value['display_default'], ($value['type'] != 'date'))) {
604 $this->$field = null;
610 * Create date string from default value
612 * @param string $value
613 * @param bool $time Should be expect time set too?
616 protected function parseDateDefault($value, $time = false)
620 $dtAry = explode('&', $value, 2);
621 $dateValue = $timedate->getNow(true)->modify($dtAry[0]);
622 if(!empty($dtAry[1])) {
623 $timeValue = $timedate->fromString($dtAry[1]);
624 $dateValue->setTime($timeValue->hour, $timeValue->min, $timeValue->sec);
626 return $timedate->asUser($dateValue);
628 return $timedate->asUserDate($timedate->getNow(true)->modify($value));
632 function populateDefaultValues($force=false){
633 if ( !is_array($this->field_defs) )
635 foreach($this->field_defs as $field=>$value){
636 if((isset($value['default']) || !empty($value['display_default'])) && ($force || empty($this->$field))){
637 $type = $value['type'];
641 if(!empty($value['display_default'])){
642 $this->$field = $this->parseDateDefault($value['display_default']);
646 case 'datetimecombo':
647 if(!empty($value['display_default'])){
648 $this->$field = $this->parseDateDefault($value['display_default'], true);
652 if(empty($value['default']) && !empty($value['display_default']))
653 $this->$field = $value['display_default'];
655 $this->$field = $value['default'];
658 if ( isset($value['default']) && $value['default'] !== '' ) {
659 $this->$field = htmlentities($value['default'], ENT_QUOTES, 'UTF-8');
670 * Removes relationship metadata cache.
672 * Every module that has relationships defined with other modules, has this meta data cached. The cache is
673 * stores in 2 locations: relationships table and file system. This method clears the cache from both locations.
675 * @param string $key module whose meta cache is to be cleared.
676 * @param string $db database handle.
677 * @param string $tablename table name
678 * @param string $dictionary vardef for the module
679 * @param string $module_dir name of subdirectory where module is installed.
684 * Internal function, do not override.
686 function removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir)
688 //load the module dictionary if not supplied.
689 if ((!isset($dictionary) or empty($dictionary)) && !empty($module_dir))
691 $filename='modules/'. $module_dir . '/vardefs.php';
692 if(file_exists($filename))
697 if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
699 $GLOBALS['log']->fatal("removeRelationshipMeta: Metadata for table ".$tablename. " does not exist");
700 display_notice("meta data absent for table ".$tablename." keyed to $key ");
704 if (isset($dictionary[$key]['relationships']))
706 $RelationshipDefs = $dictionary[$key]['relationships'];
707 foreach ($RelationshipDefs as $rel_name)
709 Relationship::delete($rel_name,$db);
717 * This method has been deprecated.
719 * @see removeRelationshipMeta()
720 * @deprecated 4.5.1 - Nov 14, 2006
723 function remove_relationship_meta($key,$db,$log,$tablename,$dictionary,$module_dir)
725 SugarBean::removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
730 * Populates the relationship meta for a module.
732 * It is called during setup/install. It is used statically to create relationship meta data for many-to-many tables.
734 * @param string $key name of the object.
735 * @param object $db database handle.
736 * @param string $tablename table, meta data is being populated for.
737 * @param array dictionary vardef dictionary for the object. *
738 * @param string module_dir name of subdirectory where module is installed.
739 * @param boolean $iscustom Optional,set to true if module is installed in a custom directory. Default value is false.
742 * Internal function, do not override.
744 function createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir,$iscustom=false)
746 //load the module dictionary if not supplied.
747 if (empty($dictionary) && !empty($module_dir))
751 $filename='custom/modules/' . $module_dir . '/Ext/Vardefs/vardefs.ext.php';
757 // a very special case for the Employees module
758 // this must be done because the Employees/vardefs.php does an include_once on
760 $filename='modules/Users/vardefs.php';
764 $filename='modules/'. $module_dir . '/vardefs.php';
768 if(file_exists($filename))
771 // cn: bug 7679 - dictionary entries defined as $GLOBALS['name'] not found
772 if(empty($dictionary) || !empty($GLOBALS['dictionary'][$key]))
774 $dictionary = $GLOBALS['dictionary'];
779 $GLOBALS['log']->debug("createRelationshipMeta: no metadata file found" . $filename);
784 if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
786 $GLOBALS['log']->fatal("createRelationshipMeta: Metadata for table ".$tablename. " does not exist");
787 display_notice("meta data absent for table ".$tablename." keyed to $key ");
791 if (isset($dictionary[$key]['relationships']))
794 $RelationshipDefs = $dictionary[$key]['relationships'];
798 $beanList_ucase=array_change_key_case ( $beanList ,CASE_UPPER);
799 foreach ($RelationshipDefs as $rel_name=>$rel_def)
801 if (isset($rel_def['lhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['lhs_module'])])) {
802 $GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' lhs module is missing ' . $rel_def['lhs_module']);
805 if (isset($rel_def['rhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['rhs_module'])])) {
806 $GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' rhs module is missing ' . $rel_def['rhs_module']);
811 //check whether relationship exists or not first.
812 if (Relationship::exists($rel_name,$db))
814 $GLOBALS['log']->debug('Skipping, reltionship already exists '.$rel_name);
818 $seed = BeanFactory::getBean("Relationships");
819 $keys = array_keys($seed->field_defs);
821 foreach($keys as $key)
825 $toInsert[$key] = create_guid();
827 else if ($key == "relationship_name")
829 $toInsert[$key] = $rel_name;
831 else if (isset($rel_def[$key]))
833 $toInsert[$key] = $rel_def[$key];
835 //todo specify defaults if meta not defined.
839 $column_list = implode(",", array_keys($toInsert));
840 $value_list = "'" . implode("','", array_values($toInsert)) . "'";
842 //create the record. todo add error check.
843 $insert_string = "INSERT into relationships (" .$column_list. ") values (".$value_list.")";
844 $db->query($insert_string, true);
851 //log informational message stating no relationships meta was set for this bean.
857 * This method has been deprecated.
858 * @see createRelationshipMeta()
859 * @deprecated 4.5.1 - Nov 14, 2006
862 function create_relationship_meta($key,&$db,&$log,$tablename,$dictionary,$module_dir)
864 SugarBean::createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
869 * Loads the request relationship. This method should be called before performing any operations on the related data.
871 * This method searches the vardef array for the requested attribute's definition. If the attribute is of the type
872 * link then it creates a similary named variable and loads the relationship definition.
874 * @param string $rel_name relationship/attribute name.
877 function load_relationship($rel_name)
879 $GLOBALS['log']->debug("SugarBean[{$this->object_name}].load_relationships, Loading relationship (".$rel_name.").");
881 if (empty($rel_name))
883 $GLOBALS['log']->error("SugarBean.load_relationships, Null relationship name passed.");
886 $fieldDefs = $this->getFieldDefinitions();
888 //find all definitions of type link.
889 if (!empty($fieldDefs[$rel_name]))
891 //initialize a variable of type Link
892 require_once('data/Link2.php');
893 $class = load_link_class($fieldDefs[$rel_name]);
894 if (isset($this->$rel_name) && $this->$rel_name instanceof $class) {
897 //if rel_name is provided, search the fieldef array keys by name.
898 if (isset($fieldDefs[$rel_name]['type']) && $fieldDefs[$rel_name]['type'] == 'link')
900 if ($class == "Link2")
901 $this->$rel_name = new $class($rel_name, $this);
903 $this->$rel_name = new $class($fieldDefs[$rel_name]['relationship'], $this, $fieldDefs[$rel_name]);
905 if (empty($this->$rel_name) ||
906 (method_exists($this->$rel_name, "loadedSuccesfully") && !$this->$rel_name->loadedSuccesfully()))
908 unset($this->$rel_name);
914 $GLOBALS['log']->debug("SugarBean.load_relationships, Error Loading relationship (".$rel_name.")");
919 * Loads all attributes of type link.
921 * DO NOT CALL THIS FUNCTION IF YOU CAN AVOID IT. Please use load_relationship directly instead.
923 * Method searches the implmenting module's vardef file for attributes of type link, and for each attribute
924 * create a similary named variable and load the relationship definition.
928 * Internal function, do not override.
930 function load_relationships()
932 $GLOBALS['log']->debug("SugarBean.load_relationships, Loading all relationships of type link.");
933 $linked_fields=$this->get_linked_fields();
934 foreach($linked_fields as $name=>$properties)
936 $this->load_relationship($name);
941 * Returns an array of beans of related data.
943 * For instance, if an account is related to 10 contacts , this function will return an array of contacts beans (10)
944 * with each bean representing a contact record.
945 * Method will load the relationship if not done so already.
947 * @param string $field_name relationship to be loaded.
948 * @param string $bean name class name of the related bean.
949 * @param array $sort_array optional, unused
950 * @param int $begin_index Optional, default 0, unused.
951 * @param int $end_index Optional, default -1
952 * @param int $deleted Optional, Default 0, 0 adds deleted=0 filter, 1 adds deleted=1 filter.
953 * @param string $optional_where, Optional, default empty.
955 * Internal function, do not override.
957 function get_linked_beans($field_name,$bean_name, $sort_array = array(), $begin_index = 0, $end_index = -1,
958 $deleted=0, $optional_where="")
960 if($this->load_relationship($field_name))
961 return array_values($this->$field_name->getBeans());
967 * Returns an array of fields that are of type link.
969 * @return array List of fields.
971 * Internal function, do not override.
973 function get_linked_fields()
976 $linked_fields=array();
978 // require_once('data/Link.php');
980 $fieldDefs = $this->getFieldDefinitions();
982 //find all definitions of type link.
983 if (!empty($fieldDefs))
985 foreach ($fieldDefs as $name=>$properties)
987 if (array_search('link',$properties) === 'type')
989 $linked_fields[$name]=$properties;
994 return $linked_fields;
998 * Returns an array of fields that are able to be Imported into
999 * i.e. 'importable' not set to 'false'
1001 * @return array List of fields.
1003 * Internal function, do not override.
1005 function get_importable_fields()
1007 $importableFields = array();
1009 $fieldDefs= $this->getFieldDefinitions();
1011 if (!empty($fieldDefs)) {
1012 foreach ($fieldDefs as $key=>$value_array) {
1013 if ( (isset($value_array['importable'])
1014 && (is_string($value_array['importable']) && $value_array['importable'] == 'false'
1015 || is_bool($value_array['importable']) && $value_array['importable'] == false))
1016 || (isset($value_array['type']) && $value_array['type'] == 'link')
1017 || (isset($value_array['auto_increment'])
1018 && ($value_array['type'] == true || $value_array['type'] == 'true')) ) {
1019 // only allow import if we force it
1020 if (isset($value_array['importable'])
1021 && (is_string($value_array['importable']) && $value_array['importable'] == 'true'
1022 || is_bool($value_array['importable']) && $value_array['importable'] == true)) {
1023 $importableFields[$key]=$value_array;
1027 $importableFields[$key]=$value_array;
1032 return $importableFields;
1036 * Returns an array of fields that are of type relate.
1038 * @return array List of fields.
1040 * Internal function, do not override.
1042 function get_related_fields()
1045 $related_fields=array();
1047 // require_once('data/Link.php');
1049 $fieldDefs = $this->getFieldDefinitions();
1051 //find all definitions of type link.
1052 if (!empty($fieldDefs))
1054 foreach ($fieldDefs as $name=>$properties)
1056 if (array_search('relate',$properties) === 'type')
1058 $related_fields[$name]=$properties;
1063 return $related_fields;
1067 * Returns an array of fields that are required for import
1071 function get_import_required_fields()
1073 $importable_fields = $this->get_importable_fields();
1074 $required_fields = array();
1076 foreach ( $importable_fields as $name => $properties ) {
1077 if ( isset($properties['importable']) && is_string($properties['importable']) && $properties['importable'] == 'required' ) {
1078 $required_fields[$name] = $properties;
1082 return $required_fields;
1086 * Iterates through all the relationships and deletes all records for reach relationship.
1088 * @param string $id Primary key value of the parent reocrd
1090 function delete_linked($id)
1092 $linked_fields=$this->get_linked_fields();
1093 foreach ($linked_fields as $name => $value)
1095 if ($this->load_relationship($name))
1097 $this->$name->delete($id);
1101 $GLOBALS['log']->fatal("error loading relationship $name");
1107 * Creates tables for the module implementing the class.
1108 * If you override this function make sure that your code can handles table creation.
1111 function create_tables()
1115 $key = $this->getObjectName();
1116 if (!array_key_exists($key, $dictionary))
1118 $GLOBALS['log']->fatal("create_tables: Metadata for table ".$this->table_name. " does not exist");
1119 display_notice("meta data absent for table ".$this->table_name." keyed to $key ");
1123 if(!$this->db->tableExists($this->table_name))
1125 $this->db->createTable($this);
1126 if($this->bean_implements('ACL')){
1127 if(!empty($this->acltype)){
1128 ACLAction::addActions($this->getACLCategory(), $this->acltype);
1130 ACLAction::addActions($this->getACLCategory());
1136 echo "Table already exists : $this->table_name<br>";
1138 if($this->is_AuditEnabled()){
1139 if (!$this->db->tableExists($this->get_audit_table_name())) {
1140 $this->create_audit_table();
1148 * Delete the primary table for the module implementing the class.
1149 * If custom fields were added to this table/module, the custom table will be removed too, along with the cache
1150 * entries that define the custom fields.
1153 function drop_tables()
1156 $key = $this->getObjectName();
1157 if (!array_key_exists($key, $dictionary))
1159 $GLOBALS['log']->fatal("drop_tables: Metadata for table ".$this->table_name. " does not exist");
1160 echo "meta data absent for table ".$this->table_name."<br>\n";
1162 if(empty($this->table_name))return;
1163 if ($this->db->tableExists($this->table_name))
1165 $this->db->dropTable($this);
1166 if ($this->db->tableExists($this->table_name. '_cstm'))
1168 $this->db->dropTableName($this->table_name. '_cstm');
1169 DynamicField::deleteCache();
1171 if ($this->db->tableExists($this->get_audit_table_name())) {
1172 $this->db->dropTableName($this->get_audit_table_name());
1181 * Loads the definition of custom fields defined for the module.
1182 * Local file system cache is created as needed.
1184 * @param string $module_name setting up custom fields for this module.
1185 * @param boolean $clean_load Optional, default true, rebuilds the cache if set to true.
1187 function setupCustomFields($module_name, $clean_load=true)
1189 $this->custom_fields = new DynamicField($module_name);
1190 $this->custom_fields->setup($this);
1195 * Cleans char, varchar, text, etc. fields of XSS type materials
1197 function cleanBean() {
1198 foreach($this->field_defs as $key => $def) {
1200 if (isset($def['type'])) {
1203 if(isset($def['dbType']))
1204 $type .= $def['dbType'];
1206 if((strpos($type, 'char') !== false ||
1207 strpos($type, 'text') !== false ||
1211 $str = from_html($this->$key);
1212 // Julian's XSS cleaner
1213 $potentials = clean_xss($str, false);
1215 if(is_array($potentials) && !empty($potentials)) {
1216 foreach($potentials as $bad) {
1217 $str = str_replace($bad, "", $str);
1219 $this->$key = to_html($str);
1226 * Implements a generic insert and update logic for any SugarBean
1227 * This method only works for subclasses that implement the same variable names.
1228 * This method uses the presence of an id field that is not null to signify and update.
1229 * The id field should not be set otherwise.
1231 * @param boolean $check_notify Optional, default false, if set to true assignee of the record is notified via email.
1232 * @todo Add support for field type validation and encoding of parameters.
1234 function save($check_notify = FALSE)
1236 $this->in_save = true;
1237 // cn: SECURITY - strip XSS potential vectors
1239 // This is used so custom/3rd-party code can be upgraded with fewer issues, this will be removed in a future release
1240 $this->fixUpFormatting();
1242 global $current_user, $action;
1245 if(empty($this->id))
1250 if ( $this->new_with_id == true )
1254 if(empty($this->date_modified) || $this->update_date_modified)
1256 $this->date_modified = $GLOBALS['timedate']->nowDb();
1259 $this->_checkOptimisticLocking($action, $isUpdate);
1261 if(!empty($this->modified_by_name)) $this->old_modified_by_name = $this->modified_by_name;
1262 if($this->update_modified_by)
1264 $this->modified_user_id = 1;
1266 if (!empty($current_user))
1268 $this->modified_user_id = $current_user->id;
1269 $this->modified_by_name = $current_user->user_name;
1272 if ($this->deleted != 1)
1276 if (empty($this->date_entered))
1278 $this->date_entered = $this->date_modified;
1280 if($this->set_created_by == true)
1282 // created by should always be this user
1283 $this->created_by = (isset($current_user)) ? $current_user->id : "";
1285 if( $this->new_with_id == false)
1287 $this->id = create_guid();
1293 require_once("data/BeanFactory.php");
1294 BeanFactory::registerBean($this->module_name, $this);
1296 if (empty($GLOBALS['updating_relationships']) && empty($GLOBALS['saving_relationships']) && empty ($GLOBALS['resavingRelatedBeans']))
1298 $GLOBALS['saving_relationships'] = true;
1299 // let subclasses save related field changes
1300 $this->save_relationship_changes($isUpdate);
1301 $GLOBALS['saving_relationships'] = false;
1303 if($isUpdate && !$this->update_date_entered)
1305 unset($this->date_entered);
1307 // call the custom business logic
1308 $custom_logic_arguments['check_notify'] = $check_notify;
1311 $this->call_custom_logic("before_save", $custom_logic_arguments);
1312 unset($custom_logic_arguments);
1314 if(isset($this->custom_fields))
1316 $this->custom_fields->bean = $this;
1317 $this->custom_fields->save($isUpdate);
1320 // use the db independent query generator
1321 $this->preprocess_fields_on_save();
1323 //construct the SQL to create the audit record if auditing is enabled.
1324 $dataChanges=array();
1325 if ($this->is_AuditEnabled()) {
1326 if ($isUpdate && !isset($this->fetched_row)) {
1327 $GLOBALS['log']->debug('Auditing: Retrieve was not called, audit record will not be created.');
1329 $dataChanges=$this->db->getDataChanges($this);
1333 $this->_sendNotifications($check_notify);
1336 $this->db->update($this);
1338 $this->db->insert($this);
1341 if (!empty($dataChanges) && is_array($dataChanges))
1343 foreach ($dataChanges as $change)
1345 $this->db->save_audit_records($this,$change);
1350 //If we aren't in setup mode and we have a current user and module, then we track
1351 if(isset($GLOBALS['current_user']) && isset($this->module_dir))
1353 $this->track_view($current_user->id, $this->module_dir, 'save');
1356 $this->call_custom_logic('after_save', '');
1358 //Now that the record has been saved, we don't want to insert again on further saves
1359 $this->new_with_id = false;
1360 $this->in_save = false;
1366 * Performs a check if the record has been modified since the specified date
1368 * @param date $date Datetime for verification
1369 * @param string $modified_user_id User modified by
1371 function has_been_modified_since($date, $modified_user_id)
1373 global $current_user;
1374 $date = $this->db->convert($this->db->quoted($date), 'datetime');
1375 if (isset($current_user))
1377 $query = "SELECT date_modified FROM $this->table_name WHERE id='$this->id' AND modified_user_id != '$current_user->id'
1378 AND (modified_user_id != '$modified_user_id' OR date_modified > $date)";
1379 $result = $this->db->query($query);
1381 if($this->db->fetchByAssoc($result))
1390 * Determines which users receive a notification
1392 function get_notification_recipients() {
1393 $notify_user = new User();
1394 $notify_user->retrieve($this->assigned_user_id);
1395 $this->new_assigned_user_name = $notify_user->full_name;
1397 $GLOBALS['log']->info("Notifications: recipient is $this->new_assigned_user_name");
1399 $user_list = array($notify_user);
1402 //send notifications to followers, but ensure to not query for the assigned_user.
1403 return SugarFollowing::getFollowers($this, $notify_user);
1408 * Handles sending out email notifications when items are first assigned to users
1410 * @param string $notify_user user to notify
1411 * @param string $admin the admin user that sends out the notification
1413 function send_assignment_notifications($notify_user, $admin)
1415 global $current_user;
1417 if(($this->object_name == 'Meeting' || $this->object_name == 'Call') || $notify_user->receive_notifications)
1419 $sendToEmail = $notify_user->emailAddress->getPrimaryAddress($notify_user);
1421 if(empty($sendToEmail)) {
1422 $GLOBALS['log']->warn("Notifications: no e-mail address set for user {$notify_user->user_name}, cancelling send");
1426 $notify_mail = $this->create_notification_email($notify_user);
1427 $notify_mail->setMailerForSystem();
1429 if(empty($admin->settings['notify_send_from_assigning_user'])) {
1430 $notify_mail->From = $admin->settings['notify_fromaddress'];
1431 $notify_mail->FromName = (empty($admin->settings['notify_fromname'])) ? "" : $admin->settings['notify_fromname'];
1433 // Send notifications from the current user's e-mail (ifset)
1434 $fromAddress = $current_user->emailAddress->getReplyToAddress($current_user);
1435 $fromAddress = !empty($fromAddress) ? $fromAddress : $admin->settings['notify_fromaddress'];
1436 $notify_mail->From = $fromAddress;
1437 //Use the users full name is available otherwise default to system name
1438 $from_name = !empty($admin->settings['notify_fromname']) ? $admin->settings['notify_fromname'] : "";
1439 $from_name = !empty($current_user->full_name) ? $current_user->full_name : $from_name;
1440 $notify_mail->FromName = $from_name;
1443 $oe = new OutboundEmail();
1444 $oe = $oe->getUserMailerSettings($current_user);
1445 //only send if smtp server is defined
1447 $smtpVerified = false;
1449 //first check the user settings
1450 if(!empty($oe->mail_smtpserver)){
1451 $smtpVerified = true;
1454 //if still not verified, check against the system settings
1455 if (!$smtpVerified){
1456 $oe = $oe->getSystemMailerSettings();
1457 if(!empty($oe->mail_smtpserver)){
1458 $smtpVerified = true;
1461 //if smtp was not verified against user or system, then do not send out email
1462 if (!$smtpVerified){
1463 $GLOBALS['log']->fatal("Notifications: error sending e-mail, smtp server was not found ");
1468 if(!$notify_mail->Send()) {
1469 $GLOBALS['log']->fatal("Notifications: error sending e-mail (method: {$notify_mail->Mailer}), (error: {$notify_mail->ErrorInfo})");
1471 $GLOBALS['log']->fatal("Notifications: e-mail successfully sent");
1479 * This function handles create the email notifications email.
1480 * @param string $notify_user the user to send the notification email to
1482 function create_notification_email($notify_user) {
1483 global $sugar_version;
1484 global $sugar_config;
1485 global $app_list_strings;
1486 global $current_user;
1489 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
1492 require_once("include/SugarPHPMailer.php");
1494 $notify_address = $notify_user->emailAddress->getPrimaryAddress($notify_user);
1495 $notify_name = $notify_user->full_name;
1496 $GLOBALS['log']->debug("Notifications: user has e-mail defined");
1498 $notify_mail = new SugarPHPMailer();
1499 $notify_mail->AddAddress($notify_address,$locale->translateCharsetMIME(trim($notify_name), 'UTF-8', $OBCharset));
1501 if(empty($_SESSION['authenticated_user_language'])) {
1502 $current_language = $sugar_config['default_language'];
1504 $current_language = $_SESSION['authenticated_user_language'];
1506 $xtpl = new XTemplate(get_notify_template_file($current_language));
1507 if($this->module_dir == "Cases") {
1508 $template_name = "Case"; //we should use Case, you can refer to the en_us.notify_template.html.
1511 $template_name = $beanList[$this->module_dir]; //bug 20637, in workflow this->object_name = strange chars.
1514 $this->current_notify_user = $notify_user;
1516 if(in_array('set_notification_body', get_class_methods($this))) {
1517 $xtpl = $this->set_notification_body($xtpl, $this);
1519 $xtpl->assign("OBJECT", $this->object_name);
1520 $template_name = "Default";
1522 if(!empty($_SESSION["special_notification"]) && $_SESSION["special_notification"]) {
1523 $template_name = $beanList[$this->module_dir].'Special';
1525 if($this->special_notification) {
1526 $template_name = $beanList[$this->module_dir].'Special';
1528 $xtpl->assign("ASSIGNED_USER", $this->new_assigned_user_name);
1529 $xtpl->assign("ASSIGNER", $current_user->name);
1532 if(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
1533 $port = $_SERVER['SERVER_PORT'];
1536 if (!isset($_SERVER['HTTP_HOST'])) {
1537 $_SERVER['HTTP_HOST'] = '';
1540 $httpHost = $_SERVER['HTTP_HOST'];
1542 if($colon = strpos($httpHost, ':')) {
1543 $httpHost = substr($httpHost, 0, $colon);
1546 $parsedSiteUrl = parse_url($sugar_config['site_url']);
1547 $host = $parsedSiteUrl['host'];
1548 if(!isset($parsedSiteUrl['port'])) {
1549 $parsedSiteUrl['port'] = 80;
1552 $port = ($parsedSiteUrl['port'] != 80) ? ":".$parsedSiteUrl['port'] : '';
1553 $path = !empty($parsedSiteUrl['path']) ? $parsedSiteUrl['path'] : "";
1554 $cleanUrl = "{$parsedSiteUrl['scheme']}://{$host}{$port}{$path}";
1556 $xtpl->assign("URL", $cleanUrl."/index.php?module={$this->module_dir}&action=DetailView&record={$this->id}");
1557 $xtpl->assign("SUGAR", "Sugar v{$sugar_version}");
1558 $xtpl->parse($template_name);
1559 $xtpl->parse($template_name . "_Subject");
1561 $notify_mail->Body = from_html(trim($xtpl->text($template_name)));
1562 $notify_mail->Subject = from_html($xtpl->text($template_name . "_Subject"));
1564 // cn: bug 8568 encode notify email in User's outbound email encoding
1565 $notify_mail->prepForOutbound();
1567 return $notify_mail;
1571 * This function is a good location to save changes that have been made to a relationship.
1572 * This should be overriden in subclasses that have something to save.
1574 * @param $is_update true if this save is an update.
1576 function save_relationship_changes($is_update, $exclude=array())
1578 $new_rel_id = false;
1579 $new_rel_link = false;
1581 //this allows us to dynamically relate modules without adding it to the relationship_fields array
1582 if(!empty($_REQUEST['relate_id']) && !empty($_REQUEST['relate_to']) && !in_array($_REQUEST['relate_to'], $exclude) && $_REQUEST['relate_id'] != $this->id){
1583 $new_rel_id = $_REQUEST['relate_id'];
1584 $new_rel_relname = $_REQUEST['relate_to'];
1585 if(!empty($this->in_workflow) && !empty($this->not_use_rel_in_req)) {
1586 $new_rel_id = !empty($this->new_rel_id) ? $this->new_rel_id : '';
1587 $new_rel_relname = !empty($this->new_rel_relname) ? $this->new_rel_relname : '';
1589 $new_rel_link = $new_rel_relname;
1590 //Try to find the link in this bean based on the relationship
1591 foreach ( $this->field_defs as $key => $def ) {
1592 if (isset($def['type']) && $def['type'] == 'link'
1593 && isset($def['relationship']) && $def['relationship'] == $new_rel_relname) {
1594 $new_rel_link = $key;
1600 // First we handle the preset fields listed in the fixed relationship_fields array hardcoded into the OOB beans
1601 // TODO: remove this mechanism and replace with mechanism exclusively based on the vardefs
1602 if (isset($this->relationship_fields) && is_array($this->relationship_fields))
1604 foreach ($this->relationship_fields as $id=>$rel_name)
1607 if(in_array($id, $exclude))continue;
1609 if(!empty($this->$id))
1611 $GLOBALS['log']->debug('save_relationship_changes(): From relationship_field array - adding a relationship record: '.$rel_name . ' = ' . $this->$id);
1612 //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
1613 if($this->$id == $new_rel_id){
1614 $new_rel_id = false;
1616 $this->load_relationship($rel_name);
1617 $this->$rel_name->add($this->$id);
1622 //if before value is not empty then attempt to delete relationship
1623 if(!empty($this->rel_fields_before_value[$id]))
1625 $GLOBALS['log']->debug('save_relationship_changes(): From relationship_field array - attempting to remove the relationship record, using relationship attribute'.$rel_name);
1626 $this->load_relationship($rel_name);
1627 $this->$rel_name->delete($this->id,$this->rel_fields_before_value[$id]);
1633 /* Next, we'll attempt to update all of the remaining relate fields in the vardefs that have 'save' set in their field_def
1634 Only the 'save' fields should be saved as some vardef entries today are not for display only purposes and break the application if saved
1635 If the vardef has entries for field <a> of type relate, where a->id_name = <b> and field <b> of type link
1636 then we receive a value for b from the MVC in the _REQUEST, and it should be set in the bean as $this->$b
1639 foreach ( $this->field_defs as $def )
1641 if ($def [ 'type' ] == 'relate' && isset ( $def [ 'id_name'] ) && isset ( $def [ 'link'] ) && isset ( $def[ 'save' ]) )
1643 if ( in_array( $def['id_name'], $exclude) || in_array( $def['id_name'], $this->relationship_fields ) )
1644 continue ; // continue to honor the exclude array and exclude any relationships that will be handled by the relationship_fields mechanism
1646 $linkField = $def [ 'link' ] ;
1647 if (isset( $this->field_defs[$linkField ] ))
1649 $linkfield = $this->field_defs[$linkField] ;
1651 if ($this->load_relationship ( $linkField))
1653 $idName = $def['id_name'];
1655 if (!empty($this->rel_fields_before_value[$idName]) && empty($this->$idName))
1657 //if before value is not empty then attempt to delete relationship
1658 $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' ]]}");
1659 $this->$def ['link' ]->delete($this->id, $this->rel_fields_before_value[$def [ 'id_name' ]] );
1662 if (!empty($this->$idName) && is_string($this->$idName))
1664 $GLOBALS['log']->debug("save_relationship_changes(): From field_defs - attempting to add a relationship record - {$def [ 'link' ]} = {$this->$def [ 'id_name' ]}" );
1666 $this->$linkField->add($this->$idName);
1669 $GLOBALS['log']->fatal("Failed to load relationship {$linkField} while saving {$this->module_dir}");
1675 // Finally, we update a field listed in the _REQUEST['*/relate_id']/_REQUEST['relate_to'] mechanism (if it hasn't already been updated above)
1676 if(!empty($new_rel_id)){
1678 if($this->load_relationship($new_rel_link)){
1679 $this->$new_rel_link->add($new_rel_id);
1682 $lower_link = strtolower($new_rel_link);
1683 if($this->load_relationship($lower_link)){
1684 $this->$lower_link->add($new_rel_id);
1687 require_once('data/Link2.php');
1688 $rel = Relationship::retrieve_by_modules($new_rel_link, $this->module_dir, $GLOBALS['db'], 'many-to-many');
1691 foreach($this->field_defs as $field=>$def){
1692 if($def['type'] == 'link' && !empty($def['relationship']) && $def['relationship'] == $rel){
1693 $this->load_relationship($field);
1694 $this->$field->add($new_rel_id);
1700 //ok so we didn't find it in the field defs let's save it anyway if we have the relationshp
1702 $this->$rel=new Link2($rel, $this, array());
1703 $this->$rel->add($new_rel_id);
1712 * This function retrieves a record of the appropriate type from the DB.
1713 * It fills in all of the fields from the DB into the object it was called on.
1715 * @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.
1716 * @return this - The object that it was called apon or null if exactly 1 record was not found.
1720 function check_date_relationships_load()
1722 global $disable_date_format;
1724 if (empty($timedate))
1725 $timedate=TimeDate::getInstance();
1727 if(empty($this->field_defs))
1731 foreach($this->field_defs as $fieldDef)
1733 $field = $fieldDef['name'];
1734 if(!isset($this->processed_dates_times[$field]))
1736 $this->processed_dates_times[$field] = '1';
1737 if(empty($this->$field)) continue;
1738 if($field == 'date_modified' || $field == 'date_entered')
1740 $this->$field = $this->db->fromConvert($this->$field, 'datetime');
1741 if(empty($disable_date_format)) {
1742 $this->$field = $timedate->to_display_date_time($this->$field);
1745 elseif(isset($this->field_name_map[$field]['type']))
1747 $type = $this->field_name_map[$field]['type'];
1749 if($type == 'relate' && isset($this->field_name_map[$field]['custom_module']))
1751 $type = $this->field_name_map[$field]['type'];
1756 if($this->$field == '0000-00-00')
1759 } elseif(!empty($this->field_name_map[$field]['rel_field']))
1761 $rel_field = $this->field_name_map[$field]['rel_field'];
1763 if(!empty($this->$rel_field))
1765 if(empty($disable_date_format)) {
1766 $mergetime = $timedate->merge_date_time($this->$field,$this->$rel_field);
1767 $this->$field = $timedate->to_display_date($mergetime);
1768 $this->$rel_field = $timedate->to_display_time($mergetime);
1774 if(empty($disable_date_format)) {
1775 $this->$field = $timedate->to_display_date($this->$field, false);
1778 } elseif($type == 'datetime' || $type == 'datetimecombo')
1780 if($this->$field == '0000-00-00 00:00:00')
1786 if(empty($disable_date_format)) {
1787 $this->$field = $timedate->to_display_date_time($this->$field, true, true);
1790 } elseif($type == 'time')
1792 if($this->$field == '00:00:00')
1797 //$this->$field = from_db_convert($this->$field, 'time');
1798 if(empty($this->field_name_map[$field]['rel_field']) && empty($disable_date_format))
1800 $this->$field = $timedate->to_display_time($this->$field,true, false);
1803 } elseif($type == 'encrypt' && empty($disable_date_format)){
1804 $this->$field = $this->decrypt_after_retrieve($this->$field);
1812 * This function processes the fields before save.
1813 * Interal function, do not override.
1815 function preprocess_fields_on_save()
1817 $GLOBALS['log']->deprecated('SugarBean.php: preprocess_fields_on_save() is deprecated');
1821 * Removes formatting from values posted from the user interface.
1822 * It only unformats numbers. Function relies on user/system prefernce for format strings.
1824 * Internal Function, do not override.
1826 function unformat_all_fields()
1828 $GLOBALS['log']->deprecated('SugarBean.php: unformat_all_fields() is deprecated');
1832 * This functions adds formatting to all number fields before presenting them to user interface.
1834 * Internal function, do not override.
1836 function format_all_fields()
1838 $GLOBALS['log']->deprecated('SugarBean.php: format_all_fields() is deprecated');
1841 function format_field($fieldDef)
1843 $GLOBALS['log']->deprecated('SugarBean.php: format_field() is deprecated');
1847 * Function corrects any bad formatting done by 3rd party/custom code
1849 * 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
1851 function fixUpFormatting()
1854 static $boolean_false_values = array('off', 'false', '0', 'no');
1857 foreach($this->field_defs as $field=>$def)
1859 if ( !isset($this->$field) ) {
1862 if ( (isset($def['source'])&&$def['source']=='non-db') || $field == 'deleted' ) {
1865 if ( isset($this->fetched_row[$field]) && $this->$field == $this->fetched_row[$field] ) {
1866 // Don't hand out warnings because the field was untouched between retrieval and saving, most database drivers hand pretty much everything back as strings.
1869 $reformatted = false;
1870 switch($def['type']) {
1872 case 'datetimecombo':
1873 if(empty($this->$field)) break;
1874 if ($this->$field == 'NULL') {
1878 if ( ! preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/',$this->$field) ) {
1879 // This appears to be formatted in user date/time
1880 $this->$field = $timedate->to_db($this->$field);
1881 $reformatted = true;
1885 if(empty($this->$field)) break;
1886 if ($this->$field == 'NULL') {
1890 if ( ! preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$this->$field) ) {
1891 // This date appears to be formatted in the user's format
1892 $this->$field = $timedate->to_db_date($this->$field, false);
1893 $reformatted = true;
1897 if(empty($this->$field)) break;
1898 if ($this->$field == 'NULL') {
1902 if ( preg_match('/(am|pm)/i',$this->$field) ) {
1903 // This time appears to be formatted in the user's format
1904 $this->$field = $timedate->fromUserTime($this->$field)->format(TimeDate::DB_TIME_FORMAT);
1905 $reformatted = true;
1912 if ( $this->$field === '' || $this->$field == NULL || $this->$field == 'NULL') {
1915 if ( is_string($this->$field) ) {
1916 $this->$field = (float)unformat_number($this->$field);
1917 $reformatted = true;
1926 if ( $this->$field === '' || $this->$field == NULL || $this->$field == 'NULL') {
1929 if ( is_string($this->$field) ) {
1930 $this->$field = (int)unformat_number($this->$field);
1931 $reformatted = true;
1935 if (empty($this->$field)) {
1936 $this->$field = false;
1937 } else if(true === $this->$field || 1 == $this->$field) {
1938 $this->$field = true;
1939 } else if(in_array(strval($this->$field), $boolean_false_values)) {
1940 $this->$field = false;
1941 $reformatted = true;
1943 $this->$field = true;
1944 $reformatted = true;
1948 $this->$field = $this->encrpyt_before_save($this->$field);
1951 if ( $reformatted ) {
1952 $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');
1959 * Function fetches a single row of data given the primary key value.
1961 * The fetched data is then set into the bean. The function also processes the fetched data by formattig
1962 * date/time and numeric values.
1964 * @param string $id Optional, default -1, is set to -1 id value from the bean is used, else, passed value is used
1965 * @param boolean $encode Optional, default true, encodes the values fetched from the database.
1966 * @param boolean $deleted Optional, default true, if set to false deleted filter will not be added.
1968 * Internal function, do not override.
1970 function retrieve($id = -1, $encode=true,$deleted=true)
1973 $custom_logic_arguments['id'] = $id;
1974 $this->call_custom_logic('before_retrieve', $custom_logic_arguments);
1980 if(isset($this->custom_fields))
1982 $custom_join = $this->custom_fields->getJOIN();
1985 $custom_join = false;
1989 $query = "SELECT $this->table_name.*". $custom_join['select']. " FROM $this->table_name ";
1993 $query = "SELECT $this->table_name.* FROM $this->table_name ";
1998 $query .= ' ' . $custom_join['join'];
2000 $query .= " WHERE $this->table_name.id = '$id' ";
2001 if ($deleted) $query .= " AND $this->table_name.deleted=0";
2002 $GLOBALS['log']->debug("Retrieve $this->object_name : ".$query);
2003 //requireSingleResult has beeen deprecated.
2004 //$result = $this->db->requireSingleResult($query, true, "Retrieving record by id $this->table_name:$id found ");
2005 $result = $this->db->limitQuery($query,0,1,true, "Retrieving record by id $this->table_name:$id found ");
2011 $row = $this->db->fetchByAssoc($result, -1, $encode);
2017 //make copy of the fetched row for construction of audit record and for business logic/workflow
2018 $row = $this->convertRow($row);
2019 $this->fetched_row=$row;
2020 $this->populateFromRow($row);
2022 global $module, $action;
2023 //Just to get optimistic locking working for this release
2024 if($this->optimistic_lock && $module == $this->module_dir && $action =='EditView' )
2026 $_SESSION['o_lock_id']= $id;
2027 $_SESSION['o_lock_dm']= $this->date_modified;
2028 $_SESSION['o_lock_on'] = $this->object_name;
2030 $this->processed_dates_times = array();
2031 $this->check_date_relationships_load();
2035 $this->custom_fields->fill_relationships();
2038 $this->fill_in_additional_detail_fields();
2039 $this->fill_in_relationship_fields();
2040 //make a copy of fields in the relatiosnhip_fields array. these field values will be used to
2041 //clear relatioship.
2042 foreach ( $this->field_defs as $key => $def )
2044 if ($def [ 'type' ] == 'relate' && isset ( $def [ 'id_name'] ) && isset ( $def [ 'link'] ) && isset ( $def[ 'save' ])) {
2045 if (isset($this->$key)) {
2046 $this->rel_fields_before_value[$key]=$this->$key;
2047 if (isset($this->$def [ 'id_name']))
2048 $this->rel_fields_before_value[$def [ 'id_name']]=$this->$def [ 'id_name'];
2051 $this->rel_fields_before_value[$key]=null;
2054 if (isset($this->relationship_fields) && is_array($this->relationship_fields))
2056 foreach ($this->relationship_fields as $rel_id=>$rel_name)
2058 if (isset($this->$rel_id))
2059 $this->rel_fields_before_value[$rel_id]=$this->$rel_id;
2061 $this->rel_fields_before_value[$rel_id]=null;
2065 // call the custom business logic
2066 $custom_logic_arguments['id'] = $id;
2067 $custom_logic_arguments['encode'] = $encode;
2068 $this->call_custom_logic("after_retrieve", $custom_logic_arguments);
2069 unset($custom_logic_arguments);
2074 * Sets value from fetched row into the bean.
2076 * @param array $row Fetched row
2077 * @todo loop through vardefs instead
2078 * @internal runs into an issue when populating from field_defs for users - corrupts user prefs
2080 * Internal function, do not override.
2082 function populateFromRow($row)
2085 foreach($this->field_defs as $field=>$field_value)
2087 if($field == 'user_preferences' && $this->module_dir == 'Users')
2089 if(isset($row[$field]))
2091 $this->$field = $row[$field];
2092 $owner = $field . '_owner';
2093 if(!empty($row[$owner])){
2094 $this->$owner = $row[$owner];
2099 $this->$field = $nullvalue;
2107 * Add any required joins to the list count query. The joins are required if there
2108 * is a field in the $where clause that needs to be joined.
2110 * @param string $query
2111 * @param string $where
2113 * Internal Function, do Not override.
2115 function add_list_count_joins(&$query, $where)
2117 $custom_join = $this->custom_fields->getJOIN();
2120 $query .= $custom_join['join'];
2126 * Changes the select expression of the given query to be 'count(*)' so you
2127 * can get the number of items the query will return. This is used to
2128 * populate the upper limit on ListViews.
2130 * @param string $query Select query string
2131 * @return string count query
2133 * Internal function, do not override.
2135 function create_list_count_query($query)
2137 // remove the 'order by' clause which is expected to be at the end of the query
2138 $pattern = '/\sORDER BY.*/is'; // ignores the case
2140 $query = preg_replace($pattern, $replacement, $query);
2141 //handle distinct clause
2143 if(substr_count(strtolower($query), 'distinct')){
2144 if (!empty($this->seed) && !empty($this->seed->table_name ))
2145 $star = 'DISTINCT ' . $this->seed->table_name . '.id';
2147 $star = 'DISTINCT ' . $this->table_name . '.id';
2151 // change the select expression to 'count(*)'
2152 $pattern = '/SELECT(.*?)(\s){1}FROM(\s){1}/is'; // ignores the case
2153 $replacement = 'SELECT count(' . $star . ') c FROM ';
2155 //if the passed query has union clause then replace all instances of the pattern.
2156 //this is very rare. I have seen this happening only from projects module.
2157 //in addition to this added a condition that has union clause and uses
2159 if (strstr($query," UNION ALL ") !== false) {
2161 //seperate out all the queries.
2162 $union_qs=explode(" UNION ALL ", $query);
2163 foreach ($union_qs as $key=>$union_query) {
2165 preg_match($pattern, $union_query, $matches);
2166 if (!empty($matches)) {
2167 if (stristr($matches[0], "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';
2174 $replacement = 'SELECT count(' . $star . ') c FROM ';
2175 $union_qs[$key] = preg_replace($pattern, $replacement, $union_query,1);
2177 $modified_select_query=implode(" UNION ALL ",$union_qs);
2179 $modified_select_query = preg_replace($pattern, $replacement, $query,1);
2183 return $modified_select_query;
2187 * This function returns a paged list of the current object type. It is intended to allow for
2188 * hopping back and forth through pages of data. It only retrieves what is on the current page.
2190 * @internal This method must be called on a new instance. It trashes the values of all the fields in the current one.
2191 * @param string $order_by
2192 * @param string $where Additional where clause
2193 * @param int $row_offset Optaional,default 0, starting row number
2194 * @param init $limit Optional, default -1
2195 * @param int $max Optional, default -1
2196 * @param boolean $show_deleted Optioanl, default 0, if set to 1 system will show deleted records.
2197 * @return array Fetched data.
2199 * Internal function, do not override.
2202 function get_list($order_by = "", $where = "", $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $singleSelect=false)
2204 $GLOBALS['log']->debug("get_list: order_by = '$order_by' and where = '$where' and limit = '$limit'");
2205 if(isset($_SESSION['show_deleted']))
2209 $order_by=$this->process_order_by($order_by, null);
2211 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2213 global $current_user;
2214 $owner_where = $this->getOwnerWhere($current_user->id);
2216 //rrs - because $this->getOwnerWhere() can return '' we need to be sure to check for it and
2217 //handle it properly else you could get into a situation where you are create a where stmt like
2219 if(!empty($owner_where)){
2221 $where = $owner_where;
2223 $where .= ' AND '. $owner_where;
2227 $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted,'',false,null,$singleSelect);
2228 return $this->process_list_query($query, $row_offset, $limit, $max, $where);
2232 * Prefixes column names with this bean's table name.
2234 * @param string $order_by Order by clause to be processed
2235 * @param string $submodule name of the module this order by clause is for
2236 * @return string Processed order by clause
2238 * Internal function, do not override.
2240 function process_order_by ($order_by, $submodule)
2242 if (empty($order_by))
2245 //submodule is empty,this is for list object in focus
2246 if (empty($submodule))
2248 $bean_queried = &$this;
2252 //submodule is set, so this is for subpanel, use submodule
2253 $bean_queried = $submodule;
2255 $elements = explode(',',$order_by);
2256 foreach ($elements as $key=>$value)
2258 if (strchr($value,'.') === false)
2260 //value might have ascending and descending decorations
2261 $list_column = explode(' ',trim($value));
2262 if (isset($list_column[0]))
2264 $list_column_name=trim($list_column[0]);
2265 if (isset($bean_queried->field_defs[$list_column_name]))
2267 $source=isset($bean_queried->field_defs[$list_column_name]['source']) ? $bean_queried->field_defs[$list_column_name]['source']:'db';
2268 if (empty($bean_queried->field_defs[$list_column_name]['table']) && $source=='db')
2270 $list_column[0] = $bean_queried->table_name .".".$list_column[0] ;
2272 if (empty($bean_queried->field_defs[$list_column_name]['table']) && $source=='custom_fields')
2274 $list_column[0] = $bean_queried->table_name ."_cstm.".$list_column[0] ;
2276 // Bug 38803 - Use CONVERT() function when doing an order by on ntext, text, and image fields
2277 if ($source != 'non-db' && $this->db->isTextType($this->db->getFieldType($bean_queried->field_defs[$list_column_name]))) {
2278 $list_column[0] = $this->db->convert($list_column[0], "text2char");
2280 $value = implode(' ',$list_column);
2282 $GLOBALS['log']->debug("process_order_by: ($list_column[0]) does not have a vardef entry.");
2286 $elements[$key]=$value;
2288 return implode(',', $elements);
2294 * Returns a detail object like retrieving of the current object type.
2296 * It is intended for use in navigation buttons on the DetailView. It will pass an offset and limit argument to the sql query.
2297 * @internal This method must be called on a new instance. It overrides the values of all the fields in the current one.
2299 * @param string $order_by
2300 * @param string $where Additional where clause
2301 * @param int $row_offset Optaional,default 0, starting row number
2302 * @param init $limit Optional, default -1
2303 * @param int $max Optional, default -1
2304 * @param boolean $show_deleted Optioanl, default 0, if set to 1 system will show deleted records.
2305 * @return array Fetched data.
2307 * Internal function, do not override.
2309 function get_detail($order_by = "", $where = "", $offset = 0, $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)
2311 $GLOBALS['log']->debug("get_detail: order_by = '$order_by' and where = '$where' and limit = '$limit' and offset = '$offset'");
2312 if(isset($_SESSION['show_deleted']))
2317 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2319 global $current_user;
2320 $owner_where = $this->getOwnerWhere($current_user->id);
2324 $where = $owner_where;
2328 $where .= ' AND '. $owner_where;
2331 $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted, $offset);
2333 //Add Limit and Offset to query
2334 //$query .= " LIMIT 1 OFFSET $offset";
2336 return $this->process_detail_query($query, $row_offset, $limit, $max, $where, $offset);
2340 * Fetches data from all related tables.
2342 * @param object $child_seed
2343 * @param string $related_field_name relation to fetch data for
2344 * @param string $order_by Optional, default empty
2345 * @param string $where Optional, additional where clause
2346 * @return array Fetched data.
2348 * Internal function, do not override.
2350 function get_related_list($child_seed,$related_field_name, $order_by = "", $where = "",
2351 $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)
2353 global $layout_edit_mode;
2354 if(isset($layout_edit_mode) && $layout_edit_mode)
2356 $response = array();
2357 $child_seed->assign_display_fields($child_seed->module_dir);
2358 $response['list'] = array($child_seed);
2359 $response['row_count'] = 1;
2360 $response['next_offset'] = 0;
2361 $response['previous_offset'] = 0;
2365 $GLOBALS['log']->debug("get_related_list: order_by = '$order_by' and where = '$where' and limit = '$limit'");
2366 if(isset($_SESSION['show_deleted']))
2371 $this->load_relationship($related_field_name);
2372 $query_array = $this->$related_field_name->getQuery(true);
2373 $entire_where = $query_array['where'];
2376 if(empty($entire_where))
2378 $entire_where = ' WHERE ' . $where;
2382 $entire_where .= ' AND ' . $where;
2386 $query = 'SELECT '.$child_seed->table_name.'.* ' . $query_array['from'] . ' ' . $entire_where;
2387 if(!empty($order_by))
2389 $query .= " ORDER BY " . $order_by;
2392 return $child_seed->process_list_query($query, $row_offset, $limit, $max, $where);
2396 protected static function build_sub_queries_for_union($subpanel_list, $subpanel_def, $parentbean, $order_by)
2398 global $layout_edit_mode, $beanFiles, $beanList;
2399 $subqueries = array();
2400 foreach($subpanel_list as $this_subpanel)
2402 if(!$this_subpanel->isDatasourceFunction() || ($this_subpanel->isDatasourceFunction()
2403 && isset($this_subpanel->_instance_properties['generate_select'])
2404 && $this_subpanel->_instance_properties['generate_select']==true))
2406 //the custom query function must return an array with
2407 if ($this_subpanel->isDatasourceFunction()) {
2408 $shortcut_function_name = $this_subpanel->get_data_source_name();
2409 $parameters=$this_subpanel->get_function_parameters();
2410 if (!empty($parameters))
2412 //if the import file function is set, then import the file to call the custom function from
2413 if (is_array($parameters) && isset($parameters['import_function_file'])){
2414 //this call may happen multiple times, so only require if function does not exist
2415 if(!function_exists($shortcut_function_name)){
2416 require_once($parameters['import_function_file']);
2418 //call function from required file
2419 $query_array = $shortcut_function_name($parameters);
2421 //call function from parent bean
2422 $query_array = $parentbean->$shortcut_function_name($parameters);
2427 $query_array = $parentbean->$shortcut_function_name();
2430 $related_field_name = $this_subpanel->get_data_source_name();
2431 if (!$parentbean->load_relationship($related_field_name)){
2432 unset ($parentbean->$related_field_name);
2435 $query_array = $parentbean->$related_field_name->getSubpanelQuery(array(), true);
2437 $table_where = $this_subpanel->get_where();
2438 $where_definition = $query_array['where'];
2440 if(!empty($table_where))
2442 if(empty($where_definition))
2444 $where_definition = $table_where;
2448 $where_definition .= ' AND ' . $table_where;
2452 $submodulename = $this_subpanel->_instance_properties['module'];
2453 $submoduleclass = $beanList[$submodulename];
2454 //require_once($beanFiles[$submoduleclass]);
2455 $submodule = new $submoduleclass();
2456 $subwhere = $where_definition;
2460 $subwhere = str_replace('WHERE', '', $subwhere);
2461 $list_fields = $this_subpanel->get_list_fields();
2462 foreach($list_fields as $list_key=>$list_field)
2464 if(isset($list_field['usage']) && $list_field['usage'] == 'display_only')
2466 unset($list_fields[$list_key]);
2471 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'))
2473 $order_by = $submodule->table_name .'.'. $order_by;
2475 $table_name = $this_subpanel->table_name;
2476 $panel_name=$this_subpanel->name;
2478 $params['distinct'] = $this_subpanel->distinct_query();
2480 $params['joined_tables'] = $query_array['join_tables'];
2481 $params['include_custom_fields'] = !$subpanel_def->isCollection();
2482 $params['collection_list'] = $subpanel_def->get_inst_prop_value('collection_list');
2484 $subquery = $submodule->create_new_list_query('',$subwhere ,$list_fields,$params, 0,'', true,$parentbean);
2486 $subquery['select'] = $subquery['select']." , '$panel_name' panel_name ";
2487 $subquery['from'] = $subquery['from'].$query_array['join'];
2488 $subquery['query_array'] = $query_array;
2489 $subquery['params'] = $params;
2491 $subqueries[] = $subquery;
2498 * Constructs a query to fetch data for supanels and list views
2500 * It constructs union queries for activities subpanel.
2502 * @param SugarBean $parentbean constructing queries for link attributes in this bean
2503 * @param string $order_by Optional, order by clause
2504 * @param string $sort_order Optional, sort order
2505 * @param string $where Optional, additional where clause
2507 * Internal Function, do not overide.
2509 function get_union_related_list($parentbean, $order_by = "", $sort_order='', $where = "",
2510 $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $subpanel_def)
2512 $secondary_queries = array();
2513 global $layout_edit_mode, $beanFiles, $beanList;
2515 if(isset($_SESSION['show_deleted']))
2520 $final_query_rows = '';
2521 $subpanel_list=array();
2522 if ($subpanel_def->isCollection())
2524 $subpanel_def->load_sub_subpanels();
2525 $subpanel_list=$subpanel_def->sub_subpanels;
2529 $subpanel_list[]=$subpanel_def;
2534 //Breaking the building process into two loops. The first loop gets a list of all the sub-queries.
2535 //The second loop merges the queries and forces them to select the same number of columns
2536 //All columns in a sub-subpanel group must have the same aliases
2537 //If the subpanel is a datasource function, it can't be a collection so we just poll that function for the and return that
2538 foreach($subpanel_list as $this_subpanel)
2540 if($this_subpanel->isDatasourceFunction() && empty($this_subpanel->_instance_properties['generate_select']))
2542 $shortcut_function_name = $this_subpanel->get_data_source_name();
2543 $parameters=$this_subpanel->get_function_parameters();
2544 if (!empty($parameters))
2546 //if the import file function is set, then import the file to call the custom function from
2547 if (is_array($parameters) && isset($parameters['import_function_file'])){
2548 //this call may happen multiple times, so only require if function does not exist
2549 if(!function_exists($shortcut_function_name)){
2550 require_once($parameters['import_function_file']);
2552 //call function from required file
2553 $tmp_final_query = $shortcut_function_name($parameters);
2555 //call function from parent bean
2556 $tmp_final_query = $parentbean->$shortcut_function_name($parameters);
2559 $tmp_final_query = $parentbean->$shortcut_function_name();
2563 $final_query_rows .= ' UNION ALL ( '.$parentbean->create_list_count_query($tmp_final_query, $parameters) . ' )';
2564 $final_query .= ' UNION ALL ( '.$tmp_final_query . ' )';
2566 $final_query_rows = '(' . $parentbean->create_list_count_query($tmp_final_query, $parameters) . ')';
2567 $final_query = '(' . $tmp_final_query . ')';
2572 //If final_query is still empty, its time to build the sub-queries
2573 if (empty($final_query))
2575 $subqueries = SugarBean::build_sub_queries_for_union($subpanel_list, $subpanel_def, $parentbean, $order_by);
2576 $all_fields = array();
2577 foreach($subqueries as $i => $subquery)
2579 $query_fields = $GLOBALS['db']->getSelectFieldsFromQuery($subquery['select']);
2580 foreach($query_fields as $field => $select)
2582 if (!in_array($field, $all_fields))
2583 $all_fields[] = $field;
2585 $subqueries[$i]['query_fields'] = $query_fields;
2588 //Now ensure the queries have the same set of fields in the same order.
2589 foreach($subqueries as $subquery)
2591 $subquery['select'] = "SELECT";
2592 foreach($all_fields as $field)
2594 if (!isset($subquery['query_fields'][$field]))
2596 $subquery['select'] .= " ' ' $field,";
2600 $subquery['select'] .= " {$subquery['query_fields'][$field]},";
2603 $subquery['select'] = substr($subquery['select'], 0 , strlen($subquery['select']) - 1);
2604 //Put the query into the final_query
2605 $query = $subquery['select'] . " " . $subquery['from'] . " " . $subquery['where'];
2608 $query = ' UNION ALL ( '.$query . ' )';
2609 $final_query_rows .= " UNION ALL ";
2611 $query = '(' . $query . ')';
2614 $query_array = $subquery['query_array'];
2615 $select_position=strpos($query_array['select'],"SELECT");
2616 $distinct_position=strpos($query_array['select'],"DISTINCT");
2617 if ($select_position !== false && $distinct_position!= false)
2619 $query_rows = "( ".substr_replace($query_array['select'],"SELECT count(",$select_position,6). ")" . $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2623 //resort to default behavior.
2624 $query_rows = "( SELECT count(*)". $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2626 if(!empty($subquery['secondary_select']))
2629 $subquerystring= $subquery['secondary_select'] . $subquery['secondary_from'].$query_array['join']. $subquery['where'];
2630 if (!empty($subquery['secondary_where']))
2632 if (empty($subquery['where']))
2634 $subquerystring.=" WHERE " .$subquery['secondary_where'];
2638 $subquerystring.=" AND " .$subquery['secondary_where'];
2641 $secondary_queries[]=$subquerystring;
2643 $final_query .= $query;
2644 $final_query_rows .= $query_rows;
2648 if(!empty($order_by))
2651 if(!$subpanel_def->isCollection())
2653 $submodulename = $subpanel_def->_instance_properties['module'];
2654 $submoduleclass = $beanList[$submodulename];
2655 $submodule = new $submoduleclass();
2657 if(!empty($submodule) && !empty($submodule->table_name))
2659 $final_query .= " ORDER BY " .$parentbean->process_order_by($order_by, $submodule);
2664 $final_query .= " ORDER BY ". $order_by . ' ';
2666 if(!empty($sort_order))
2668 $final_query .= ' ' .$sort_order;
2673 if(isset($layout_edit_mode) && $layout_edit_mode)
2675 $response = array();
2676 if(!empty($submodule))
2678 $submodule->assign_display_fields($submodule->module_dir);
2679 $response['list'] = array($submodule);
2683 $response['list'] = array();
2685 $response['parent_data'] = array();
2686 $response['row_count'] = 1;
2687 $response['next_offset'] = 0;
2688 $response['previous_offset'] = 0;
2693 return $parentbean->process_union_list_query($parentbean, $final_query, $row_offset, $limit, $max, '',$subpanel_def, $final_query_rows, $secondary_queries);
2698 * Returns a full (ie non-paged) list of the current object type.
2700 * @param string $order_by the order by SQL parameter. defaults to ""
2701 * @param string $where where clause. defaults to ""
2702 * @param boolean $check_dates. defaults to false
2703 * @param int $show_deleted show deleted records. defaults to 0
2705 function get_full_list($order_by = "", $where = "", $check_dates=false, $show_deleted = 0)
2707 $GLOBALS['log']->debug("get_full_list: order_by = '$order_by' and where = '$where'");
2708 if(isset($_SESSION['show_deleted']))
2712 $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted);
2713 return $this->process_full_list_query($query, $check_dates);
2717 * Return the list query used by the list views and export button. Next generation of create_new_list_query function.
2719 * Override this function to return a custom query.
2721 * @param string $order_by custom order by clause
2722 * @param string $where custom where clause
2723 * @param array $filter Optioanal
2724 * @param array $params Optional *
2725 * @param int $show_deleted Optional, default 0, show deleted records is set to 1.
2726 * @param string $join_type
2727 * @param boolean $return_array Optional, default false, response as array
2728 * @param object $parentbean creating a subquery for this bean.
2729 * @param boolean $singleSelect Optional, default false.
2730 * @return String select query string, optionally an array value will be returned if $return_array= true.
2732 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)
2734 global $beanFiles, $beanList;
2735 $selectedFields = array();
2736 $secondarySelectedFields = array();
2737 $ret_array = array();
2739 if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2741 global $current_user;
2742 $owner_where = $this->getOwnerWhere($current_user->id);
2745 $where = $owner_where;
2749 $where .= ' AND '. $owner_where;
2752 if(!empty($params['distinct']))
2754 $distinct = ' DISTINCT ';
2758 $ret_array['select'] = " SELECT $distinct $this->table_name.* ";
2762 $ret_array['select'] = " SELECT $distinct $this->table_name.id ";
2764 $ret_array['from'] = " FROM $this->table_name ";
2765 $ret_array['from_min'] = $ret_array['from'];
2766 $ret_array['secondary_from'] = $ret_array['from'] ;
2767 $ret_array['where'] = '';
2768 $ret_array['order_by'] = '';
2769 //secondary selects are selects that need to be run after the primarty query to retrieve additional info on main
2772 $ret_array['secondary_select']=& $ret_array['select'];
2773 $ret_array['secondary_from'] = & $ret_array['from'];
2777 $ret_array['secondary_select'] = '';
2779 $custom_join = false;
2780 if((!isset($params['include_custom_fields']) || $params['include_custom_fields']) && isset($this->custom_fields))
2783 $custom_join = $this->custom_fields->getJOIN( empty($filter)? true: $filter );
2786 $ret_array['select'] .= ' ' .$custom_join['select'];
2791 $ret_array['from'] .= ' ' . $custom_join['join'];
2794 //LOOP AROUND FOR FIXIN VARDEF ISSUES
2795 require('include/VarDefHandler/listvardefoverride.php');
2796 $joined_tables = array();
2797 if(!empty($params['joined_tables']))
2799 foreach($params['joined_tables'] as $table)
2801 $joined_tables[$table] = 1;
2807 $filterKeys = array_keys($filter);
2808 if(is_numeric($filterKeys[0]))
2811 foreach($filter as $field)
2813 $field = strtolower($field);
2814 //remove out id field so we don't duplicate it
2815 if ( $field == 'id' && !empty($filter) ) {
2818 if(isset($this->field_defs[$field]))
2820 $fields[$field]= $this->field_defs[$field];
2824 $fields[$field] = array('force_exists'=>true);
2833 $fields = $this->field_defs;
2836 $used_join_key = array();
2838 foreach($fields as $field=>$value)
2840 //alias is used to alias field names
2842 if (isset($value['alias']))
2844 $alias =' as ' . $value['alias'] . ' ';
2847 if(empty($this->field_defs[$field]) || !empty($value['force_blank']) )
2849 if(!empty($filter) && isset($filter[$field]['force_exists']) && $filter[$field]['force_exists'])
2851 if ( isset($filter[$field]['force_default']) )
2852 $ret_array['select'] .= ", {$filter[$field]['force_default']} $field ";
2854 //spaces are a fix for length issue problem with unions. The union only returns the maximum number of characters from the first select statemtn.
2855 $ret_array['select'] .= ", ' ' $field ";
2861 $data = $this->field_defs[$field];
2864 //ignore fields that are a part of the collection and a field has been removed as a result of
2865 //layout customization.. this happens in subpanel customizations, use case, from the contacts subpanel
2866 //in opportunities module remove the contact_role/opportunity_role field.
2867 $process_field=true;
2868 if (isset($data['relationship_fields']) and !empty($data['relationship_fields']))
2870 foreach ($data['relationship_fields'] as $field_name)
2872 if (!isset($fields[$field_name]))
2874 $process_field=false;
2878 if (!$process_field)
2883 if( (!isset($data['source']) || $data['source'] == 'db') && (!empty($alias) || !empty($filter) ))
2885 $ret_array['select'] .= ", $this->table_name.$field $alias";
2886 $selectedFields["$this->table_name.$field"] = true;
2891 if($data['type'] != 'relate' && isset($data['db_concat_fields']))
2893 $ret_array['select'] .= ", " . db_concat($this->table_name, $data['db_concat_fields']) . " as $field";
2894 $selectedFields[db_concat($this->table_name, $data['db_concat_fields'])] = true;
2896 //Custom relate field or relate fields built in module builder which have no link field associated.
2897 if ($data['type'] == 'relate' && (isset($data['custom_module']) || isset($data['ext2']))) {
2898 $joinTableAlias = 'jt' . $jtcount;
2899 $relateJoinInfo = $this->custom_fields->getRelateJoin($data, $joinTableAlias);
2900 $ret_array['select'] .= $relateJoinInfo['select'];
2901 $ret_array['from'] .= $relateJoinInfo['from'];
2902 //Replace any references to the relationship in the where clause with the new alias
2903 //If the link isn't set, assume that search used the local table for the field
2904 $searchTable = isset($data['link']) ? $relateJoinInfo['rel_table'] : $this->table_name;
2905 $field_name = $relateJoinInfo['rel_table'] . '.' . !empty($data['name'])?$data['name']:'name';
2906 $where = preg_replace('/(^|[\s(])' . $field_name . '/' , '${1}' . $relateJoinInfo['name_field'], $where);
2910 if ($data['type'] == 'parent') {
2911 //See if we need to join anything by inspecting the where clause
2912 $match = preg_match('/(^|[\s(])parent_(\w+)_(\w+)\.name/', $where, $matches);
2914 $joinTableAlias = 'jt' . $jtcount;
2915 $joinModule = $matches[2];
2916 $joinTable = $matches[3];
2917 $localTable = $this->table_name;
2918 if (!empty($data['custom_module'])) {
2919 $localTable .= '_cstm';
2921 global $beanFiles, $beanList, $module;
2922 require_once($beanFiles[$beanList[$joinModule]]);
2923 $rel_mod = new $beanList[$joinModule]();
2924 $nameField = "$joinTableAlias.name";
2925 if (isset($rel_mod->field_defs['name']))
2927 $name_field_def = $rel_mod->field_defs['name'];
2928 if(isset($name_field_def['db_concat_fields']))
2930 $nameField = db_concat($joinTableAlias, $name_field_def['db_concat_fields']);
2933 $ret_array['select'] .= ", $nameField {$data['name']} ";
2934 $ret_array['from'] .= " LEFT JOIN $joinTable $joinTableAlias
2935 ON $localTable.{$data['id_name']} = $joinTableAlias.id";
2936 //Replace any references to the relationship in the where clause with the new alias
2937 $where = preg_replace('/(^|[\s(])parent_' . $joinModule . '_' . $joinTable . '\.name/', '${1}' . $nameField, $where);
2941 if($data['type'] == 'relate' && isset($data['link']))
2943 $this->load_relationship($data['link']);
2944 if(!empty($this->$data['link']))
2947 if(empty($join_type))
2949 $params['join_type'] = ' LEFT JOIN ';
2953 $params['join_type'] = $join_type;
2955 if(isset($data['join_name']))
2957 $params['join_table_alias'] = $data['join_name'];
2961 $params['join_table_alias'] = 'jt' . $jtcount;
2964 if(isset($data['join_link_name']))
2966 $params['join_table_link_alias'] = $data['join_link_name'];
2970 $params['join_table_link_alias'] = 'jtl' . $jtcount;
2972 $join_primary = !isset($data['join_primary']) || $data['join_primary'];
2974 $join = $this->$data['link']->getJoin($params, true);
2975 $used_join_key[] = $join['rel_key'];
2976 $rel_module = $this->$data['link']->getRelatedModuleName();
2977 $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');
2979 //if rnanme is set to 'name', and bean files exist, then check if field should be a concatenated name
2980 global $beanFiles, $beanList;
2981 if($data['rname'] && !empty($beanFiles[$beanList[$rel_module]])) {
2983 //create an instance of the related bean
2984 require_once($beanFiles[$beanList[$rel_module]]);
2985 $rel_mod = new $beanList[$rel_module]();
2986 //if bean has first and last name fields, then name should be concatenated
2987 if(isset($rel_mod->field_name_map['first_name']) && isset($rel_mod->field_name_map['last_name'])){
2988 $data['db_concat_fields'] = array(0=>'first_name', 1=>'last_name');
2993 if($join['type'] == 'many-to-many')
2995 if(empty($ret_array['secondary_select']))
2997 $ret_array['secondary_select'] = " SELECT $this->table_name.id ref_id ";
2999 if(!empty($beanFiles[$beanList[$rel_module]]) && $join_primary)
3001 require_once($beanFiles[$beanList[$rel_module]]);
3002 $rel_mod = new $beanList[$rel_module]();
3003 if(isset($rel_mod->field_defs['assigned_user_id']))
3005 $ret_array['secondary_select'].= " , ". $params['join_table_alias'] . ".assigned_user_id {$field}_owner, '$rel_module' {$field}_mod";
3010 if(isset($rel_mod->field_defs['created_by']))
3012 $ret_array['secondary_select'].= " , ". $params['join_table_alias'] . ".created_by {$field}_owner , '$rel_module' {$field}_mod";
3023 if(isset($data['db_concat_fields']))
3025 $ret_array['secondary_select'] .= ' , ' . db_concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
3029 if(!isset($data['relationship_fields']))
3031 $ret_array['secondary_select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
3036 $ret_array['select'] .= ", ' ' $field ";
3037 $ret_array['select'] .= ", ' ' " . $join['rel_key'] . ' ';
3040 foreach($used_join_key as $used_key) {
3041 if($used_key == $join['rel_key']) $count_used++;
3043 if($count_used <= 1) {//27416, the $ret_array['secondary_select'] should always generate, regardless the dbtype
3044 $ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'].'.'. $join['rel_key'] .' ' . $join['rel_key'];
3046 if(isset($data['relationship_fields']))
3048 foreach($data['relationship_fields'] as $r_name=>$alias_name)
3050 if(!empty( $secondarySelectedFields[$alias_name]))continue;
3051 $ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'].'.'. $r_name .' ' . $alias_name;
3052 $secondarySelectedFields[$alias_name] = true;
3057 $ret_array['secondary_from'] .= ' ' . $join['join']. ' AND ' . $params['join_table_alias'].'.deleted=0';
3058 if (isset($data['link_type']) && $data['link_type'] == 'relationship_info' && ($parentbean instanceOf SugarBean))
3060 $ret_array['secondary_where'] = $params['join_table_link_alias'] . '.' . $join['rel_key']. "='" .$parentbean->id . "'";
3066 if(isset($data['db_concat_fields']))
3068 $ret_array['select'] .= ' , ' . db_concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
3072 $ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
3074 if(isset($data['additionalFields'])){
3075 foreach($data['additionalFields'] as $k=>$v){
3076 $ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $k . ' ' . $v;
3081 $ret_array['from'] .= ' ' . $join['join']. ' AND ' . $params['join_table_alias'].'.deleted=0';
3082 if(!empty($beanList[$rel_module]) && !empty($beanFiles[$beanList[$rel_module]]))
3084 require_once($beanFiles[$beanList[$rel_module]]);
3085 $rel_mod = new $beanList[$rel_module]();
3086 if(isset($value['target_record_key']) && !empty($filter))
3088 $selectedFields[$this->table_name.'.'.$value['target_record_key']] = true;
3089 $ret_array['select'] .= " , $this->table_name.{$value['target_record_key']} ";
3091 if(isset($rel_mod->field_defs['assigned_user_id']))
3093 $ret_array['select'] .= ' , ' .$params['join_table_alias'] . '.assigned_user_id ' . $field . '_owner';
3097 $ret_array['select'] .= ' , ' .$params['join_table_alias'] . '.created_by ' . $field . '_owner';
3099 $ret_array['select'] .= " , '".$rel_module ."' " . $field . '_mod';
3104 // To fix SOAP stuff where we are trying to retrieve all the accounts data where accounts.id = ..
3105 // and this code changes accounts to jt4 as there is a self join with the accounts table.
3107 if(isset($data['db_concat_fields'])){
3108 $buildWhere = false;
3109 if(in_array('first_name', $data['db_concat_fields']) && in_array('last_name', $data['db_concat_fields']))
3111 $exp = '/\(\s*?'.$data['name'].'.*?\%\'\s*?\)/';
3112 if(preg_match($exp, $where, $matches))
3114 $search_expression = $matches[0];
3115 //Create three search conditions - first + last, first, last
3116 $first_name_search = str_replace($data['name'], $params['join_table_alias'] . '.first_name', $search_expression);
3117 $last_name_search = str_replace($data['name'], $params['join_table_alias'] . '.last_name', $search_expression);
3118 $full_name_search = str_replace($data['name'], db_concat($params['join_table_alias'], $data['db_concat_fields']), $search_expression);
3120 $where = str_replace($search_expression, '(' . $full_name_search . ' OR ' . $first_name_search . ' OR ' . $last_name_search . ')', $where);
3126 $db_field = db_concat($params['join_table_alias'], $data['db_concat_fields']);
3127 $where = preg_replace('/'.$data['name'].'/', $db_field, $where);
3130 $where = preg_replace('/(^|[\s(])' . $data['name'] . '/', '${1}' . $params['join_table_alias'] . '.'.$data['rname'], $where);
3134 $joined_tables[$params['join_table_alias']]=1;
3135 $joined_tables[$params['join_table_link_alias']]=1;
3144 if(isset($this->field_defs['assigned_user_id']) && empty($selectedFields[$this->table_name.'.assigned_user_id']))
3146 $ret_array['select'] .= ", $this->table_name.assigned_user_id ";
3148 else if(isset($this->field_defs['created_by']) && empty($selectedFields[$this->table_name.'.created_by']))
3150 $ret_array['select'] .= ", $this->table_name.created_by ";
3152 if(isset($this->field_defs['system_id']) && empty($selectedFields[$this->table_name.'.system_id']))
3154 $ret_array['select'] .= ", $this->table_name.system_id ";
3159 if ($ifListForExport) {
3160 if(isset($this->field_defs['email1'])) {
3161 $ret_array['select'].= " ,email_addresses.email_address email1";
3162 $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 ";
3166 $where_auto = '1=1';
3167 if($show_deleted == 0)
3169 $where_auto = "$this->table_name.deleted=0";
3170 }else if($show_deleted == 1)
3172 $where_auto = "$this->table_name.deleted=1";
3175 $ret_array['where'] = " where ($where) AND $where_auto";
3177 $ret_array['where'] = " where $where_auto";
3178 if(!empty($order_by))
3180 //make call to process the order by clause
3181 $ret_array['order_by'] = " ORDER BY ". $this->process_order_by($order_by, null);
3185 unset($ret_array['secondary_where']);
3186 unset($ret_array['secondary_from']);
3187 unset($ret_array['secondary_select']);
3195 return $ret_array['select'] . $ret_array['from'] . $ret_array['where']. $ret_array['order_by'];
3198 * Returns parent record data for objects that store relationship information
3200 * @param array $type_info
3202 * Interal function, do not override.
3204 function retrieve_parent_fields($type_info)
3207 global $beanList, $beanFiles;
3208 $templates = array();
3209 $parent_child_map = array();
3210 foreach($type_info as $children_info)
3212 foreach($children_info as $child_info)
3214 if($child_info['type'] == 'parent')
3216 if(empty($templates[$child_info['parent_type']]))
3218 //Test emails will have an invalid parent_type, don't try to load the non-existant parent bean
3219 if ($child_info['parent_type'] == 'test') {
3222 $class = $beanList[$child_info['parent_type']];
3223 // Added to avoid error below; just silently fail and write message to log
3224 if ( empty($beanFiles[$class]) ) {
3225 $GLOBALS['log']->error($this->object_name.'::retrieve_parent_fields() - cannot load class "'.$class.'", skip loading.');
3228 require_once($beanFiles[$class]);
3229 $templates[$child_info['parent_type']] = new $class();
3232 if(empty($queries[$child_info['parent_type']]))
3234 $queries[$child_info['parent_type']] = "SELECT id ";
3235 $field_def = $templates[$child_info['parent_type']]->field_defs['name'];
3236 if(isset($field_def['db_concat_fields']))
3238 $queries[$child_info['parent_type']] .= ' , ' . db_concat($templates[$child_info['parent_type']]->table_name, $field_def['db_concat_fields']) . ' parent_name';
3242 $queries[$child_info['parent_type']] .= ' , name parent_name';
3244 if(isset($templates[$child_info['parent_type']]->field_defs['assigned_user_id']))
3246 $queries[$child_info['parent_type']] .= ", assigned_user_id parent_name_owner , '{$child_info['parent_type']}' parent_name_mod";;
3247 }else if(isset($templates[$child_info['parent_type']]->field_defs['created_by']))
3249 $queries[$child_info['parent_type']] .= ", created_by parent_name_owner, '{$child_info['parent_type']}' parent_name_mod";
3251 $queries[$child_info['parent_type']] .= " FROM " . $templates[$child_info['parent_type']]->table_name ." WHERE id IN ('{$child_info['parent_id']}'";
3255 if(empty($parent_child_map[$child_info['parent_id']]))
3256 $queries[$child_info['parent_type']] .= " ,'{$child_info['parent_id']}'";
3258 $parent_child_map[$child_info['parent_id']][] = $child_info['child_id'];
3263 foreach($queries as $query)
3265 $result = $this->db->query($query . ')');
3266 while($row = $this->db->fetchByAssoc($result))
3268 $results[$row['id']] = $row;
3272 $child_results = array();
3273 foreach($parent_child_map as $parent_key=>$parent_child)
3275 foreach($parent_child as $child)
3277 if(isset( $results[$parent_key]))
3279 $child_results[$child] = $results[$parent_key];
3283 return $child_results;
3287 * Processes the list query and return fetched row.
3289 * Internal function, do not override.
3290 * @param string $query select query to be processed.
3291 * @param int $row_offset starting position
3292 * @param int $limit Optioanl, default -1
3293 * @param int $max_per_page Optional, default -1
3294 * @param string $where Optional, additional filter criteria.
3295 * @return array Fetched data
3297 function process_list_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '')
3299 global $sugar_config;
3300 $db = DBManagerFactory::getInstance('listviews');
3302 * if the row_offset is set to 'end' go to the end of the list
3304 $toEnd = strval($row_offset) == 'end';
3305 $GLOBALS['log']->debug("process_list_query: ".$query);
3306 if($max_per_page == -1)
3308 $max_per_page = $sugar_config['list_max_entries_per_page'];
3310 // Check to see if we have a count query available.
3311 if(empty($sugar_config['disable_count_query']) || $toEnd)
3313 $count_query = $this->create_list_count_query($query);
3314 if(!empty($count_query) && (empty($limit) || $limit == -1))
3316 // We have a count query. Run it and get the results.
3317 $result = $db->query($count_query, true, "Error running count query for $this->object_name List: ");
3318 $assoc = $db->fetchByAssoc($result);
3319 if(!empty($assoc['c']))
3321 $rows_found = $assoc['c'];
3322 $limit = $sugar_config['list_max_entries_per_page'];
3326 $row_offset = (floor(($rows_found -1) / $limit)) * $limit;
3332 if((empty($limit) || $limit == -1))
3334 $limit = $max_per_page + 1;
3335 $max_per_page = $limit;
3340 if(empty($row_offset))
3344 if(!empty($limit) && $limit != -1 && $limit != -99)
3346 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $this->object_name list: ");
3350 $result = $db->query($query,true,"Error retrieving $this->object_name list: ");
3355 if(empty($rows_found))
3357 $rows_found = $db->getRowCount($result);
3360 $GLOBALS['log']->debug("Found $rows_found ".$this->object_name."s");
3362 $previous_offset = $row_offset - $max_per_page;
3363 $next_offset = $row_offset + $max_per_page;
3365 $class = get_class($this);
3366 if($rows_found != 0 || !$db->supports('select_rows'))
3368 //FIXME: Bug? we should remove the magic number -99
3369 //use -99 to return all
3370 $index = $row_offset;
3371 while ($max_per_page == -99 || ($index < $row_offset + $max_per_page))
3374 if(!empty($sugar_config['disable_count_query']))
3376 $row = $db->fetchByAssoc($result);
3380 $row = $db->fetchByAssoc($result, $index);
3387 //instantiate a new class each time. This is because php5 passes
3388 //by reference by default so if we continually update $this, we will
3389 //at the end have a list of all the same objects
3390 $temp = new $class();
3392 foreach($this->field_defs as $field=>$value)
3394 if (isset($row[$field]))
3396 $temp->$field = $row[$field];
3397 $owner_field = $field . '_owner';
3398 if(isset($row[$owner_field]))
3400 $temp->$owner_field = $row[$owner_field];
3403 $GLOBALS['log']->debug("$temp->object_name({$row['id']}): ".$field." = ".$temp->$field);
3404 }else if (isset($row[$this->table_name .'.'.$field]))
3406 $temp->$field = $row[$this->table_name .'.'.$field];
3414 $temp->check_date_relationships_load();
3415 $temp->fill_in_additional_list_fields();
3416 if($temp->hasCustomFields()) $temp->custom_fields->fill_relationships();
3417 $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]);
3436 $response = Array();
3437 $response['list'] = $list;
3438 $response['row_count'] = $rows_found;
3439 $response['next_offset'] = $next_offset;
3440 $response['previous_offset'] = $previous_offset;
3441 $response['current_offset'] = $row_offset ;
3446 * Returns the number of rows that the given SQL query should produce
3448 * Internal function, do not override.
3449 * @param string $query valid select query
3450 * @param boolean $is_count_query Optional, Default false, set to true if passed query is a count query.
3451 * @return int count of rows found
3453 function _get_num_rows_in_query($query, $is_count_query=false)
3455 $num_rows_in_query = 0;
3456 if (!$is_count_query)
3458 $count_query = SugarBean::create_list_count_query($query);
3460 $count_query=$query;
3462 $result = $this->db->query($count_query, true, "Error running count query for $this->object_name List: ");
3464 $row = $this->db->fetchByAssoc($result, $row_num);
3467 $num_rows_in_query += current($row);
3469 $row = $this->db->fetchByAssoc($result, $row_num);
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 if(empty($rows_found))
3566 $rows_found = $db->getRowCount($result);
3569 $GLOBALS['log']->debug("Found $rows_found ".$parent_bean->object_name."s");
3570 if($rows_found != 0 || !$db->supports('select_rows'))
3572 //use -99 to return all
3574 // get the current row
3575 $index = $row_offset;
3576 if(!empty($sugar_config['disable_count_query']))
3578 $row = $db->fetchByAssoc($result);
3582 $row = $db->fetchByAssoc($result, $index);
3585 $post_retrieve = array();
3586 $isFirstTime = true;
3589 $function_fields = array();
3590 if(($index < $row_offset + $max_per_page || $max_per_page == -99))
3592 if ($processing_collection)
3594 $current_bean =$subpanel_def->sub_subpanels[$row['panel_name']]->template_instance;
3597 $class = get_class($subpanel_def->sub_subpanels[$row['panel_name']]->template_instance);
3598 $current_bean = new $class();
3601 $current_bean=$subpanel_def->template_instance;
3604 $class = get_class($subpanel_def->template_instance);
3605 $current_bean = new $class();
3608 $isFirstTime = false;
3609 //set the panel name in the bean instance.
3610 if (isset($row['panel_name']))
3612 $current_bean->panel_name=$row['panel_name'];
3614 foreach($current_bean->field_defs as $field=>$value)
3617 if (isset($row[$field]))
3619 $current_bean->$field = $row[$field];
3620 unset($row[$field]);
3622 else if (isset($row[$this->table_name .'.'.$field]))
3624 $current_bean->$field = $row[$current_bean->table_name .'.'.$field];
3625 unset($row[$current_bean->table_name .'.'.$field]);
3629 $current_bean->$field = "";
3630 unset($row[$field]);
3632 if(isset($value['source']) && $value['source'] == 'function')
3634 $function_fields[]=$field;
3637 foreach($row as $key=>$value)
3639 $current_bean->$key = $value;
3641 foreach($function_fields as $function_field)
3643 $value = $current_bean->field_defs[$function_field];
3644 $can_execute = true;
3645 $execute_params = array();
3646 $execute_function = array();
3647 if(!empty($value['function_class']))
3649 $execute_function[] = $value['function_class'];
3650 $execute_function[] = $value['function_name'];
3654 $execute_function = $value['function_name'];
3656 foreach($value['function_params'] as $param )
3658 if (empty($value['function_params_source']) or $value['function_params_source']=='parent')
3660 if(empty($this->$param))
3662 $can_execute = false;
3663 } else if($param == '$this') {
3664 $execute_params[] = $this;
3668 $execute_params[] = $this->$param;
3670 } else if ($value['function_params_source']=='this')
3672 if(empty($current_bean->$param))
3674 $can_execute = false;
3675 } else if($param == '$this') {
3676 $execute_params[] = $current_bean;
3680 $execute_params[] = $current_bean->$param;
3685 $can_execute = false;
3691 if(!empty($value['function_require']))
3693 require_once($value['function_require']);
3695 $current_bean->$function_field = call_user_func_array($execute_function, $execute_params);
3698 if(!empty($current_bean->parent_type) && !empty($current_bean->parent_id))
3700 if(!isset($post_retrieve[$current_bean->parent_type]))
3702 $post_retrieve[$current_bean->parent_type] = array();
3704 $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');
3706 //$current_bean->fill_in_additional_list_fields();
3707 $list[$current_bean->id] = $current_bean;
3709 // go to the next row
3711 $row = $db->fetchByAssoc($result, $index);
3714 //now handle retrieving many-to-many relationships
3717 foreach($secondary_queries as $query2)
3719 $result2 = $db->query($query2);
3721 $row2 = $db->fetchByAssoc($result2);
3724 $id_ref = $row2['ref_id'];
3726 if(isset($list[$id_ref]))
3728 foreach($row2 as $r2key=>$r2value)
3730 if($r2key != 'ref_id')
3732 $list[$id_ref]->$r2key = $r2value;
3736 $row2 = $db->fetchByAssoc($result2);
3742 if(isset($post_retrieve))
3744 $parent_fields = $this->retrieve_parent_fields($post_retrieve);
3748 $parent_fields = array();
3750 if(!empty($sugar_config['disable_count_query']) && !empty($limit))
3752 //C.L. Bug 43535 - Use the $index value to set the $rows_found value here
3753 $rows_found = isset($index) ? $index : $row_offset + count($list);
3755 if(count($list) >= $limit)
3769 $parent_fields = array();
3771 $response = array();
3772 $response['list'] = $list;
3773 $response['parent_data'] = $parent_fields;
3774 $response['row_count'] = $rows_found;
3775 $response['next_offset'] = $next_offset;
3776 $response['previous_offset'] = $previous_offset;
3777 $response['current_offset'] = $row_offset ;
3778 $response['query'] = $query;
3784 * Applies pagination window to select queries used by detail view,
3785 * executes the query and returns fetched data.
3787 * Internal function, do not override.
3788 * @param string $query query to be processed.
3789 * @param int $row_offset
3790 * @param int $limit optional, default -1
3791 * @param int $max_per_page Optional, default -1
3792 * @param string $where Custom where clause.
3793 * @param int $offset Optional, default 0
3794 * @return array Fetched data.
3797 function process_detail_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '', $offset = 0)
3799 global $sugar_config;
3800 $GLOBALS['log']->debug("process_detail_query: ".$query);
3801 if($max_per_page == -1)
3803 $max_per_page = $sugar_config['list_max_entries_per_page'];
3806 // Check to see if we have a count query available.
3807 $count_query = $this->create_list_count_query($query);
3809 if(!empty($count_query) && (empty($limit) || $limit == -1))
3811 // We have a count query. Run it and get the results.
3812 $result = $this->db->query($count_query, true, "Error running count query for $this->object_name List: ");
3813 $assoc = $this->db->fetchByAssoc($result);
3814 if(!empty($assoc['c']))
3816 $total_rows = $assoc['c'];
3820 if(empty($row_offset))
3825 $result = $this->db->limitQuery($query, $offset, 1, true,"Error retrieving $this->object_name list: ");
3827 $rows_found = $this->db->getRowCount($result);
3829 $GLOBALS['log']->debug("Found $rows_found ".$this->object_name."s");
3831 $previous_offset = $row_offset - $max_per_page;
3832 $next_offset = $row_offset + $max_per_page;
3834 if($rows_found != 0 || !$this->db->supports('select_rows'))
3837 $row = $this->db->fetchByAssoc($result, $index);
3838 $this->retrieve($row['id']);
3841 $response = Array();
3842 $response['bean'] = $this;
3843 if (empty($total_rows))
3845 $response['row_count'] = $total_rows;
3846 $response['next_offset'] = $next_offset;
3847 $response['previous_offset'] = $previous_offset;
3853 * Processes fetched list view data
3855 * Internal function, do not override.
3856 * @param string $query query to be processed.
3857 * @param boolean $check_date Optional, default false. if set to true date time values are processed.
3858 * @return array Fetched data.
3861 function process_full_list_query($query, $check_date=false)
3864 $GLOBALS['log']->debug("process_full_list_query: query is ".$query);
3865 $result = $this->db->query($query, false);
3866 $GLOBALS['log']->debug("process_full_list_query: result is ".print_r($result,true));
3867 $class = get_class($this);
3868 $isFirstTime = true;
3869 $bean = new $class();
3871 //if($this->db->getRowCount($result) > 0){
3874 // We have some data.
3875 //while ($row = $this->db->fetchByAssoc($result)) {
3876 while (($row = $bean->db->fetchByAssoc($result)) != null)
3880 $bean = new $class();
3882 $isFirstTime = false;
3884 foreach($bean->field_defs as $field=>$value)
3886 if (isset($row[$field]))
3888 $bean->$field = $row[$field];
3889 $GLOBALS['log']->debug("process_full_list: $bean->object_name({$row['id']}): ".$field." = ".$bean->$field);
3898 $bean->processed_dates_times = array();
3899 $bean->check_date_relationships_load();
3901 $bean->fill_in_additional_list_fields();
3902 $bean->call_custom_logic("process_record");
3903 $bean->fetched_row = $row;
3908 if (isset($list)) return $list;
3913 * Tracks the viewing of a detail record.
3914 * This leverages get_summary_text() which is object specific.
3916 * Internal function, do not override.
3917 * @param string $user_id - String value of the user that is viewing the record.
3918 * @param string $current_module - String value of the module being processed.
3919 * @param string $current_view - String value of the current view
3921 function track_view($user_id, $current_module, $current_view='')
3923 $trackerManager = TrackerManager::getInstance();
3924 if($monitor = $trackerManager->getMonitor('tracker')){
3925 $monitor->setValue('date_modified', $GLOBALS['timedate']->nowDb());
3926 $monitor->setValue('user_id', $user_id);
3927 $monitor->setValue('module_name', $current_module);
3928 $monitor->setValue('action', $current_view);
3929 $monitor->setValue('item_id', $this->id);
3930 $monitor->setValue('item_summary', $this->get_summary_text());
3931 $monitor->setValue('visible', $this->tracker_visibility);
3932 $trackerManager->saveMonitor($monitor);
3937 * Returns the summary text that should show up in the recent history list for this object.
3941 public function get_summary_text()
3943 return "Base Implementation. Should be overridden.";
3947 * This is designed to be overridden and add specific fields to each record.
3948 * This allows the generic query to fill in the major fields, and then targeted
3949 * queries to get related fields and add them to the record. The contact's
3950 * account for instance. This method is only used for populating extra fields
3953 function fill_in_additional_list_fields(){
3954 if(!empty($this->field_defs['parent_name']) && empty($this->parent_name)){
3955 $this->fill_in_additional_parent_fields();
3960 * This is designed to be overridden and add specific fields to each record.
3961 * This allows the generic query to fill in the major fields, and then targeted
3962 * queries to get related fields and add them to the record. The contact's
3963 * account for instance. This method is only used for populating extra fields
3964 * in the detail form
3966 function fill_in_additional_detail_fields()
3968 if(!empty($this->field_defs['assigned_user_name']) && !empty($this->assigned_user_id)){
3970 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
3973 if(!empty($this->field_defs['created_by']) && !empty($this->created_by))
3974 $this->created_by_name = get_assigned_user_name($this->created_by);
3975 if(!empty($this->field_defs['modified_user_id']) && !empty($this->modified_user_id))
3976 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
3978 if(!empty($this->field_defs['parent_name'])){
3979 $this->fill_in_additional_parent_fields();
3984 * This is desgined to be overridden or called from extending bean. This method
3985 * will fill in any parent_name fields.
3987 function fill_in_additional_parent_fields() {
3989 if(!empty($this->parent_id) && !empty($this->last_parent_id) && $this->last_parent_id == $this->parent_id){
3992 $this->parent_name = '';
3994 if(!empty($this->parent_type)) {
3995 $this->last_parent_id = $this->parent_id;
3996 $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'));
3997 if(!empty($this->parent_first_name) || !empty($this->parent_last_name) ){
3998 $this->parent_name = $GLOBALS['locale']->getLocaleFormattedName($this->parent_first_name, $this->parent_last_name);
3999 } else if(!empty($this->parent_document_name)){
4000 $this->parent_name = $this->parent_document_name;
4006 * Fill in a link field
4009 function fill_in_link_field( $linkFieldName )
4011 if ($this->load_relationship($linkFieldName))
4013 $list=$this->$linkFieldName->get();
4014 $this->$linkFieldName = '' ; // match up with null value in $this->populateFromRow()
4016 $this->$linkFieldName = $list[0];
4021 * Fill in fields where type = relate
4023 function fill_in_relationship_fields(){
4024 global $fill_in_rel_depth;
4025 if(empty($fill_in_rel_depth) || $fill_in_rel_depth < 0)
4026 $fill_in_rel_depth = 0;
4027 if($fill_in_rel_depth > 1)
4029 $fill_in_rel_depth++;
4031 foreach($this->field_defs as $field)
4033 if(0 == strcmp($field['type'],'relate') && !empty($field['module']))
4035 $name = $field['name'];
4036 if(empty($this->$name))
4038 // 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']
4039 $related_module = $field['module'];
4040 $id_name = $field['id_name'];
4041 if (empty($this->$id_name)){
4042 $this->fill_in_link_field($id_name);
4044 if(!empty($this->$id_name) && ( $this->object_name != $related_module || ( $this->object_name == $related_module && $this->$id_name != $this->id ))){
4045 if(isset($GLOBALS['beanList'][ $related_module])){
4046 $class = $GLOBALS['beanList'][$related_module];
4048 if(!empty($this->$id_name) && file_exists($GLOBALS['beanFiles'][$class]) && isset($this->$name)){
4049 require_once($GLOBALS['beanFiles'][$class]);
4050 $mod = new $class();
4051 $mod->retrieve($this->$id_name);
4052 if (!empty($field['rname'])) {
4053 $this->$name = $mod->$field['rname'];
4054 } else if (isset($mod->name)) {
4055 $this->$name = $mod->name;
4060 if(!empty($this->$id_name) && isset($this->$name))
4062 if(!isset($field['additionalFields']))
4063 $field['additionalFields'] = array();
4064 if(!empty($field['rname']))
4066 $field['additionalFields'][$field['rname']]= $name;
4070 $field['additionalFields']['name']= $name;
4072 $this->getRelatedFields($related_module, $this->$id_name, $field['additionalFields']);
4077 $fill_in_rel_depth--;
4081 * This is a helper function that is used to quickly created indexes when creating tables.
4083 function create_index($query)
4085 $GLOBALS['log']->info("create_index: $query");
4087 $result = $this->db->query($query, true, "Error creating index:");
4091 * This function should be overridden in each module. It marks an item as deleted.
4093 * If it is not overridden, then marking this type of item is not allowed
4095 function mark_deleted($id)
4097 global $current_user;
4098 $date_modified = $GLOBALS['timedate']->nowDb();
4099 if(isset($_SESSION['show_deleted']))
4101 $this->mark_undeleted($id);
4105 // call the custom business logic
4106 $custom_logic_arguments['id'] = $id;
4107 $this->call_custom_logic("before_delete", $custom_logic_arguments);
4109 $this->mark_relationships_deleted($id);
4110 if ( isset($this->field_defs['modified_user_id']) ) {
4111 if (!empty($current_user)) {
4112 $this->modified_user_id = $current_user->id;
4114 $this->modified_user_id = 1;
4116 $query = "UPDATE $this->table_name set deleted=1 , date_modified = '$date_modified', modified_user_id = '$this->modified_user_id' where id='$id'";
4118 $query = "UPDATE $this->table_name set deleted=1 , date_modified = '$date_modified' where id='$id'";
4120 $this->db->query($query, true,"Error marking record deleted: ");
4122 SugarRelationship::resaveRelatedBeans();
4124 // Take the item off the recently viewed lists
4125 $tracker = new Tracker();
4126 $tracker->makeInvisibleForAll($id);
4128 // call the custom business logic
4129 $this->call_custom_logic("after_delete", $custom_logic_arguments);
4134 * Restores data deleted by call to mark_deleted() function.
4136 * Internal function, do not override.
4138 function mark_undeleted($id)
4140 // call the custom business logic
4141 $custom_logic_arguments['id'] = $id;
4142 $this->call_custom_logic("before_restore", $custom_logic_arguments);
4144 $date_modified = $GLOBALS['timedate']->nowDb();
4145 $query = "UPDATE $this->table_name set deleted=0 , date_modified = '$date_modified' where id='$id'";
4146 $this->db->query($query, true,"Error marking record undeleted: ");
4148 // call the custom business logic
4149 $this->call_custom_logic("after_restore", $custom_logic_arguments);
4153 * This function deletes relationships to this object. It should be overridden
4154 * to handle the relationships of the specific object.
4155 * This function is called when the item itself is being deleted.
4157 * @param int $id id of the relationship to delete
4159 function mark_relationships_deleted($id)
4161 $this->delete_linked($id);
4165 * This function is used to execute the query and create an array template objects
4166 * from the resulting ids from the query.
4167 * It is currently used for building sub-panel arrays.
4169 * @param string $query - the query that should be executed to build the list
4170 * @param object $template - The object that should be used to copy the records.
4171 * @param int $row_offset Optional, default 0
4172 * @param int $limit Optional, default -1
4175 function build_related_list($query, &$template, $row_offset = 0, $limit = -1)
4177 $GLOBALS['log']->debug("Finding linked records $this->object_name: ".$query);
4178 $db = DBManagerFactory::getInstance('listviews');
4180 if(!empty($row_offset) && $row_offset != 0 && !empty($limit) && $limit != -1)
4182 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $template->object_name list: ");
4186 $result = $db->query($query, true);
4190 $isFirstTime = true;
4191 $class = get_class($template);
4192 while($row = $this->db->fetchByAssoc($result))
4196 $template = new $class();
4198 $isFirstTime = false;
4199 $record = $template->retrieve($row['id']);
4203 // this copies the object into the array
4204 $list[] = $template;
4211 * This function is used to execute the query and create an array template objects
4212 * from the resulting ids from the query.
4213 * It is currently used for building sub-panel arrays. It supports an additional
4214 * where clause that is executed as a filter on the results
4216 * @param string $query - the query that should be executed to build the list
4217 * @param object $template - The object that should be used to copy the records.
4219 function build_related_list_where($query, &$template, $where='', $in='', $order_by, $limit='', $row_offset = 0)
4221 $db = DBManagerFactory::getInstance('listviews');
4222 // No need to do an additional query
4223 $GLOBALS['log']->debug("Finding linked records $this->object_name: ".$query);
4224 if(empty($in) && !empty($query))
4226 $idList = $this->build_related_in($query);
4227 $in = $idList['in'];
4229 // MFH - Added Support For Custom Fields in Searches
4231 if(isset($this->custom_fields)) {
4232 $custom_join = $this->custom_fields->getJOIN();
4235 $query = "SELECT id ";
4237 if (!empty($custom_join)) {
4238 $query .= $custom_join['select'];
4240 $query .= " FROM $this->table_name ";
4242 if (!empty($custom_join) && !empty($custom_join['join'])) {
4243 $query .= " " . $custom_join['join'];
4246 $query .= " WHERE deleted=0 AND id IN $in";
4249 $query .= " AND $where";
4253 if(!empty($order_by))
4255 $query .= "ORDER BY $order_by";
4259 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $this->object_name list: ");
4263 $result = $db->query($query, true);
4267 $isFirstTime = true;
4268 $class = get_class($template);
4270 $disable_security_flag = ($template->disable_row_level_security) ? true : false;
4271 while($row = $db->fetchByAssoc($result))
4275 $template = new $class();
4276 $template->disable_row_level_security = $disable_security_flag;
4278 $isFirstTime = false;
4279 $record = $template->retrieve($row['id']);
4282 // this copies the object into the array
4283 $list[] = $template;
4291 * Constructs an comma seperated list of ids from passed query results.
4293 * @param string @query query to be executed.
4296 function build_related_in($query)
4299 $result = $this->db->query($query, true);
4301 while($row = $this->db->fetchByAssoc($result))
4303 $idList[] = $row['id'];
4306 $ids = "('" . $row['id'] . "'";
4310 $ids .= ",'" . $row['id'] . "'";
4320 return array('list'=>$idList, 'in'=>$ids);
4324 * Optionally copies values from fetched row into the bean.
4326 * Internal function, do not override.
4328 * @param string $query - the query that should be executed to build the list
4329 * @param object $template - The object that should be used to copy the records
4330 * @param array $field_list List of fields.
4333 function build_related_list2($query, &$template, &$field_list)
4335 $GLOBALS['log']->debug("Finding linked values $this->object_name: ".$query);
4337 $result = $this->db->query($query, true);
4340 $isFirstTime = true;
4341 $class = get_class($template);
4342 while($row = $this->db->fetchByAssoc($result))
4344 // Create a blank copy
4348 $copy = new $class();
4350 $isFirstTime = false;
4351 foreach($field_list as $field)
4353 // Copy the relevant fields
4354 $copy->$field = $row[$field];
4358 // this copies the object into the array
4366 * Let implementing classes to fill in row specific columns of a list view form
4369 function list_view_parse_additional_sections(&$list_form)
4374 * Assigns all of the values into the template for the list view
4376 function get_list_view_array()
4378 static $cache = array();
4379 // cn: bug 12270 - sensitive fields being passed arbitrarily in listViews
4380 $sensitiveFields = array('user_hash' => '');
4382 $return_array = Array();
4383 global $app_list_strings, $mod_strings;
4384 foreach($this->field_defs as $field=>$value){
4386 if(isset($this->$field)){
4388 // cn: bug 12270 - sensitive fields being passed arbitrarily in listViews
4389 if(isset($sensitiveFields[$field]))
4391 if(!isset($cache[$field]))
4392 $cache[$field] = strtoupper($field);
4394 //Fields hidden by Dependent Fields
4395 if (isset($value['hidden']) && $value['hidden'] === true) {
4396 $return_array[$cache[$field]] = "";
4399 //cn: if $field is a _dom, detect and return VALUE not KEY
4400 //cl: empty function check for meta-data enum types that have values loaded from a function
4401 else if (((!empty($value['type']) && ($value['type'] == 'enum' || $value['type'] == 'radioenum') )) && empty($value['function'])){
4402 if(!empty($app_list_strings[$value['options']][$this->$field])){
4403 $return_array[$cache[$field]] = $app_list_strings[$value['options']][$this->$field];
4405 //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.
4406 elseif(!empty($mod_strings[$value['options']][$this->$field]))
4408 $return_array[$cache[$field]] = $mod_strings[$value['options']][$this->$field];
4411 $return_array[$cache[$field]] = $this->$field;
4414 // tjy: no need to do this str_replace as the changes in 29994 for ListViewGeneric.tpl for translation handle this now
4415 // }elseif(!empty($value['type']) && $value['type'] == 'multienum'&& empty($value['function'])){
4416 // $return_array[strtoupper($field)] = str_replace('^,^', ', ', $this->$field );
4417 }elseif(!empty($value['custom_module']) && $value['type'] != 'currency'){
4418 // $this->format_field($value);
4419 $return_array[$cache[$field]] = $this->$field;
4421 $return_array[$cache[$field]] = $this->$field;
4423 // handle "Assigned User Name"
4424 if($field == 'assigned_user_name'){
4425 $return_array['ASSIGNED_USER_NAME'] = get_assigned_user_name($this->assigned_user_id);
4429 return $return_array;
4432 * Override this function to set values in the array used to render list view data.
4435 function get_list_view_data()
4437 return $this->get_list_view_array();
4441 * Construct where clause from a list of name-value pairs.
4444 function get_where(&$fields_array)
4446 $where_clause = "WHERE ";
4448 foreach ($fields_array as $name=>$value)
4456 $where_clause .= " AND ";
4459 $where_clause .= "$name = '".$this->db->quote($value,false)."'";
4461 $where_clause .= " AND deleted=0";
4462 return $where_clause;
4467 * Constructs a select query and fetch 1 row using this query, and then process the row
4469 * Internal function, do not override.
4470 * @param array @fields_array array of name value pairs used to construct query.
4471 * @param boolean $encode Optional, default true, encode fetched data.
4472 * @return object Instance of this bean with fetched data.
4474 function retrieve_by_string_fields($fields_array, $encode=true)
4476 $where_clause = $this->get_where($fields_array);
4477 if(isset($this->custom_fields))
4478 $custom_join = $this->custom_fields->getJOIN();
4479 else $custom_join = false;
4482 $query = "SELECT $this->table_name.*". $custom_join['select']. " FROM $this->table_name " . $custom_join['join'];
4486 $query = "SELECT $this->table_name.* FROM $this->table_name ";
4488 $query .= " $where_clause";
4489 $GLOBALS['log']->debug("Retrieve $this->object_name: ".$query);
4490 //requireSingleResult has beeen deprecated.
4491 //$result = $this->db->requireSingleResult($query, true, "Retrieving record $where_clause:");
4492 $result = $this->db->limitQuery($query,0,1,true, "Retrieving record $where_clause:");
4499 if($this->db->getRowCount($result) > 1)
4501 $this->duplicates_found = true;
4503 $row = $this->db->fetchByAssoc($result, -1, $encode);
4508 $row = $this->convertRow($row);
4509 $this->fetched_row = $row;
4510 $this->fromArray($row);
4511 $this->fill_in_additional_detail_fields();
4516 * This method is called during an import before inserting a bean
4517 * Define an associative array called $special_fields
4518 * the keys are user defined, and don't directly map to the bean's fields
4519 * the value is the method name within that bean that will do extra
4520 * processing for that field. example: 'full_name'=>'get_names_from_full_name'
4523 function process_special_fields()
4525 foreach ($this->special_functions as $func_name)
4527 if ( method_exists($this,$func_name) )
4529 $this->$func_name();
4535 * Override this function to build a where clause based on the search criteria set into bean .
4538 function build_generic_where_clause($value)
4542 function getRelatedFields($module, $id, $fields, $return_array = false){
4543 if(empty($GLOBALS['beanList'][$module]))return '';
4544 $object = $GLOBALS['beanList'][$module];
4545 if ($object == 'aCase') {
4549 VardefManager::loadVardef($module, $object);
4550 if(empty($GLOBALS['dictionary'][$object]['table']))return '';
4551 $table = $GLOBALS['dictionary'][$object]['table'];
4552 $query = 'SELECT id';
4553 foreach($fields as $field=>$alias){
4554 if(!empty($GLOBALS['dictionary'][$object]['fields'][$field]['db_concat_fields'])){
4555 $query .= ' ,' .db_concat($table, $GLOBALS['dictionary'][$object]['fields'][$field]['db_concat_fields']) . ' as ' . $alias ;
4556 }else if(!empty($GLOBALS['dictionary'][$object]['fields'][$field]) &&
4557 (empty($GLOBALS['dictionary'][$object]['fields'][$field]['source']) ||
4558 $GLOBALS['dictionary'][$object]['fields'][$field]['source'] != "non-db"))
4560 $query .= ' ,' .$table . '.' . $field . ' as ' . $alias;
4562 if(!$return_array)$this->$alias = '';
4564 if($query == 'SELECT id' || empty($id)){
4569 if(isset($GLOBALS['dictionary'][$object]['fields']['assigned_user_id']))
4571 $query .= " , ". $table . ".assigned_user_id owner";
4574 else if(isset($GLOBALS['dictionary'][$object]['fields']['created_by']))
4576 $query .= " , ". $table . ".created_by owner";
4579 $query .= ' FROM ' . $table . ' WHERE deleted=0 AND id=';
4580 $result = $GLOBALS['db']->query($query . "'$id'" );
4581 $row = $GLOBALS['db']->fetchByAssoc($result);
4585 $owner = (empty($row['owner']))?'':$row['owner'];
4586 foreach($fields as $alias){
4587 $this->$alias = (!empty($row[$alias]))? $row[$alias]: '';
4588 $alias = $alias .'_owner';
4589 $this->$alias = $owner;
4590 $a_mod = $alias .'_mod';
4591 $this->$a_mod = $module;
4598 function &parse_additional_headers(&$list_form, $xTemplateSection)
4603 function assign_display_fields($currentModule)
4606 foreach($this->column_fields as $field)
4608 if(isset($this->field_name_map[$field]) && empty($this->$field))
4610 if($this->field_name_map[$field]['type'] != 'date' && $this->field_name_map[$field]['type'] != 'enum')
4611 $this->$field = $field;
4612 if($this->field_name_map[$field]['type'] == 'date')
4614 $this->$field = $timedate->to_display_date('1980-07-09');
4616 if($this->field_name_map[$field]['type'] == 'enum')
4618 $dom = $this->field_name_map[$field]['options'];
4619 global $current_language, $app_list_strings;
4620 $mod_strings = return_module_language($current_language, $currentModule);
4622 if(isset($mod_strings[$dom]))
4624 $options = $mod_strings[$dom];
4625 foreach($options as $key=>$value)
4627 if(!empty($key) && empty($this->$field ))
4629 $this->$field = $key;
4633 if(isset($app_list_strings[$dom]))
4635 $options = $app_list_strings[$dom];
4636 foreach($options as $key=>$value)
4638 if(!empty($key) && empty($this->$field ))
4640 $this->$field = $key;
4652 * RELATIONSHIP HANDLING
4655 function set_relationship($table, $relate_values, $check_duplicates = true,$do_update=false,$data_values=null)
4659 // make sure there is a date modified
4660 $date_modified = $this->db->convert("'".$GLOBALS['timedate']->nowDb()."'", 'datetime');
4663 if($check_duplicates)
4665 $query = "SELECT * FROM $table ";
4666 $where = "WHERE deleted = '0' ";
4667 foreach($relate_values as $name=>$value)
4669 $where .= " AND $name = '$value' ";
4672 $result = $this->db->query($query, false, "Looking For Duplicate Relationship:" . $query);
4673 $row=$this->db->fetchByAssoc($result);
4676 if(!$check_duplicates || empty($row) )
4678 unset($relate_values['id']);
4679 if ( isset($data_values))
4681 $relate_values = array_merge($relate_values,$data_values);
4683 $query = "INSERT INTO $table (id, ". implode(',', array_keys($relate_values)) . ", date_modified) VALUES ('" . create_guid() . "', " . "'" . implode("', '", $relate_values) . "', ".$date_modified.")" ;
4685 $this->db->query($query, false, "Creating Relationship:" . $query);
4687 else if ($do_update)
4690 foreach($data_values as $key=>$value)
4692 array_push($conds,$key."='".$this->db->quote($value)."'");
4694 $query = "UPDATE $table SET ". implode(',', $conds).",date_modified=".$date_modified." ".$where;
4695 $this->db->query($query, false, "Updating Relationship:" . $query);
4699 function retrieve_relationships($table, $values, $select_id)
4701 $query = "SELECT $select_id FROM $table WHERE deleted = 0 ";
4702 foreach($values as $name=>$value)
4704 $query .= " AND $name = '$value' ";
4706 $query .= " ORDER BY $select_id ";
4707 $result = $this->db->query($query, false, "Retrieving Relationship:" . $query);
4709 while($row = $this->db->fetchByAssoc($result))
4716 // TODO: this function needs adjustment
4717 function loadLayoutDefs()
4719 global $layout_defs;
4720 if(empty( $this->layout_def) && file_exists('modules/'. $this->module_dir . '/layout_defs.php'))
4722 include_once('modules/'. $this->module_dir . '/layout_defs.php');
4723 if(file_exists('custom/modules/'. $this->module_dir . '/Ext/Layoutdefs/layoutdefs.ext.php'))
4725 include_once('custom/modules/'. $this->module_dir . '/Ext/Layoutdefs/layoutdefs.ext.php');
4727 if ( empty( $layout_defs[get_class($this)]))
4729 echo "\$layout_defs[" . get_class($this) . "]; does not exist";
4732 $this->layout_def = $layout_defs[get_class($this)];
4737 * Trigger custom logic for this module that is defined for the provided hook
4738 * The custom logic file is located under custom/modules/[CURRENT_MODULE]/logic_hooks.php.
4739 * That file should define the $hook_version that should be used.
4740 * It should also define the $hook_array. The $hook_array will be a two dimensional array
4741 * the first dimension is the name of the event, the second dimension is the information needed
4742 * to fire the hook. Each entry in the top level array should be defined on a single line to make it
4743 * easier to automatically replace this file. There should be no contents of this file that are not replacable.
4745 * $hook_array['before_save'][] = Array(1, testtype, 'custom/modules/Leads/test12.php', 'TestClass', 'lead_before_save_1');
4746 * This sample line creates a before_save hook. The hooks are procesed in the order in which they
4747 * are added to the array. The second dimension is an array of:
4748 * processing index (for sorting before exporting the array)
4751 * php file to include
4752 * php class the method is in
4753 * php method to call
4755 * The method signature for version 1 hooks is:
4756 * function NAME(&$bean, $event, $arguments)
4757 * $bean - $this bean passed in by reference.
4758 * $event - The string for the current event (i.e. before_save)
4759 * $arguments - An array of arguments that are specific to the event.
4761 function call_custom_logic($event, $arguments = null)
4763 if(!isset($this->processed) || $this->processed == false){
4764 //add some logic to ensure we do not get into an infinite loop
4765 if(!empty($this->logicHookDepth[$event])) {
4766 if($this->logicHookDepth[$event] > 10)
4769 $this->logicHookDepth[$event] = 0;
4771 //we have to put the increment operator here
4772 //otherwise we may never increase the depth for that event in the case
4773 //where one event will trigger another as in the case of before_save and after_save
4774 //Also keeping the depth per event allow any number of hooks to be called on the bean
4775 //and we only will return if one event gets caught in a loop. We do not increment globally
4776 //for each event called.
4777 $this->logicHookDepth[$event]++;
4779 //method defined in 'include/utils/LogicHook.php'
4781 $logicHook = new LogicHook();
4782 $logicHook->setBean($this);
4783 $logicHook->call_custom_logic($this->module_dir, $event, $arguments);
4788 /* When creating a custom field of type Dropdown, it creates an enum row in the DB.
4789 A typical get_list_view_array() result will have the *KEY* value from that drop-down.
4790 Since custom _dom objects are flat-files included in the $app_list_strings variable,
4791 We need to generate a key-key pair to get the true value like so:
4792 ([module]_cstm->fields_meta_data->$app_list_strings->*VALUE*)*/
4793 function getRealKeyFromCustomFieldAssignedKey($name)
4795 if ($this->custom_fields->avail_fields[$name]['ext1'])
4799 elseif ($this->custom_fields->avail_fields[$name]['ext2'])
4803 elseif ($this->custom_fields->avail_fields[$name]['ext3'])
4809 $GLOBALS['log']->fatal("SUGARBEAN: cannot find Real Key for custom field of type dropdown - cannot return Value.");
4814 return $this->custom_fields->avail_fields[$name][$realKey];
4818 function bean_implements($interface)
4823 * Check whether the user has access to a particular view for the current bean/module
4824 * @param $view string required, the view to determine access for i.e. DetailView, ListView...
4825 * @param $is_owner bool optional, this is part of the ACL check if the current user is an owner they will receive different access
4827 function ACLAccess($view,$is_owner='not_set')
4829 global $current_user;
4830 if($current_user->isAdminForModule($this->getACLCategory())) {
4834 if($is_owner == 'not_set')
4837 $is_owner = $this->isOwner($current_user->id);
4840 //if we don't implent acls return true
4841 if(!$this->bean_implements('ACL'))
4843 $view = strtolower($view);
4849 return ACLController::checkAccess($this->module_dir,'list', true);
4852 if( !$is_owner && $not_set && !empty($this->id)){
4853 $class = get_class($this);
4854 $temp = new $class();
4855 if(!empty($this->fetched_row) && !empty($this->fetched_row['id']) && !empty($this->fetched_row['assigned_user_id']) && !empty($this->fetched_row['created_by'])){
4856 $temp->populateFromRow($this->fetched_row);
4858 $temp->retrieve($this->id);
4860 $is_owner = $temp->isOwner($current_user->id);
4862 case 'popupeditview':
4864 return ACLController::checkAccess($this->module_dir,'edit', $is_owner, $this->acltype);
4868 return ACLController::checkAccess($this->module_dir,'view', $is_owner, $this->acltype);
4870 return ACLController::checkAccess($this->module_dir,'delete', $is_owner, $this->acltype);
4872 return ACLController::checkAccess($this->module_dir,'export', $is_owner, $this->acltype);
4874 return ACLController::checkAccess($this->module_dir,'import', true, $this->acltype);
4876 //if it is not one of the above views then it should be implemented on the page level
4880 * Returns true of false if the user_id passed is the owner
4882 * @param GUID $user_id
4885 function isOwner($user_id)
4887 //if we don't have an id we must be the owner as we are creating it
4888 if(!isset($this->id))
4892 //if there is an assigned_user that is the owner
4893 if(isset($this->assigned_user_id))
4895 if($this->assigned_user_id == $user_id) return true;
4900 //other wise if there is a created_by that is the owner
4901 if(isset($this->created_by) && $this->created_by == $user_id)
4909 * Gets there where statement for checking if a user is an owner
4911 * @param GUID $user_id
4914 function getOwnerWhere($user_id)
4916 if(isset($this->field_defs['assigned_user_id']))
4918 return " $this->table_name.assigned_user_id ='$user_id' ";
4920 if(isset($this->field_defs['created_by']))
4922 return " $this->table_name.created_by ='$user_id' ";
4929 * Used in order to manage ListView links and if they should
4930 * links or not based on the ACL permissions of the user
4932 * @return ARRAY of STRINGS
4934 function listviewACLHelper()
4936 $array_assign = array();
4937 if($this->ACLAccess('DetailView'))
4939 $array_assign['MAIN'] = 'a';
4943 $array_assign['MAIN'] = 'span';
4945 return $array_assign;
4949 * returns this bean as an array
4951 * @return array of fields with id, name, access and category
4953 function toArray($dbOnly = false, $stringOnly = false, $upperKeys=false)
4955 static $cache = array();
4958 foreach($this->field_defs as $field=>$data)
4960 if( !$dbOnly || !isset($data['source']) || $data['source'] == 'db')
4961 if(!$stringOnly || is_string($this->$field))
4964 if(!isset($cache[$field])){
4965 $cache[$field] = strtoupper($field);
4967 $arr[$cache[$field]] = $this->$field;
4971 if(isset($this->$field)){
4972 $arr[$field] = $this->$field;
4982 * Converts an array into an acl mapping name value pairs into files
4986 function fromArray($arr)
4988 foreach($arr as $name=>$value)
4990 $this->$name = $value;
4995 * Convert row data from DB format to internal format
4996 * Mostly useful for dates/times
4998 * @return array $row
5000 public function convertRow($row)
5002 foreach($this->field_defs as $name => $fieldDef)
5004 // skip empty fields and non-db fields
5005 if(empty($row[$name])) continue;
5006 if(isset($fieldDef['source']) && $fieldDef['source'] != 'db') continue;
5007 // fromConvert other fields
5008 $row[$name] = $this->db->fromConvert($row[$name], $this->db->getFieldType($fieldDef));
5014 * Loads a row of data into instance of a bean. The data is passed as an array to this function
5016 * @param array $arr row of data fetched from the database.
5019 * Internal function do not override.
5021 function loadFromRow($arr)
5023 $this->populateFromRow($arr);
5024 $this->processed_dates_times = array();
5025 $this->check_date_relationships_load();
5027 $this->fill_in_additional_list_fields();
5029 if($this->hasCustomFields())$this->custom_fields->fill_relationships();
5030 $this->call_custom_logic("process_record");
5033 function hasCustomFields()
5035 return !empty($GLOBALS['dictionary'][$this->object_name]['custom_fields']);
5039 * Ensure that fields within order by clauses are properly qualified with
5040 * their tablename. This qualification is a requirement for sql server support.
5042 * @param string $order_by original order by from the query
5043 * @param string $qualify prefix for columns in the order by list.
5046 * Internal function do not override.
5048 function create_qualified_order_by( $order_by, $qualify)
5049 { // 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
5050 if (empty($order_by))
5054 $order_by_clause = " ORDER BY ";
5055 $tmp = explode(",", $order_by);
5057 foreach ( $tmp as $stmp)
5059 $stmp = (substr_count($stmp, ".") > 0?trim($stmp):"$qualify." . trim($stmp));
5060 $order_by_clause .= $comma . $stmp;
5063 return $order_by_clause;
5067 * Combined the contents of street field 2 thru 4 into the main field
5069 * @param string $street_field
5072 function add_address_streets(
5076 $street_field_2 = $street_field.'_2';
5077 $street_field_3 = $street_field.'_3';
5078 $street_field_4 = $street_field.'_4';
5079 if ( isset($this->$street_field_2)) {
5080 $this->$street_field .= "\n". $this->$street_field_2;
5081 unset($this->$street_field_2);
5083 if ( isset($this->$street_field_3)) {
5084 $this->$street_field .= "\n". $this->$street_field_3;
5085 unset($this->$street_field_3);
5087 if ( isset($this->$street_field_4)) {
5088 $this->$street_field .= "\n". $this->$street_field_4;
5089 unset($this->$street_field_4);
5091 if ( isset($this->$street_field)) {
5092 $this->$street_field = trim($this->$street_field, "\n");
5096 * Encrpyt and base64 encode an 'encrypt' field type in the bean using Blowfish. The default system key is stored in cache/Blowfish/{keytype}
5097 * @param STRING value -plain text value of the bean field.
5100 function encrpyt_before_save($value)
5102 require_once("include/utils/encryption_utils.php");
5103 return blowfishEncode(blowfishGetKey('encrypt_field'),$value);
5107 * Decode and decrypt a base 64 encoded string with field type 'encrypt' in this bean using Blowfish.
5108 * @param STRING value - an encrypted and base 64 encoded string.
5111 function decrypt_after_retrieve($value)
5113 require_once("include/utils/encryption_utils.php");
5114 return blowfishDecode(blowfishGetKey('encrypt_field'), $value);
5118 * Moved from save() method, functionality is the same, but this is intended to handle
5119 * Optimistic locking functionality.
5121 private function _checkOptimisticLocking($action, $isUpdate){
5122 if($this->optimistic_lock && !isset($_SESSION['o_lock_fs'])){
5123 if(isset($_SESSION['o_lock_id']) && $_SESSION['o_lock_id'] == $this->id && $_SESSION['o_lock_on'] == $this->object_name)
5125 if($action == 'Save' && $isUpdate && isset($this->modified_user_id) && $this->has_been_modified_since($_SESSION['o_lock_dm'], $this->modified_user_id))
5127 $_SESSION['o_lock_class'] = get_class($this);
5128 $_SESSION['o_lock_module'] = $this->module_dir;
5129 $_SESSION['o_lock_object'] = $this->toArray();
5130 $saveform = "<form name='save' id='save' method='POST'>";
5131 foreach($_POST as $key=>$arg)
5133 $saveform .= "<input type='hidden' name='". addslashes($key) ."' value='". addslashes($arg) ."'>";
5135 $saveform .= "</form><script>document.getElementById('save').submit();</script>";
5136 $_SESSION['o_lock_save'] = $saveform;
5137 header('Location: index.php?module=OptimisticLock&action=LockResolve');
5142 unset ($_SESSION['o_lock_object']);
5143 unset ($_SESSION['o_lock_id']);
5144 unset ($_SESSION['o_lock_dm']);
5150 if(isset($_SESSION['o_lock_object'])) { unset ($_SESSION['o_lock_object']); }
5151 if(isset($_SESSION['o_lock_id'])) { unset ($_SESSION['o_lock_id']); }
5152 if(isset($_SESSION['o_lock_dm'])) { unset ($_SESSION['o_lock_dm']); }
5153 if(isset($_SESSION['o_lock_fs'])) { unset ($_SESSION['o_lock_fs']); }
5154 if(isset($_SESSION['o_lock_save'])) { unset ($_SESSION['o_lock_save']); }
5159 * Send assignment notifications and invites for meetings and calls
5161 private function _sendNotifications($check_notify){
5162 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.
5163 && !$this->isOwner($this->created_by) ) // cn: bug 42727 no need to send email to owner (within workflow)
5165 $admin = new Administration();
5166 $admin->retrieveSettings();
5167 $sendNotifications = false;
5169 if ($admin->settings['notify_on'])
5171 $GLOBALS['log']->info("Notifications: user assignment has changed, checking if user receives notifications");
5172 $sendNotifications = true;
5174 elseif(isset($_REQUEST['send_invites']) && $_REQUEST['send_invites'] == 1)
5176 // cn: bug 5795 Send Invites failing for Contacts
5177 $sendNotifications = true;
5181 $GLOBALS['log']->info("Notifications: not sending e-mail, notify_on is set to OFF");
5185 if($sendNotifications == true)
5187 $notify_list = $this->get_notification_recipients();
5188 foreach ($notify_list as $notify_user)
5190 $this->send_assignment_notifications($notify_user, $admin);
5198 * Called from ImportFieldSanitize::relate(), when creating a new bean in a related module. Will
5199 * copies fields over from the current bean into the related. Designed to be overriden in child classes.
5201 * @param SugarBean $newbean newly created related bean
5203 public function populateRelatedBean(
5210 * Called during the import process before a bean save, to handle any needed pre-save logic when
5211 * importing a record
5213 public function beforeImportSave()
5218 * Called during the import process after a bean save, to handle any needed post-save logic when
5219 * importing a record
5221 public function afterImportSave()
5226 * This function is designed to cache references to field arrays that were previously stored in the
5227 * bean files and have since been moved to seperate files. Was previously in include/CacheHandler.php
5230 * @param $module_dir string the module directory
5231 * @param $module string the name of the module
5232 * @param $key string the type of field array we are referencing, i.e. list_fields, column_fields, required_fields
5234 private function _loadCachedArray(
5240 static $moduleDefs = array();
5242 $fileName = 'field_arrays.php';
5244 $cache_key = "load_cached_array.$module_dir.$module.$key";
5245 $result = sugar_cache_retrieve($cache_key);
5248 // Use SugarCache::EXTERNAL_CACHE_NULL_VALUE to store null values in the cache.
5249 if($result == SugarCache::EXTERNAL_CACHE_NULL_VALUE)
5257 if(file_exists('modules/'.$module_dir.'/'.$fileName))
5259 // If the data was not loaded, try loading again....
5260 if(!isset($moduleDefs[$module]))
5262 include('modules/'.$module_dir.'/'.$fileName);
5263 $moduleDefs[$module] = $fields_array;
5265 // Now that we have tried loading, make sure it was loaded
5266 if(empty($moduleDefs[$module]) || empty($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);
5273 // It has been loaded, cache the result.
5274 sugar_cache_put($cache_key, $moduleDefs[$module][$module][$key]);
5275 return $moduleDefs[$module][$module][$key];
5278 // It was not loaded.... Fail. Cache null to prevent future repeats of this calculation
5279 sugar_cache_put($cache_key, SugarCache::EXTERNAL_CACHE_NULL_VALUE);
5284 * Returns the ACL category for this module; defaults to the SugarBean::$acl_category if defined
5285 * otherwise it is SugarBean::$module_dir
5289 public function getACLCategory()
5291 return !empty($this->acl_category)?$this->acl_category:$this->module_dir;
5295 * Returns the query used for the export functionality for a module. Override this method if you wish
5296 * to have a custom query to pull this data together instead
5298 * @param string $order_by
5299 * @param string $where
5300 * @return string SQL query
5302 public function create_export_query($order_by, $where)
5304 return $this->create_new_list_query($order_by, $where, array(), array(), 0, '', false, $this, true, true);