]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - data/SugarBean.php
Release 6.5.9
[Github/sugarcrm.git] / data / SugarBean.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
6  * 
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.
13  * 
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
17  * details.
18  * 
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
22  * 02110-1301 USA.
23  * 
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.
26  * 
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.
30  * 
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  ********************************************************************************/
37
38 /*********************************************************************************
39
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  *******************************************************************************/
47
48 require_once('modules/DynamicFields/DynamicField.php');
49 require_once("data/Relationships/RelationshipFactory.php");
50
51
52
53
54
55 /**
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).
60  *
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).
65  * @api
66  */
67 class SugarBean
68 {
69     /**
70      * A pointer to the database object
71      *
72      * @var DBManager
73      */
74     var $db;
75
76     /**
77      * Unique object identifier
78      *
79      * @var string
80      */
81     public $id;
82
83     /**
84          * When createing a bean, you can specify a value in the id column as
85          * long as that value is unique.  During save, if the system finds an
86          * id, it assumes it is an update.  Setting new_with_id to true will
87          * make sure the system performs an insert instead of an update.
88          *
89          * @var BOOL -- default false
90          */
91         var $new_with_id = false;
92
93
94         /**
95          * How deep logic hooks can go
96          * @var int
97          */
98         protected $max_logic_depth = 10;
99
100         /**
101          * Disble vardefs.  This should be set to true only for beans that do not have varders.  Tracker is an example
102          *
103          * @var BOOL -- default false
104          */
105     var $disable_vardefs = false;
106
107
108     /**
109      * holds the full name of the user that an item is assigned to.  Only used if notifications
110      * are turned on and going to be sent out.
111      *
112      * @var String
113      */
114     var $new_assigned_user_name;
115
116         /**
117          * An array of booleans.  This array is cleared out when data is loaded.
118          * As date/times are converted, a "1" is placed under the key, the field is converted.
119          *
120          * @var Array of booleans
121          */
122         var $processed_dates_times = array();
123
124         /**
125          * Whether to process date/time fields for storage in the database in GMT
126          *
127          * @var BOOL
128          */
129         var $process_save_dates =true;
130
131     /**
132      * This signals to the bean that it is being saved in a mass mode.
133      * Examples of this kind of save are import and mass update.
134      * We turn off notificaitons of this is the case to make things more efficient.
135      *
136      * @var BOOL
137      */
138     var $save_from_post = true;
139
140         /**
141          * When running a query on related items using the method: retrieve_by_string_fields
142          * this value will be set to true if more than one item matches the search criteria.
143          *
144          * @var BOOL
145          */
146         var $duplicates_found = false;
147
148         /**
149          * true if this bean has been deleted, false otherwise.
150          *
151          * @var BOOL
152          */
153         var $deleted = 0;
154
155     /**
156      * Should the date modified column of the bean be updated during save?
157      * This is used for admin level functionality that should not be updating
158      * the date modified.  This is only used by sync to allow for updates to be
159      * replicated in a way that will not cause them to be replicated back.
160      *
161      * @var BOOL
162      */
163     var $update_date_modified = true;
164
165     /**
166      * Should the modified by column of the bean be updated during save?
167      * This is used for admin level functionality that should not be updating
168      * the modified by column.  This is only used by sync to allow for updates to be
169      * replicated in a way that will not cause them to be replicated back.
170      *
171      * @var BOOL
172      */
173     var $update_modified_by = true;
174
175     /**
176      * Setting this to true allows for updates to overwrite the date_entered
177      *
178      * @var BOOL
179      */
180     var $update_date_entered = false;
181
182     /**
183      * This allows for seed data to be created without using the current uesr to set the id.
184      * This should be replaced by altering the current user before the call to save.
185      *
186      * @var unknown_type
187      */
188     //TODO This should be replaced by altering the current user before the call to save.
189     var $set_created_by = true;
190
191     var $team_set_id;
192
193     /**
194      * The database table where records of this Bean are stored.
195      *
196      * @var String
197      */
198     var $table_name = '';
199
200     /**
201     * This is the singular name of the bean.  (i.e. Contact).
202     *
203     * @var String
204     */
205     var $object_name = '';
206
207     /** Set this to true if you query contains a sub-select and bean is converting both select statements
208     * into count queries.
209     */
210     var $ungreedy_count=false;
211
212     /**
213     * The name of the module folder for this type of bean.
214     *
215     * @var String
216     */
217     var $module_dir = '';
218     var $module_name = '';
219     var $field_name_map;
220     var $field_defs;
221     var $custom_fields;
222     var $column_fields = array();
223     var $list_fields = array();
224     var $additional_column_fields = array();
225     var $relationship_fields = array();
226     var $current_notify_user;
227     var $fetched_row=false;
228     var $fetched_rel_row = array();
229     var $layout_def;
230     var $force_load_details = false;
231     var $optimistic_lock = false;
232     var $disable_custom_fields = false;
233     var $number_formatting_done = false;
234     var $process_field_encrypted=false;
235     /*
236     * The default ACL type
237     */
238     var $acltype = 'module';
239
240
241     var $additional_meta_fields = array();
242
243     /**
244      * Set to true in the child beans if the module supports importing
245      */
246     var $importable = false;
247
248     /**
249     * Set to true in the child beans if the module use the special notification template
250     */
251     var $special_notification = false;
252
253     /**
254      * Set to true if the bean is being dealt with in a workflow
255      */
256     var $in_workflow = false;
257
258     /**
259      *
260      * By default it will be true but if any module is to be kept non visible
261      * to tracker, then its value needs to be overriden in that particular module to false.
262      *
263      */
264     var $tracker_visibility = true;
265
266     /**
267      * Used to pass inner join string to ListView Data.
268      */
269     var $listview_inner_join = array();
270
271     /**
272      * Set to true in <modules>/Import/views/view.step4.php if a module is being imported
273      */
274     var $in_import = false;
275     /**
276      * A way to keep track of the loaded relationships so when we clone the object we can unset them.
277      *
278      * @var array
279      */
280     protected $loaded_relationships = array();
281
282         /**
283      * set to true if dependent fields updated
284      */
285     protected $is_updated_dependent_fields = false;
286
287     /**
288      * Blowfish encryption key
289      * @var string
290      */
291     static protected $field_key;
292
293     /**
294      * Constructor for the bean, it performs following tasks:
295      *
296      * 1. Initalized a database connections
297      * 2. Load the vardefs for the module implemeting the class. cache the entries
298      *    if needed
299      * 3. Setup row-level security preference
300      * All implementing classes  must call this constructor using the parent::SugarBean() class.
301      *
302      */
303     function SugarBean()
304     {
305         global  $dictionary, $current_user;
306         static $loaded_defs = array();
307         $this->db = DBManagerFactory::getInstance();
308         if (empty($this->module_name))
309             $this->module_name = $this->module_dir;
310         if((false == $this->disable_vardefs && empty($loaded_defs[$this->object_name])) || !empty($GLOBALS['reload_vardefs']))
311         {
312             VardefManager::loadVardef($this->module_dir, $this->object_name);
313
314             // build $this->column_fields from the field_defs if they exist
315             if (!empty($dictionary[$this->object_name]['fields'])) {
316                 foreach ($dictionary[$this->object_name]['fields'] as $key=>$value_array) {
317                     $column_fields[] = $key;
318                     if(!empty($value_array['required']) && !empty($value_array['name'])) {
319                         $this->required_fields[$value_array['name']] = 1;
320                     }
321                 }
322                 $this->column_fields = $column_fields;
323             }
324
325             //setup custom fields
326             if(!isset($this->custom_fields) &&
327                 empty($this->disable_custom_fields))
328             {
329                 $this->setupCustomFields($this->module_dir);
330             }
331             //load up field_arrays from CacheHandler;
332             if(empty($this->list_fields))
333                 $this->list_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'list_fields');
334             if(empty($this->column_fields))
335                 $this->column_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'column_fields');
336             if(empty($this->required_fields))
337                 $this->required_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'required_fields');
338
339             if(isset($GLOBALS['dictionary'][$this->object_name]) && !$this->disable_vardefs)
340             {
341                 $this->field_name_map = $dictionary[$this->object_name]['fields'];
342                 $this->field_defs =     $dictionary[$this->object_name]['fields'];
343
344                 if(!empty($dictionary[$this->object_name]['optimistic_locking']))
345                 {
346                     $this->optimistic_lock=true;
347                 }
348             }
349             $loaded_defs[$this->object_name]['column_fields'] =& $this->column_fields;
350             $loaded_defs[$this->object_name]['list_fields'] =& $this->list_fields;
351             $loaded_defs[$this->object_name]['required_fields'] =& $this->required_fields;
352             $loaded_defs[$this->object_name]['field_name_map'] =& $this->field_name_map;
353             $loaded_defs[$this->object_name]['field_defs'] =& $this->field_defs;
354         }
355         else
356         {
357             $this->column_fields =& $loaded_defs[$this->object_name]['column_fields'] ;
358             $this->list_fields =& $loaded_defs[$this->object_name]['list_fields'];
359             $this->required_fields =& $loaded_defs[$this->object_name]['required_fields'];
360             $this->field_name_map =& $loaded_defs[$this->object_name]['field_name_map'];
361             $this->field_defs =& $loaded_defs[$this->object_name]['field_defs'];
362             $this->added_custom_field_defs = true;
363
364             if(!isset($this->custom_fields) &&
365                 empty($this->disable_custom_fields))
366             {
367                 $this->setupCustomFields($this->module_dir, false);
368             }
369             if(!empty($dictionary[$this->object_name]['optimistic_locking']))
370             {
371                 $this->optimistic_lock=true;
372             }
373         }
374
375         if($this->bean_implements('ACL') && !empty($GLOBALS['current_user'])){
376             $this->acl_fields = (isset($dictionary[$this->object_name]['acl_fields']) && $dictionary[$this->object_name]['acl_fields'] === false)?false:true;
377         }
378         $this->populateDefaultValues();
379     }
380
381
382     /**
383      * Returns the object name. If object_name is not set, table_name is returned.
384      *
385      * All implementing classes must set a value for the object_name variable.
386      *
387      * @param array $arr row of data fetched from the database.
388      * @return  nothing
389      *
390      */
391     function getObjectName()
392     {
393         if ($this->object_name)
394             return $this->object_name;
395
396         // This is a quick way out. The generated metadata files have the table name
397         // as the key. The correct way to do this is to override this function
398         // in bean and return the object name. That requires changing all the beans
399         // as well as put the object name in the generator.
400         return $this->table_name;
401     }
402
403     /**
404      * Returns a list of fields with their definitions that have the audited property set to true.
405      * Before calling this function, check whether audit has been enabled for the table/module or not.
406      * You would set the audit flag in the implemting module's vardef file.
407      *
408      * @return array
409      * @see is_AuditEnabled
410      *
411      * Internal function, do not override.
412      */
413     function getAuditEnabledFieldDefinitions()
414     {
415         $aclcheck = $this->bean_implements('ACL');
416         $is_owner = $this->isOwner($GLOBALS['current_user']->id);
417         if (!isset($this->audit_enabled_fields))
418         {
419
420             $this->audit_enabled_fields=array();
421             foreach ($this->field_defs as $field => $properties)
422             {
423
424                 if (
425                 (
426                 !empty($properties['Audited']) || !empty($properties['audited']))
427                 )
428                 {
429
430                     $this->audit_enabled_fields[$field]=$properties;
431                 }
432             }
433
434         }
435         return $this->audit_enabled_fields;
436     }
437
438     /**
439      * Return true if auditing is enabled for this object
440      * You would set the audit flag in the implemting module's vardef file.
441      *
442      * @return boolean
443      *
444      * Internal function, do not override.
445      */
446     function is_AuditEnabled()
447     {
448         global $dictionary;
449         if (isset($dictionary[$this->getObjectName()]['audited']))
450         {
451             return $dictionary[$this->getObjectName()]['audited'];
452         }
453         else
454         {
455             return false;
456         }
457     }
458
459
460
461     /**
462      * Returns the name of the audit table.
463      * Audit table's name is based on implementing class' table name.
464      *
465      * @return String Audit table name.
466      *
467      * Internal function, do not override.
468      */
469     function get_audit_table_name()
470     {
471         return $this->getTableName().'_audit';
472     }
473
474     /**
475      * Returns the name of the custom table.
476      * Custom table's name is based on implementing class' table name.
477      *
478      * @return String Custom table name.
479      *
480      * Internal function, do not override.
481      */
482     public function get_custom_table_name()
483     {
484         return $this->getTableName().'_cstm';
485     }
486
487     /**
488      * If auditing is enabled, create the audit table.
489      *
490      * Function is used by the install scripts and a repair utility in the admin panel.
491      *
492      * Internal function, do not override.
493      */
494     function create_audit_table()
495     {
496         global $dictionary;
497         $table_name=$this->get_audit_table_name();
498
499         require('metadata/audit_templateMetaData.php');
500
501         // Bug: 52583 Need ability to customize template for audit tables
502         $custom = 'custom/metadata/audit_templateMetaData_' . $this->getTableName() . '.php';
503         if (file_exists($custom))
504         {
505             require($custom);
506         }
507
508         $fieldDefs = $dictionary['audit']['fields'];
509         $indices = $dictionary['audit']['indices'];
510
511         // Renaming template indexes to fit the particular audit table (removed the brittle hard coding)
512         foreach($indices as $nr => $properties){
513             $indices[$nr]['name'] = 'idx_' . strtolower($this->getTableName()) . '_' . $properties['name'];
514         }
515
516         $engine = null;
517         if(isset($dictionary['audit']['engine'])) {
518             $engine = $dictionary['audit']['engine'];
519         } else if(isset($dictionary[$this->getObjectName()]['engine'])) {
520             $engine = $dictionary[$this->getObjectName()]['engine'];
521         }
522
523         $this->db->createTableParams($table_name, $fieldDefs, $indices, $engine);
524     }
525
526     /**
527      * Returns the implementing class' table name.
528      *
529      * All implementing classes set a value for the table_name variable. This value is returned as the
530      * table name. If not set, table name is extracted from the implementing module's vardef.
531      *
532      * @return String Table name.
533      *
534      * Internal function, do not override.
535      */
536     public function getTableName()
537     {
538         if(isset($this->table_name))
539         {
540             return $this->table_name;
541         }
542         global $dictionary;
543         return $dictionary[$this->getObjectName()]['table'];
544     }
545
546     /**
547      * Returns field definitions for the implementing module.
548      *
549      * The definitions were loaded in the constructor.
550      *
551      * @return Array Field definitions.
552      *
553      * Internal function, do not override.
554      */
555     function getFieldDefinitions()
556     {
557         return $this->field_defs;
558     }
559
560     /**
561      * Returns index definitions for the implementing module.
562      *
563      * The definitions were loaded in the constructor.
564      *
565      * @return Array Index definitions.
566      *
567      * Internal function, do not override.
568      */
569     function getIndices()
570     {
571         global $dictionary;
572         if(isset($dictionary[$this->getObjectName()]['indices']))
573         {
574             return $dictionary[$this->getObjectName()]['indices'];
575         }
576         return array();
577     }
578
579     /**
580      * Returns field definition for the requested field name.
581      *
582      * The definitions were loaded in the constructor.
583      *
584      * @param string field name,
585      * @return Array Field properties or boolean false if the field doesn't exist
586      *
587      * Internal function, do not override.
588      */
589     function getFieldDefinition($name)
590     {
591         if ( !isset($this->field_defs[$name]) )
592             return false;
593
594         return $this->field_defs[$name];
595     }
596
597     /**
598      * Returnss  definition for the id field name.
599      *
600      * The definitions were loaded in the constructor.
601      *
602      * @return Array Field properties.
603      *
604      * Internal function, do not override.
605      */
606     function getPrimaryFieldDefinition()
607     {
608         $def = $this->getFieldDefinition("id");
609         if(empty($def)) {
610             $def = $this->getFieldDefinition(0);
611         }
612         if (empty($def)) {
613             $defs = $this->field_defs;
614             reset($defs);
615             $def = current($defs);
616         }
617         return $def;
618     }
619     /**
620      * Returns the value for the requested field.
621      *
622      * When a row of data is fetched using the bean, all fields are created as variables in the context
623      * of the bean and then fetched values are set in these variables.
624      *
625      * @param string field name,
626      * @return varies Field value.
627      *
628      * Internal function, do not override.
629      */
630     function getFieldValue($name)
631     {
632         if (!isset($this->$name)){
633             return FALSE;
634         }
635         if($this->$name === TRUE){
636             return 1;
637         }
638         if($this->$name === FALSE){
639             return 0;
640         }
641         return $this->$name;
642     }
643
644     /**
645      * Basically undoes the effects of SugarBean::populateDefaultValues(); this method is best called right after object
646      * initialization.
647      */
648     public function unPopulateDefaultValues()
649     {
650         if ( !is_array($this->field_defs) )
651             return;
652
653         foreach ($this->field_defs as $field => $value) {
654                     if( !empty($this->$field)
655                   && ((isset($value['default']) && $this->$field == $value['default']) || (!empty($value['display_default']) && $this->$field == $value['display_default']))
656                     ) {
657                 $this->$field = null;
658                 continue;
659             }
660             if(!empty($this->$field) && !empty($value['display_default']) && in_array($value['type'], array('date', 'datetime', 'datetimecombo')) &&
661             $this->$field == $this->parseDateDefault($value['display_default'], ($value['type'] != 'date'))) {
662                 $this->$field = null;
663             }
664         }
665     }
666
667     /**
668      * Create date string from default value
669      * like '+1 month'
670      * @param string $value
671      * @param bool $time Should be expect time set too?
672      * @return string
673      */
674     protected function parseDateDefault($value, $time = false)
675     {
676         global $timedate;
677         if($time) {
678             $dtAry = explode('&', $value, 2);
679             $dateValue = $timedate->getNow(true)->modify($dtAry[0]);
680             if(!empty($dtAry[1])) {
681                 $timeValue = $timedate->fromString($dtAry[1]);
682                 $dateValue->setTime($timeValue->hour, $timeValue->min, $timeValue->sec);
683             }
684             return $timedate->asUser($dateValue);
685         } else {
686             return $timedate->asUserDate($timedate->getNow(true)->modify($value));
687         }
688     }
689
690     function populateDefaultValues($force=false){
691         if ( !is_array($this->field_defs) )
692             return;
693         foreach($this->field_defs as $field=>$value){
694             if((isset($value['default']) || !empty($value['display_default'])) && ($force || empty($this->$field))){
695                 $type = $value['type'];
696
697                 switch($type){
698                     case 'date':
699                         if(!empty($value['display_default'])){
700                             $this->$field = $this->parseDateDefault($value['display_default']);
701                         }
702                         break;
703                    case 'datetime':
704                    case 'datetimecombo':
705                         if(!empty($value['display_default'])){
706                             $this->$field = $this->parseDateDefault($value['display_default'], true);
707                         }
708                         break;
709                     case 'multienum':
710                         if(empty($value['default']) && !empty($value['display_default']))
711                             $this->$field = $value['display_default'];
712                         else
713                             $this->$field = $value['default'];
714                         break;
715                     case 'bool':
716                         if(isset($this->$field)){
717                                 break;
718                         }
719                     default:
720                         if ( isset($value['default']) && $value['default'] !== '' ) {
721                             $this->$field = htmlentities($value['default'], ENT_QUOTES, 'UTF-8');
722                         } else {
723                             $this->$field = '';
724                         }
725                 } //switch
726             }
727         } //foreach
728     }
729
730
731     /**
732      * Removes relationship metadata cache.
733      *
734      * Every module that has relationships defined with other modules, has this meta data cached.  The cache is
735      * stores in 2 locations: relationships table and file system. This method clears the cache from both locations.
736      *
737      * @param string $key  module whose meta cache is to be cleared.
738      * @param string $db database handle.
739      * @param string $tablename table name
740      * @param string $dictionary vardef for the module
741      * @param string $module_dir name of subdirectory where module is installed.
742      *
743      * @return Nothing
744      * @static
745      *
746      * Internal function, do not override.
747      */
748     function removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir)
749     {
750         //load the module dictionary if not supplied.
751         if ((!isset($dictionary) or empty($dictionary)) && !empty($module_dir))
752         {
753             $filename='modules/'. $module_dir . '/vardefs.php';
754             if(file_exists($filename))
755             {
756                 include($filename);
757             }
758         }
759         if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
760         {
761             $GLOBALS['log']->fatal("removeRelationshipMeta: Metadata for table ".$tablename. " does not exist");
762             display_notice("meta data absent for table ".$tablename." keyed to $key ");
763         }
764         else
765         {
766             if (isset($dictionary[$key]['relationships']))
767             {
768                 $RelationshipDefs = $dictionary[$key]['relationships'];
769                 foreach ($RelationshipDefs as $rel_name)
770                 {
771                     Relationship::delete($rel_name,$db);
772                 }
773             }
774         }
775     }
776
777
778     /**
779      * This method has been deprecated.
780      *
781     * @see removeRelationshipMeta()
782      * @deprecated 4.5.1 - Nov 14, 2006
783      * @static
784     */
785     function remove_relationship_meta($key,$db,$log,$tablename,$dictionary,$module_dir)
786     {
787         SugarBean::removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
788     }
789
790
791     /**
792      * Populates the relationship meta for a module.
793      *
794      * It is called during setup/install. It is used statically to create relationship meta data for many-to-many tables.
795      *
796      *  @param string $key name of the object.
797      *  @param object $db database handle.
798      *  @param string $tablename table, meta data is being populated for.
799      *  @param array dictionary vardef dictionary for the object.     *
800      *  @param string module_dir name of subdirectory where module is installed.
801      *  @param boolean $iscustom Optional,set to true if module is installed in a custom directory. Default value is false.
802      *  @static
803      *
804      *  Internal function, do not override.
805      */
806     function createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir,$iscustom=false)
807     {
808         //load the module dictionary if not supplied.
809         if (empty($dictionary) && !empty($module_dir))
810         {
811             if($iscustom)
812             {
813                 $filename='custom/modules/' . $module_dir . '/Ext/Vardefs/vardefs.ext.php';
814             }
815             else
816             {
817                 if ($key == 'User')
818                 {
819                     // a very special case for the Employees module
820                     // this must be done because the Employees/vardefs.php does an include_once on
821                     // Users/vardefs.php
822                     $filename='modules/Users/vardefs.php';
823                 }
824                 else
825                 {
826                     $filename='modules/'. $module_dir . '/vardefs.php';
827                 }
828             }
829
830             if(file_exists($filename))
831             {
832                 include($filename);
833                 // cn: bug 7679 - dictionary entries defined as $GLOBALS['name'] not found
834                 if(empty($dictionary) || !empty($GLOBALS['dictionary'][$key]))
835                 {
836                     $dictionary = $GLOBALS['dictionary'];
837                 }
838             }
839             else
840             {
841                 $GLOBALS['log']->debug("createRelationshipMeta: no metadata file found" . $filename);
842                 return;
843             }
844         }
845
846         if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
847         {
848             $GLOBALS['log']->fatal("createRelationshipMeta: Metadata for table ".$tablename. " does not exist");
849             display_notice("meta data absent for table ".$tablename." keyed to $key ");
850         }
851         else
852         {
853             if (isset($dictionary[$key]['relationships']))
854             {
855
856                 $RelationshipDefs = $dictionary[$key]['relationships'];
857
858                 $delimiter=',';
859                 global $beanList;
860                 $beanList_ucase=array_change_key_case  ( $beanList ,CASE_UPPER);
861                 foreach ($RelationshipDefs as $rel_name=>$rel_def)
862                 {
863                     if (isset($rel_def['lhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['lhs_module'])])) {
864                         $GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' lhs module is missing ' . $rel_def['lhs_module']);
865                         continue;
866                     }
867                     if (isset($rel_def['rhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['rhs_module'])])) {
868                         $GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' rhs module is missing ' . $rel_def['rhs_module']);
869                         continue;
870                     }
871
872
873                     //check whether relationship exists or not first.
874                     if (Relationship::exists($rel_name,$db))
875                     {
876                         $GLOBALS['log']->debug('Skipping, reltionship already exists '.$rel_name);
877                     }
878                     else
879                     {
880                         $seed = BeanFactory::getBean("Relationships");
881                         $keys = array_keys($seed->field_defs);
882                         $toInsert = array();
883                         foreach($keys as $key)
884                         {
885                             if ($key == "id")
886                             {
887                                 $toInsert[$key] = create_guid();
888                             }
889                             else if ($key == "relationship_name")
890                             {
891                                 $toInsert[$key] = $rel_name;
892                             }
893                             else if (isset($rel_def[$key]))
894                             {
895                                 $toInsert[$key] = $rel_def[$key];
896                             }
897                             //todo specify defaults if meta not defined.
898                         }
899
900
901                         $column_list = implode(",", array_keys($toInsert));
902                         $value_list = "'" . implode("','", array_values($toInsert)) . "'";
903
904                         //create the record. todo add error check.
905                         $insert_string = "INSERT into relationships (" .$column_list. ") values (".$value_list.")";
906                         $db->query($insert_string, true);
907                     }
908                 }
909             }
910             else
911             {
912                 //todo
913                 //log informational message stating no relationships meta was set for this bean.
914             }
915         }
916     }
917
918     /**
919      * This method has been deprecated.
920     * @see createRelationshipMeta()
921      * @deprecated 4.5.1 - Nov 14, 2006
922      * @static
923     */
924     function create_relationship_meta($key,&$db,&$log,$tablename,$dictionary,$module_dir)
925     {
926         SugarBean::createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
927     }
928
929
930     /**
931      * Handle the following when a SugarBean object is cloned
932      *
933      * Currently all this does it unset any relationships that were created prior to cloning the object
934      *
935      * @api
936      */
937     public function __clone()
938     {
939         if(!empty($this->loaded_relationships)) {
940             foreach($this->loaded_relationships as $rel) {
941                 unset($this->$rel);
942             }
943         }
944     }
945
946
947     /**
948      * Loads the request relationship. This method should be called before performing any operations on the related data.
949      *
950      * This method searches the vardef array for the requested attribute's definition. If the attribute is of the type
951      * link then it creates a similary named variable and loads the relationship definition.
952      *
953      * @param string $rel_name  relationship/attribute name.
954      * @return nothing.
955      */
956     function load_relationship($rel_name)
957     {
958         $GLOBALS['log']->debug("SugarBean[{$this->object_name}].load_relationships, Loading relationship (".$rel_name.").");
959
960         if (empty($rel_name))
961         {
962             $GLOBALS['log']->error("SugarBean.load_relationships, Null relationship name passed.");
963             return false;
964         }
965         $fieldDefs = $this->getFieldDefinitions();
966
967         //find all definitions of type link.
968         if (!empty($fieldDefs[$rel_name]))
969         {
970             //initialize a variable of type Link
971             require_once('data/Link2.php');
972             $class = load_link_class($fieldDefs[$rel_name]);
973             if (isset($this->$rel_name) && $this->$rel_name instanceof $class) {
974                     return true;
975             }
976             //if rel_name is provided, search the fieldef array keys by name.
977             if (isset($fieldDefs[$rel_name]['type']) && $fieldDefs[$rel_name]['type'] == 'link')
978             {
979                 if ($class == "Link2")
980                     $this->$rel_name = new $class($rel_name, $this);
981                 else
982                     $this->$rel_name = new $class($fieldDefs[$rel_name]['relationship'], $this, $fieldDefs[$rel_name]);
983
984                 if (empty($this->$rel_name) ||
985                         (method_exists($this->$rel_name, "loadedSuccesfully") && !$this->$rel_name->loadedSuccesfully()))
986                 {
987                     unset($this->$rel_name);
988                     return false;
989                 }
990                 // keep track of the loaded relationships
991                 $this->loaded_relationships[] = $rel_name;
992                 return true;
993             }
994         }
995         $GLOBALS['log']->debug("SugarBean.load_relationships, Error Loading relationship (".$rel_name.")");
996         return false;
997     }
998
999     /**
1000      * Loads all attributes of type link.
1001      *
1002      * DO NOT CALL THIS FUNCTION IF YOU CAN AVOID IT. Please use load_relationship directly instead.
1003      *
1004      * Method searches the implmenting module's vardef file for attributes of type link, and for each attribute
1005      * create a similary named variable and load the relationship definition.
1006      *
1007      * @return Nothing
1008      *
1009      * Internal function, do not override.
1010      */
1011     function load_relationships()
1012     {
1013         $GLOBALS['log']->debug("SugarBean.load_relationships, Loading all relationships of type link.");
1014         $linked_fields=$this->get_linked_fields();
1015         foreach($linked_fields as $name=>$properties)
1016         {
1017             $this->load_relationship($name);
1018         }
1019     }
1020
1021     /**
1022      * Returns an array of beans of related data.
1023      *
1024      * For instance, if an account is related to 10 contacts , this function will return an array of contacts beans (10)
1025      * with each bean representing a contact record.
1026      * Method will load the relationship if not done so already.
1027      *
1028      * @param string $field_name relationship to be loaded.
1029      * @param string $bean name  class name of the related bean.
1030      * @param array $sort_array optional, unused
1031      * @param int $begin_index Optional, default 0, unused.
1032      * @param int $end_index Optional, default -1
1033      * @param int $deleted Optional, Default 0, 0  adds deleted=0 filter, 1  adds deleted=1 filter.
1034      * @param string $optional_where, Optional, default empty.
1035      *
1036      * Internal function, do not override.
1037      */
1038     function get_linked_beans($field_name,$bean_name, $sort_array = array(), $begin_index = 0, $end_index = -1,
1039                               $deleted=0, $optional_where="")
1040     {
1041         //if bean_name is Case then use aCase
1042         if($bean_name=="Case")
1043             $bean_name = "aCase";
1044
1045         if($this->load_relationship($field_name)) {
1046             if ($this->$field_name instanceof Link) {
1047                 // some classes are still based on Link, e.g. TeamSetLink
1048                 return array_values($this->$field_name->getBeans(new $bean_name(), $sort_array, $begin_index, $end_index, $deleted, $optional_where));
1049             } else {
1050                 // Link2 style
1051                 if ($end_index != -1 || !empty($deleted) || !empty($optional_where))
1052                     return array_values($this->$field_name->getBeans(array(
1053                         'where' => $optional_where,
1054                         'deleted' => $deleted,
1055                         'limit' => ($end_index - $begin_index)
1056                     )));
1057                 else
1058                     return array_values($this->$field_name->getBeans());
1059             }
1060         }
1061         else
1062             return array();
1063     }
1064
1065     /**
1066      * Returns an array of fields that are of type link.
1067      *
1068      * @return array List of fields.
1069      *
1070      * Internal function, do not override.
1071      */
1072     function get_linked_fields()
1073     {
1074
1075         $linked_fields=array();
1076
1077  //     require_once('data/Link.php');
1078
1079         $fieldDefs = $this->getFieldDefinitions();
1080
1081         //find all definitions of type link.
1082         if (!empty($fieldDefs))
1083         {
1084             foreach ($fieldDefs as $name=>$properties)
1085             {
1086                 if (array_search('link',$properties) === 'type')
1087                 {
1088                     $linked_fields[$name]=$properties;
1089                 }
1090             }
1091         }
1092
1093         return $linked_fields;
1094     }
1095
1096     /**
1097      * Returns an array of fields that are able to be Imported into
1098      * i.e. 'importable' not set to 'false'
1099      *
1100      * @return array List of fields.
1101      *
1102      * Internal function, do not override.
1103      */
1104     function get_importable_fields()
1105     {
1106         $importableFields = array();
1107
1108         $fieldDefs= $this->getFieldDefinitions();
1109
1110         if (!empty($fieldDefs)) {
1111             foreach ($fieldDefs as $key=>$value_array) {
1112                 if ( (isset($value_array['importable'])
1113                         && (is_string($value_array['importable']) && $value_array['importable'] == 'false'
1114                             || is_bool($value_array['importable']) && $value_array['importable'] == false))
1115                     || (isset($value_array['type']) && $value_array['type'] == 'link')
1116                     || (isset($value_array['auto_increment'])
1117                         && ($value_array['type'] == true || $value_array['type'] == 'true')) ) {
1118                     // only allow import if we force it
1119                     if (isset($value_array['importable'])
1120                         && (is_string($value_array['importable']) && $value_array['importable'] == 'true'
1121                            || is_bool($value_array['importable']) && $value_array['importable'] == true)) {
1122                         $importableFields[$key]=$value_array;
1123                     }
1124                 }
1125                 else {
1126
1127                     //Expose the cooresponding id field of a relate field if it is only defined as a link so that users can relate records by id during import
1128                     if( isset($value_array['type']) && ($value_array['type'] == 'relate') && isset($value_array['id_name']) )
1129                     {
1130                         $idField = $value_array['id_name'];
1131                         if( isset($fieldDefs[$idField]) && isset($fieldDefs[$idField]['type'] ) && $fieldDefs[$idField]['type'] == 'link' )
1132                         {
1133                             $tmpFieldDefs = $fieldDefs[$idField];
1134                             $tmpFieldDefs['vname'] = translate($value_array['vname'], $this->module_dir) . " " . $GLOBALS['app_strings']['LBL_ID'];
1135                             $importableFields[$idField]=$tmpFieldDefs;
1136                         }
1137                     }
1138
1139                     $importableFields[$key]=$value_array;
1140                 }
1141             }
1142         }
1143
1144         return $importableFields;
1145     }
1146
1147     /**
1148      * Returns an array of fields that are of type relate.
1149      *
1150      * @return array List of fields.
1151      *
1152      * Internal function, do not override.
1153      */
1154     function get_related_fields()
1155     {
1156
1157         $related_fields=array();
1158
1159 //      require_once('data/Link.php');
1160
1161         $fieldDefs = $this->getFieldDefinitions();
1162
1163         //find all definitions of type link.
1164         if (!empty($fieldDefs))
1165         {
1166             foreach ($fieldDefs as $name=>$properties)
1167             {
1168                 if (array_search('relate',$properties) === 'type')
1169                 {
1170                     $related_fields[$name]=$properties;
1171                 }
1172             }
1173         }
1174
1175         return $related_fields;
1176     }
1177
1178     /**
1179      * Returns an array of fields that are required for import
1180      *
1181      * @return array
1182      */
1183     function get_import_required_fields()
1184     {
1185         $importable_fields = $this->get_importable_fields();
1186         $required_fields   = array();
1187
1188         foreach ( $importable_fields as $name => $properties ) {
1189             if ( isset($properties['importable']) && is_string($properties['importable']) && $properties['importable'] == 'required' ) {
1190                 $required_fields[$name] = $properties;
1191             }
1192         }
1193
1194         return $required_fields;
1195     }
1196
1197     /**
1198      * Iterates through all the relationships and deletes all records for reach relationship.
1199      *
1200      * @param string $id Primary key value of the parent reocrd
1201      */
1202     function delete_linked($id)
1203     {
1204         $linked_fields=$this->get_linked_fields();
1205         foreach ($linked_fields as $name => $value)
1206         {
1207             if ($this->load_relationship($name))
1208             {
1209                 $this->$name->delete($id);
1210             }
1211             else
1212             {
1213                 $GLOBALS['log']->fatal("error loading relationship $name");
1214             }
1215         }
1216     }
1217
1218     /**
1219      * Creates tables for the module implementing the class.
1220      * If you override this function make sure that your code can handles table creation.
1221      *
1222      */
1223     function create_tables()
1224     {
1225         global $dictionary;
1226
1227         $key = $this->getObjectName();
1228         if (!array_key_exists($key, $dictionary))
1229         {
1230             $GLOBALS['log']->fatal("create_tables: Metadata for table ".$this->table_name. " does not exist");
1231             display_notice("meta data absent for table ".$this->table_name." keyed to $key ");
1232         }
1233         else
1234         {
1235             if(!$this->db->tableExists($this->table_name))
1236             {
1237                 $this->db->createTable($this);
1238                     if($this->bean_implements('ACL')){
1239                         if(!empty($this->acltype)){
1240                             ACLAction::addActions($this->getACLCategory(), $this->acltype);
1241                         }else{
1242                             ACLAction::addActions($this->getACLCategory());
1243                         }
1244                     }
1245             }
1246             else
1247             {
1248                 echo "Table already exists : $this->table_name<br>";
1249             }
1250             if($this->is_AuditEnabled()){
1251                     if (!$this->db->tableExists($this->get_audit_table_name())) {
1252                         $this->create_audit_table();
1253                     }
1254             }
1255
1256         }
1257     }
1258
1259     /**
1260      * Delete the primary table for the module implementing the class.
1261      * If custom fields were added to this table/module, the custom table will be removed too, along with the cache
1262      * entries that define the custom fields.
1263      *
1264      */
1265     function drop_tables()
1266     {
1267         global $dictionary;
1268         $key = $this->getObjectName();
1269         if (!array_key_exists($key, $dictionary))
1270         {
1271             $GLOBALS['log']->fatal("drop_tables: Metadata for table ".$this->table_name. " does not exist");
1272             echo "meta data absent for table ".$this->table_name."<br>\n";
1273         } else {
1274             if(empty($this->table_name))return;
1275             if ($this->db->tableExists($this->table_name))
1276
1277                 $this->db->dropTable($this);
1278             if ($this->db->tableExists($this->table_name. '_cstm'))
1279             {
1280                 $this->db->dropTableName($this->table_name. '_cstm');
1281                 DynamicField::deleteCache();
1282             }
1283             if ($this->db->tableExists($this->get_audit_table_name())) {
1284                 $this->db->dropTableName($this->get_audit_table_name());
1285             }
1286
1287
1288         }
1289     }
1290
1291
1292     /**
1293      * Loads the definition of custom fields defined for the module.
1294      * Local file system cache is created as needed.
1295      *
1296      * @param string $module_name setting up custom fields for this module.
1297      * @param boolean $clean_load Optional, default true, rebuilds the cache if set to true.
1298      */
1299     function setupCustomFields($module_name, $clean_load=true)
1300     {
1301         $this->custom_fields = new DynamicField($module_name);
1302         $this->custom_fields->setup($this);
1303
1304     }
1305
1306     /**
1307     * Cleans char, varchar, text, etc. fields of XSS type materials
1308     */
1309     function cleanBean() {
1310         foreach($this->field_defs as $key => $def) {
1311
1312             if (isset($def['type'])) {
1313                 $type=$def['type'];
1314             }
1315             if(isset($def['dbType']))
1316                 $type .= $def['dbType'];
1317
1318             if($def['type'] == 'html' || $def['type'] == 'longhtml') {
1319                 $this->$key = SugarCleaner::cleanHtml($this->$key, true);
1320             } elseif((strpos($type, 'char') !== false ||
1321                 strpos($type, 'text') !== false ||
1322                 $type == 'enum') &&
1323                 !empty($this->$key)
1324             ) {
1325                 $this->$key = SugarCleaner::cleanHtml($this->$key);
1326             }
1327         }
1328     }
1329
1330     /**
1331     * Implements a generic insert and update logic for any SugarBean
1332     * This method only works for subclasses that implement the same variable names.
1333     * This method uses the presence of an id field that is not null to signify and update.
1334     * The id field should not be set otherwise.
1335     *
1336     * @param boolean $check_notify Optional, default false, if set to true assignee of the record is notified via email.
1337     * @todo Add support for field type validation and encoding of parameters.
1338     */
1339     function save($check_notify = FALSE)
1340     {
1341         $this->in_save = true;
1342         // cn: SECURITY - strip XSS potential vectors
1343         $this->cleanBean();
1344         // This is used so custom/3rd-party code can be upgraded with fewer issues, this will be removed in a future release
1345         $this->fixUpFormatting();
1346         global $timedate;
1347         global $current_user, $action;
1348
1349         $isUpdate = true;
1350         if(empty($this->id))
1351         {
1352             $isUpdate = false;
1353         }
1354
1355                 if ( $this->new_with_id == true )
1356                 {
1357                         $isUpdate = false;
1358                 }
1359                 if(empty($this->date_modified) || $this->update_date_modified)
1360                 {
1361                         $this->date_modified = $GLOBALS['timedate']->nowDb();
1362                 }
1363
1364         $this->_checkOptimisticLocking($action, $isUpdate);
1365
1366         if(!empty($this->modified_by_name)) $this->old_modified_by_name = $this->modified_by_name;
1367         if($this->update_modified_by)
1368         {
1369             $this->modified_user_id = 1;
1370
1371             if (!empty($current_user))
1372             {
1373                 $this->modified_user_id = $current_user->id;
1374                 $this->modified_by_name = $current_user->user_name;
1375             }
1376         }
1377         if ($this->deleted != 1)
1378             $this->deleted = 0;
1379         if(!$isUpdate)
1380         {
1381             if (empty($this->date_entered))
1382             {
1383                 $this->date_entered = $this->date_modified;
1384             }
1385             if($this->set_created_by == true)
1386             {
1387                 // created by should always be this user
1388                 $this->created_by = (isset($current_user)) ? $current_user->id : "";
1389             }
1390             if( $this->new_with_id == false)
1391             {
1392                 $this->id = create_guid();
1393             }
1394         }
1395
1396
1397
1398         require_once("data/BeanFactory.php");
1399         BeanFactory::registerBean($this->module_name, $this);
1400
1401         if (empty($GLOBALS['updating_relationships']) && empty($GLOBALS['saving_relationships']) && empty ($GLOBALS['resavingRelatedBeans']))
1402         {
1403             $GLOBALS['saving_relationships'] = true;
1404         // let subclasses save related field changes
1405             $this->save_relationship_changes($isUpdate);
1406             $GLOBALS['saving_relationships'] = false;
1407         }
1408         if($isUpdate && !$this->update_date_entered)
1409         {
1410             unset($this->date_entered);
1411         }
1412         // call the custom business logic
1413         $custom_logic_arguments['check_notify'] = $check_notify;
1414
1415
1416         $this->call_custom_logic("before_save", $custom_logic_arguments);
1417         unset($custom_logic_arguments);
1418
1419         if(isset($this->custom_fields))
1420         {
1421             $this->custom_fields->bean = $this;
1422             $this->custom_fields->save($isUpdate);
1423         }
1424
1425         // use the db independent query generator
1426         $this->preprocess_fields_on_save();
1427
1428         //construct the SQL to create the audit record if auditing is enabled.
1429         $auditDataChanges=array();
1430         if ($this->is_AuditEnabled()) {
1431             if ($isUpdate && !isset($this->fetched_row)) {
1432                 $GLOBALS['log']->debug('Auditing: Retrieve was not called, audit record will not be created.');
1433             } else {
1434                 $auditDataChanges=$this->db->getAuditDataChanges($this);
1435             }
1436         }
1437
1438         $this->_sendNotifications($check_notify);
1439
1440         if ($isUpdate) {
1441             $this->db->update($this);
1442         } else {
1443             $this->db->insert($this);
1444         }
1445
1446         if (!empty($auditDataChanges) && is_array($auditDataChanges))
1447         {
1448             foreach ($auditDataChanges as $change)
1449             {
1450                 $this->db->save_audit_records($this,$change);
1451             }
1452         }
1453
1454
1455         if (empty($GLOBALS['resavingRelatedBeans'])){
1456             SugarRelationship::resaveRelatedBeans();
1457         }
1458
1459         // populate fetched row with current bean values
1460         foreach ($auditDataChanges as $change) {
1461             $this->fetched_row[$change['field_name']] = $change['after'];
1462         }
1463
1464
1465         //If we aren't in setup mode and we have a current user and module, then we track
1466         if(isset($GLOBALS['current_user']) && isset($this->module_dir))
1467         {
1468             $this->track_view($current_user->id, $this->module_dir, 'save');
1469         }
1470
1471         $this->call_custom_logic('after_save', '');
1472
1473         //Now that the record has been saved, we don't want to insert again on further saves
1474         $this->new_with_id = false;
1475         $this->in_save = false;
1476         return $this->id;
1477     }
1478
1479
1480     /**
1481      * Performs a check if the record has been modified since the specified date
1482      *
1483      * @param date $date Datetime for verification
1484      * @param string $modified_user_id User modified by
1485      */
1486     function has_been_modified_since($date, $modified_user_id)
1487     {
1488         global $current_user;
1489         $date = $this->db->convert($this->db->quoted($date), 'datetime');
1490         if (isset($current_user))
1491         {
1492             $query = "SELECT date_modified FROM $this->table_name WHERE id='$this->id' AND modified_user_id != '$current_user->id'
1493                 AND (modified_user_id != '$modified_user_id' OR date_modified > $date)";
1494             $result = $this->db->query($query);
1495
1496             if($this->db->fetchByAssoc($result))
1497             {
1498                 return true;
1499             }
1500         }
1501         return false;
1502     }
1503
1504     /**
1505     * Determines which users receive a notification
1506     */
1507     function get_notification_recipients() {
1508         $notify_user = new User();
1509         $notify_user->retrieve($this->assigned_user_id);
1510         $this->new_assigned_user_name = $notify_user->full_name;
1511
1512         $GLOBALS['log']->info("Notifications: recipient is $this->new_assigned_user_name");
1513
1514         $user_list = array($notify_user);
1515         return $user_list;
1516         /*
1517         //send notifications to followers, but ensure to not query for the assigned_user.
1518         return SugarFollowing::getFollowers($this, $notify_user);
1519         */
1520     }
1521
1522     /**
1523     * Handles sending out email notifications when items are first assigned to users
1524     *
1525     * @param string $notify_user user to notify
1526     * @param string $admin the admin user that sends out the notification
1527     */
1528     function send_assignment_notifications($notify_user, $admin)
1529     {
1530         global $current_user;
1531
1532         if(($this->object_name == 'Meeting' || $this->object_name == 'Call') || $notify_user->receive_notifications)
1533         {
1534             $sendToEmail = $notify_user->emailAddress->getPrimaryAddress($notify_user);
1535             $sendEmail = TRUE;
1536             if(empty($sendToEmail)) {
1537                 $GLOBALS['log']->warn("Notifications: no e-mail address set for user {$notify_user->user_name}, cancelling send");
1538                 $sendEmail = FALSE;
1539             }
1540
1541             $notify_mail = $this->create_notification_email($notify_user);
1542             $notify_mail->setMailerForSystem();
1543
1544             if(empty($admin->settings['notify_send_from_assigning_user'])) {
1545                 $notify_mail->From = $admin->settings['notify_fromaddress'];
1546                 $notify_mail->FromName = (empty($admin->settings['notify_fromname'])) ? "" : $admin->settings['notify_fromname'];
1547             } else {
1548                 // Send notifications from the current user's e-mail (if set)
1549                 $fromAddress = $current_user->emailAddress->getReplyToAddress($current_user);
1550                 $fromAddress = !empty($fromAddress) ? $fromAddress : $admin->settings['notify_fromaddress'];
1551                 $notify_mail->From = $fromAddress;
1552                 //Use the users full name is available otherwise default to system name
1553                 $from_name = !empty($admin->settings['notify_fromname']) ? $admin->settings['notify_fromname'] : "";
1554                 $from_name = !empty($current_user->full_name) ? $current_user->full_name : $from_name;
1555                 $notify_mail->FromName = $from_name;
1556             }
1557
1558            $oe = new OutboundEmail();
1559             $oe = $oe->getUserMailerSettings($current_user);
1560             //only send if smtp server is defined
1561             if($sendEmail){
1562                 $smtpVerified = false;
1563
1564                 //first check the user settings
1565                 if(!empty($oe->mail_smtpserver)){
1566                     $smtpVerified = true;
1567                 }
1568
1569                 //if still not verified, check against the system settings
1570                 if (!$smtpVerified){
1571                     $oe = $oe->getSystemMailerSettings();
1572                     if(!empty($oe->mail_smtpserver)){
1573                         $smtpVerified = true;
1574                     }
1575                 }
1576                 //if smtp was not verified against user or system, then do not send out email
1577                 if (!$smtpVerified){
1578                     $GLOBALS['log']->fatal("Notifications: error sending e-mail, smtp server was not found ");
1579                     //break out
1580                     return;
1581                 }
1582
1583                 if(!$notify_mail->Send()) {
1584                     $GLOBALS['log']->fatal("Notifications: error sending e-mail (method: {$notify_mail->Mailer}), (error: {$notify_mail->ErrorInfo})");
1585                 }else{
1586                     $GLOBALS['log']->info("Notifications: e-mail successfully sent");
1587                 }
1588             }
1589
1590         }
1591     }
1592
1593     /**
1594     * This function handles create the email notifications email.
1595     * @param string $notify_user the user to send the notification email to
1596     */
1597     function create_notification_email($notify_user) {
1598         global $sugar_version;
1599         global $sugar_config;
1600         global $app_list_strings;
1601         global $current_user;
1602         global $locale;
1603         global $beanList;
1604         $OBCharset = $locale->getPrecedentPreference('default_email_charset');
1605
1606
1607         require_once("include/SugarPHPMailer.php");
1608
1609         $notify_address = $notify_user->emailAddress->getPrimaryAddress($notify_user);
1610         $notify_name = $notify_user->full_name;
1611         $GLOBALS['log']->debug("Notifications: user has e-mail defined");
1612
1613         $notify_mail = new SugarPHPMailer();
1614         $notify_mail->AddAddress($notify_address,$locale->translateCharsetMIME(trim($notify_name), 'UTF-8', $OBCharset));
1615
1616         if(empty($_SESSION['authenticated_user_language'])) {
1617             $current_language = $sugar_config['default_language'];
1618         } else {
1619             $current_language = $_SESSION['authenticated_user_language'];
1620         }
1621         $xtpl = new XTemplate(get_notify_template_file($current_language));
1622         if($this->module_dir == "Cases") {
1623             $template_name = "Case"; //we should use Case, you can refer to the en_us.notify_template.html.
1624         }
1625         else {
1626             $template_name = $beanList[$this->module_dir]; //bug 20637, in workflow this->object_name = strange chars.
1627         }
1628
1629         $this->current_notify_user = $notify_user;
1630
1631         if(in_array('set_notification_body', get_class_methods($this))) {
1632             $xtpl = $this->set_notification_body($xtpl, $this);
1633         } else {
1634             $xtpl->assign("OBJECT", translate('LBL_MODULE_NAME'));
1635             $template_name = "Default";
1636         }
1637         if(!empty($_SESSION["special_notification"]) && $_SESSION["special_notification"]) {
1638             $template_name = $beanList[$this->module_dir].'Special';
1639         }
1640         if($this->special_notification) {
1641             $template_name = $beanList[$this->module_dir].'Special';
1642         }
1643         $xtpl->assign("ASSIGNED_USER", $this->new_assigned_user_name);
1644         $xtpl->assign("ASSIGNER", $current_user->name);
1645         $port = '';
1646
1647         if(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
1648             $port = $_SERVER['SERVER_PORT'];
1649         }
1650
1651         if (!isset($_SERVER['HTTP_HOST'])) {
1652             $_SERVER['HTTP_HOST'] = '';
1653         }
1654
1655         $httpHost = $_SERVER['HTTP_HOST'];
1656
1657         if($colon = strpos($httpHost, ':')) {
1658             $httpHost    = substr($httpHost, 0, $colon);
1659         }
1660
1661         $parsedSiteUrl = parse_url($sugar_config['site_url']);
1662         $host = $parsedSiteUrl['host'];
1663         if(!isset($parsedSiteUrl['port'])) {
1664             $parsedSiteUrl['port'] = 80;
1665         }
1666
1667         $port           = ($parsedSiteUrl['port'] != 80) ? ":".$parsedSiteUrl['port'] : '';
1668         $path           = !empty($parsedSiteUrl['path']) ? $parsedSiteUrl['path'] : "";
1669         $cleanUrl       = "{$parsedSiteUrl['scheme']}://{$host}{$port}{$path}";
1670
1671         $xtpl->assign("URL", $cleanUrl."/index.php?module={$this->module_dir}&action=DetailView&record={$this->id}");
1672         $xtpl->assign("SUGAR", "Sugar v{$sugar_version}");
1673         $xtpl->parse($template_name);
1674         $xtpl->parse($template_name . "_Subject");
1675
1676         $notify_mail->Body = from_html(trim($xtpl->text($template_name)));
1677         $notify_mail->Subject = from_html($xtpl->text($template_name . "_Subject"));
1678
1679         // cn: bug 8568 encode notify email in User's outbound email encoding
1680         $notify_mail->prepForOutbound();
1681
1682         return $notify_mail;
1683     }
1684
1685     /**
1686      * This function is a good location to save changes that have been made to a relationship.
1687      * This should be overridden in subclasses that have something to save.
1688      *
1689      * @param boolean $is_update    true if this save is an update.
1690      * @param array $exclude        a way to exclude relationships
1691      */
1692     public function save_relationship_changes($is_update, $exclude = array())
1693     {
1694         list($new_rel_id, $new_rel_link) = $this->set_relationship_info($exclude);
1695
1696         $new_rel_id = $this->handle_preset_relationships($new_rel_id, $new_rel_link, $exclude);
1697
1698         $this->handle_remaining_relate_fields($exclude);
1699
1700         $this->handle_request_relate($new_rel_id, $new_rel_link);
1701     }
1702
1703     /**
1704      * Look in the bean for the new relationship_id and relationship_name if $this->not_use_rel_in_req is set to true,
1705      * otherwise check the $_REQUEST param for a relate_id and relate_to field.  Once we have that make sure that it's
1706      * not excluded from the passed in array of relationships to exclude
1707      *
1708      * @param array $exclude        any relationship's to exclude
1709      * @return array                The relationship_id and relationship_name in an array
1710      */
1711     protected function set_relationship_info($exclude = array())
1712     {
1713
1714         $new_rel_id = false;
1715         $new_rel_link = false;
1716         // check incoming data
1717         if (isset($this->not_use_rel_in_req) && $this->not_use_rel_in_req == true) {
1718             // if we should use relation data from properties (for REQUEST-independent calls)
1719             $rel_id = isset($this->new_rel_id) ? $this->new_rel_id : '';
1720             $rel_link = isset($this->new_rel_relname) ? $this->new_rel_relname : '';
1721         }
1722         else
1723         {
1724             // if we should use relation data from REQUEST
1725             $rel_id = isset($_REQUEST['relate_id']) ? $_REQUEST['relate_id'] : '';
1726             $rel_link = isset($_REQUEST['relate_to']) ? $_REQUEST['relate_to'] : '';
1727         }
1728
1729         // filter relation data
1730         if ($rel_id && $rel_link && !in_array($rel_link, $exclude) && $rel_id != $this->id) {
1731             $new_rel_id = $rel_id;
1732             $new_rel_link = $rel_link;
1733             // Bug #53223 : wrong relationship from subpanel create button
1734             // if LHSModule and RHSModule are same module use left link to add new item b/s of:
1735             // $rel_id and $rel_link are not emty - request is from subpanel
1736             // $rel_link contains relationship name - checked by call load_relationship
1737             $isRelationshipLoaded = $this->load_relationship($rel_link);
1738             if ($isRelationshipLoaded && !empty($this->$rel_link) && $this->$rel_link->getRelationshipObject() && $this->$rel_link->getRelationshipObject()->getLHSModule() == $this->$rel_link->getRelationshipObject()->getRHSModule() )
1739             {
1740                 $new_rel_link = $this->$rel_link->getRelationshipObject()->getLHSLink();
1741             }
1742             else
1743             {
1744                 //Try to find the link in this bean based on the relationship
1745                 foreach ($this->field_defs as $key => $def)
1746                 {
1747                     if (isset($def['type']) && $def['type'] == 'link' && isset($def['relationship']) && $def['relationship'] == $rel_link)
1748                     {
1749                         $new_rel_link = $key;
1750                     }
1751                 }
1752             }
1753         }
1754
1755         return array($new_rel_id, $new_rel_link);
1756     }
1757
1758     /**
1759      * Handle the preset fields listed in the fixed relationship_fields array hardcoded into the OOB beans
1760      *
1761      * TODO: remove this mechanism and replace with mechanism exclusively based on the vardefs
1762      *
1763      * @api
1764      * @see save_relationship_changes
1765      * @param string|boolean $new_rel_id    String of the ID to add
1766      * @param string                        Relationship Name
1767      * @param array $exclude                any relationship's to exclude
1768      * @return string|boolean               Return the new_rel_id if it was not used.  False if it was used.
1769      */
1770     protected function handle_preset_relationships($new_rel_id, $new_rel_link, $exclude = array())
1771     {
1772         if (isset($this->relationship_fields) && is_array($this->relationship_fields)) {
1773             foreach ($this->relationship_fields as $id => $rel_name)
1774             {
1775
1776                 if (in_array($id, $exclude)) continue;
1777
1778                 if(!empty($this->$id))
1779                 {
1780                     // Bug #44930 We do not need to update main related field if it is changed from sub-panel.
1781                     if ($rel_name == $new_rel_link && $this->$id != $new_rel_id)
1782                     {
1783                         $new_rel_id = '';
1784                     }
1785                     $GLOBALS['log']->debug('save_relationship_changes(): From relationship_field array - adding a relationship record: '.$rel_name . ' = ' . $this->$id);
1786                     //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
1787                     $this->load_relationship($rel_name);
1788                     $rel_add = $this->$rel_name->add($this->$id);
1789                     // move this around to only take out the id if it was save successfully
1790                     if ($this->$id == $new_rel_id && $rel_add == true) {
1791                         $new_rel_id = false;
1792                     }
1793                 } else {
1794                     //if before value is not empty then attempt to delete relationship
1795                     if (!empty($this->rel_fields_before_value[$id])) {
1796                         $GLOBALS['log']->debug('save_relationship_changes(): From relationship_field array - attempting to remove the relationship record, using relationship attribute' . $rel_name);
1797                         $this->load_relationship($rel_name);
1798                         $this->$rel_name->delete($this->id, $this->rel_fields_before_value[$id]);
1799                     }
1800                 }
1801             }
1802         }
1803
1804         return $new_rel_id;
1805     }
1806
1807     /**
1808      * Next, we'll attempt to update all of the remaining relate fields in the vardefs that have 'save' set in their field_def
1809      * Only the 'save' fields should be saved as some vardef entries today are not for display only purposes and break the application if saved
1810      * If the vardef has entries for field <a> of type relate, where a->id_name = <b> and field <b> of type link
1811      * then we receive a value for b from the MVC in the _REQUEST, and it should be set in the bean as $this->$b
1812      *
1813      * @api
1814      * @see save_relationship_changes
1815      * @param array $exclude            any relationship's to exclude
1816      * @return array                    the list of relationships that were added or removed successfully or if they were a failure
1817      */
1818     protected function handle_remaining_relate_fields($exclude = array())
1819     {
1820
1821         $modified_relationships = array(
1822             'add' => array('success' => array(), 'failure' => array()),
1823             'remove' => array('success' => array(), 'failure' => array()),
1824         );
1825
1826         foreach ($this->field_defs as $def)
1827         {
1828             if ($def ['type'] == 'relate' && isset ($def ['id_name']) && isset ($def ['link']) && isset ($def['save'])) {
1829                 if (in_array($def['id_name'], $exclude) || in_array($def['id_name'], $this->relationship_fields))
1830                     continue; // continue to honor the exclude array and exclude any relationships that will be handled by the relationship_fields mechanism
1831
1832                 $linkField = $def ['link'];
1833                 if (isset($this->field_defs[$linkField])) {
1834                     if ($this->load_relationship($linkField)) {
1835                         $idName = $def['id_name'];
1836
1837                         if (!empty($this->rel_fields_before_value[$idName]) && empty($this->$idName)) {
1838                             //if before value is not empty then attempt to delete relationship
1839                             $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' ]]}");
1840                             $success = $this->$def ['link']->delete($this->id, $this->rel_fields_before_value[$def ['id_name']]);
1841                             // just need to make sure it's true and not an array as it's possible to return an array
1842                             if($success == true) {
1843                                 $modified_relationships['remove']['success'][] = $def['link'];
1844                             } else {
1845                                 $modified_relationships['remove']['failure'][] = $def['link'];
1846                             }
1847                             $GLOBALS['log']->debug("save_relationship_changes(): From field_defs - attempting to remove the relationship record returned " . var_export($success, true));
1848                         }
1849
1850                         if (!empty($this->$idName) && is_string($this->$idName)) {
1851                             $GLOBALS['log']->debug("save_relationship_changes(): From field_defs - attempting to add a relationship record - {$def [ 'link' ]} = {$this->$def [ 'id_name' ]}");
1852
1853                             $success = $this->$linkField->add($this->$idName);
1854
1855                             // just need to make sure it's true and not an array as it's possible to return an array
1856                             if($success == true) {
1857                                 $modified_relationships['add']['success'][] = $linkField;
1858                             } else {
1859                                 $modified_relationships['add']['failure'][] = $linkField;
1860                             }
1861
1862                             $GLOBALS['log']->debug("save_relationship_changes(): From field_defs - add a relationship record returned " . var_export($success, true));
1863                         }
1864                     } else {
1865                         $GLOBALS['log']->fatal("Failed to load relationship {$linkField} while saving {$this->module_dir}");
1866                     }
1867                 }
1868             }
1869         }
1870
1871         return $modified_relationships;
1872     }
1873
1874     /**
1875      * Finally, we update a field listed in the _REQUEST['%/relate_id']/_REQUEST['relate_to'] mechanism (if it has not already been updated)
1876      *
1877      * @api
1878      * @see save_relationship_changes
1879      * @param string|boolean $new_rel_id
1880      * @param string $new_rel_link
1881      * @return boolean
1882      */
1883     protected function handle_request_relate($new_rel_id, $new_rel_link)
1884     {
1885         if (!empty($new_rel_id)) {
1886
1887             if ($this->load_relationship($new_rel_link)) {
1888                 return $this->$new_rel_link->add($new_rel_id);
1889             } else {
1890                 $lower_link = strtolower($new_rel_link);
1891                 if ($this->load_relationship($lower_link)) {
1892                     return $this->$lower_link->add($new_rel_id);
1893
1894                 } else {
1895                     require_once('data/Link2.php');
1896                     $rel = Relationship::retrieve_by_modules($new_rel_link, $this->module_dir, $this->db, 'many-to-many');
1897
1898                     if (!empty($rel)) {
1899                         foreach ($this->field_defs as $field => $def) {
1900                             if ($def['type'] == 'link' && !empty($def['relationship']) && $def['relationship'] == $rel) {
1901                                 $this->load_relationship($field);
1902                                 return $this->$field->add($new_rel_id);
1903                             }
1904
1905                         }
1906                         //ok so we didn't find it in the field defs let's save it anyway if we have the relationshp
1907
1908                         $this->$rel = new Link2($rel, $this, array());
1909                         return $this->$rel->add($new_rel_id);
1910                     }
1911                 }
1912             }
1913         }
1914
1915         // nothing was saved so just return false;
1916         return false;
1917     }
1918
1919     /**
1920     * This function retrieves a record of the appropriate type from the DB.
1921     * It fills in all of the fields from the DB into the object it was called on.
1922     *
1923     * @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.
1924     * @return this - The object that it was called apon or null if exactly 1 record was not found.
1925     *
1926         */
1927
1928         function check_date_relationships_load()
1929         {
1930                 global $disable_date_format;
1931                 global $timedate;
1932                 if (empty($timedate))
1933                         $timedate=TimeDate::getInstance();
1934
1935                 if(empty($this->field_defs))
1936                 {
1937                         return;
1938                 }
1939                 foreach($this->field_defs as $fieldDef)
1940                 {
1941                         $field = $fieldDef['name'];
1942                         if(!isset($this->processed_dates_times[$field]))
1943                         {
1944                                 $this->processed_dates_times[$field] = '1';
1945                                 if(empty($this->$field)) continue;
1946                                 if($field == 'date_modified' || $field == 'date_entered')
1947                                 {
1948                                         $this->$field = $this->db->fromConvert($this->$field, 'datetime');
1949                                         if(empty($disable_date_format)) {
1950                                                 $this->$field = $timedate->to_display_date_time($this->$field);
1951                                         }
1952                                 }
1953                                 elseif(isset($this->field_name_map[$field]['type']))
1954                                 {
1955                                         $type = $this->field_name_map[$field]['type'];
1956
1957                                         if($type == 'relate'  && isset($this->field_name_map[$field]['custom_module']))
1958                                         {
1959                                                 $type = $this->field_name_map[$field]['type'];
1960                                         }
1961
1962                                         if($type == 'date')
1963                                         {
1964                                                 if($this->$field == '0000-00-00')
1965                                                 {
1966                                                         $this->$field = '';
1967                                                 } elseif(!empty($this->field_name_map[$field]['rel_field']))
1968                                                 {
1969                                                         $rel_field = $this->field_name_map[$field]['rel_field'];
1970
1971                                                         if(!empty($this->$rel_field))
1972                                                         {
1973                                                                 if(empty($disable_date_format)) {
1974                                                                         $mergetime = $timedate->merge_date_time($this->$field,$this->$rel_field);
1975                                                                         $this->$field = $timedate->to_display_date($mergetime);
1976                                                                         $this->$rel_field = $timedate->to_display_time($mergetime);
1977                                                                 }
1978                                                         }
1979                                                 }
1980                                                 else
1981                                                 {
1982                                                         if(empty($disable_date_format)) {
1983                                                                 $this->$field = $timedate->to_display_date($this->$field, false);
1984                                                         }
1985                                                 }
1986                                         } elseif($type == 'datetime' || $type == 'datetimecombo')
1987                                         {
1988                                                 if($this->$field == '0000-00-00 00:00:00')
1989                                                 {
1990                                                         $this->$field = '';
1991                                                 }
1992                                                 else
1993                                                 {
1994                                                         if(empty($disable_date_format)) {
1995                                                                 $this->$field = $timedate->to_display_date_time($this->$field, true, true);
1996                                                         }
1997                                                 }
1998                                         } elseif($type == 'time')
1999                                         {
2000                                                 if($this->$field == '00:00:00')
2001                                                 {
2002                                                         $this->$field = '';
2003                                                 } else
2004                                                 {
2005                                                         //$this->$field = from_db_convert($this->$field, 'time');
2006                                                         if(empty($this->field_name_map[$field]['rel_field']) && empty($disable_date_format))
2007                                                         {
2008                                                                 $this->$field = $timedate->to_display_time($this->$field,true, false);
2009                                                         }
2010                                                 }
2011                                         } elseif($type == 'encrypt' && empty($disable_date_format)){
2012                                                 $this->$field = $this->decrypt_after_retrieve($this->$field);
2013                                         }
2014                                 }
2015                         }
2016                 }
2017         }
2018
2019     /**
2020      * This function processes the fields before save.
2021      * Interal function, do not override.
2022      */
2023     function preprocess_fields_on_save()
2024     {
2025         $GLOBALS['log']->deprecated('SugarBean.php: preprocess_fields_on_save() is deprecated');
2026     }
2027
2028     /**
2029     * Removes formatting from values posted from the user interface.
2030      * It only unformats numbers.  Function relies on user/system prefernce for format strings.
2031      *
2032      * Internal Function, do not override.
2033     */
2034     function unformat_all_fields()
2035     {
2036         $GLOBALS['log']->deprecated('SugarBean.php: unformat_all_fields() is deprecated');
2037     }
2038
2039     /**
2040     * This functions adds formatting to all number fields before presenting them to user interface.
2041      *
2042      * Internal function, do not override.
2043     */
2044     function format_all_fields()
2045     {
2046         $GLOBALS['log']->deprecated('SugarBean.php: format_all_fields() is deprecated');
2047     }
2048
2049     function format_field($fieldDef)
2050         {
2051         $GLOBALS['log']->deprecated('SugarBean.php: format_field() is deprecated');
2052         }
2053
2054     /**
2055      * Function corrects any bad formatting done by 3rd party/custom code
2056      *
2057      * 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
2058      */
2059     function fixUpFormatting()
2060     {
2061         global $timedate;
2062         static $boolean_false_values = array('off', 'false', '0', 'no');
2063
2064
2065         foreach($this->field_defs as $field=>$def)
2066             {
2067             if ( !isset($this->$field) ) {
2068                 continue;
2069                 }
2070             if ( (isset($def['source'])&&$def['source']=='non-db') || $field == 'deleted' ) {
2071                 continue;
2072             }
2073             if ( isset($this->fetched_row[$field]) && $this->$field == $this->fetched_row[$field] ) {
2074                 // Don't hand out warnings because the field was untouched between retrieval and saving, most database drivers hand pretty much everything back as strings.
2075                 continue;
2076             }
2077             $reformatted = false;
2078             switch($def['type']) {
2079                 case 'datetime':
2080                 case 'datetimecombo':
2081                     if(empty($this->$field)) break;
2082                     if ($this->$field == 'NULL') {
2083                         $this->$field = '';
2084                         break;
2085                     }
2086                     if ( ! preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/',$this->$field) ) {
2087                         // This appears to be formatted in user date/time
2088                         $this->$field = $timedate->to_db($this->$field);
2089                         $reformatted = true;
2090                     }
2091                     break;
2092                 case 'date':
2093                     if(empty($this->$field)) break;
2094                     if ($this->$field == 'NULL') {
2095                         $this->$field = '';
2096                         break;
2097                     }
2098                     if ( ! preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$this->$field) ) {
2099                         // This date appears to be formatted in the user's format
2100                         $this->$field = $timedate->to_db_date($this->$field, false);
2101                         $reformatted = true;
2102                     }
2103                     break;
2104                 case 'time':
2105                     if(empty($this->$field)) break;
2106                     if ($this->$field == 'NULL') {
2107                         $this->$field = '';
2108                         break;
2109                     }
2110                     if ( preg_match('/(am|pm)/i',$this->$field) ) {
2111                         // This time appears to be formatted in the user's format
2112                         $this->$field = $timedate->fromUserTime($this->$field)->format(TimeDate::DB_TIME_FORMAT);
2113                         $reformatted = true;
2114                     }
2115                     break;
2116                 case 'double':
2117                 case 'decimal':
2118                 case 'currency':
2119                 case 'float':
2120                     if ( $this->$field === '' || $this->$field == NULL || $this->$field == 'NULL') {
2121                         continue;
2122                     }
2123                     if ( is_string($this->$field) ) {
2124                         $this->$field = (float)unformat_number($this->$field);
2125                         $reformatted = true;
2126                     }
2127                     break;
2128                case 'uint':
2129                case 'ulong':
2130                case 'long':
2131                case 'short':
2132                case 'tinyint':
2133                case 'int':
2134                     if ( $this->$field === '' || $this->$field == NULL || $this->$field == 'NULL') {
2135                         continue;
2136                     }
2137                     if ( is_string($this->$field) ) {
2138                         $this->$field = (int)unformat_number($this->$field);
2139                         $reformatted = true;
2140                     }
2141                    break;
2142                case 'bool':
2143                    if (empty($this->$field)) {
2144                        $this->$field = false;
2145                    } else if(true === $this->$field || 1 == $this->$field) {
2146                        $this->$field = true;
2147                    } else if(in_array(strval($this->$field), $boolean_false_values)) {
2148                        $this->$field = false;
2149                        $reformatted = true;
2150                    } else {
2151                        $this->$field = true;
2152                        $reformatted = true;
2153                    }
2154                    break;
2155                case 'encrypt':
2156                     $this->$field = $this->encrpyt_before_save($this->$field);
2157                     break;
2158             }
2159             if ( $reformatted ) {
2160                 $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');
2161             }
2162         }
2163
2164     }
2165
2166     /**
2167      * Function fetches a single row of data given the primary key value.
2168      *
2169      * The fetched data is then set into the bean. The function also processes the fetched data by formattig
2170      * date/time and numeric values.
2171      *
2172      * @param string $id Optional, default -1, is set to -1 id value from the bean is used, else, passed value is used
2173      * @param boolean $encode Optional, default true, encodes the values fetched from the database.
2174      * @param boolean $deleted Optional, default true, if set to false deleted filter will not be added.
2175      *
2176      * Internal function, do not override.
2177     */
2178     function retrieve($id = -1, $encode=true,$deleted=true)
2179     {
2180
2181         $custom_logic_arguments['id'] = $id;
2182         $this->call_custom_logic('before_retrieve', $custom_logic_arguments);
2183
2184         if ($id == -1)
2185         {
2186             $id = $this->id;
2187         }
2188         if(isset($this->custom_fields))
2189         {
2190             $custom_join = $this->custom_fields->getJOIN();
2191         }
2192         else
2193             $custom_join = false;
2194
2195         if($custom_join)
2196         {
2197             $query = "SELECT $this->table_name.*". $custom_join['select']. " FROM $this->table_name ";
2198         }
2199         else
2200         {
2201             $query = "SELECT $this->table_name.* FROM $this->table_name ";
2202         }
2203
2204         if($custom_join)
2205         {
2206             $query .= ' ' . $custom_join['join'];
2207         }
2208         $query .= " WHERE $this->table_name.id = ".$this->db->quoted($id);
2209         if ($deleted) $query .= " AND $this->table_name.deleted=0";
2210         $GLOBALS['log']->debug("Retrieve $this->object_name : ".$query);
2211         $result = $this->db->limitQuery($query,0,1,true, "Retrieving record by id $this->table_name:$id found ");
2212         if(empty($result))
2213         {
2214             return null;
2215         }
2216
2217         $row = $this->db->fetchByAssoc($result, $encode);
2218         if(empty($row))
2219         {
2220             return null;
2221         }
2222
2223         //make copy of the fetched row for construction of audit record and for business logic/workflow
2224         $row = $this->convertRow($row);
2225         $this->fetched_row=$row;
2226         $this->populateFromRow($row);
2227
2228         global $module, $action;
2229         //Just to get optimistic locking working for this release
2230         if($this->optimistic_lock && $module == $this->module_dir && $action =='EditView' )
2231         {
2232             $_SESSION['o_lock_id']= $id;
2233             $_SESSION['o_lock_dm']= $this->date_modified;
2234             $_SESSION['o_lock_on'] = $this->object_name;
2235         }
2236         $this->processed_dates_times = array();
2237         $this->check_date_relationships_load();
2238
2239         if($custom_join)
2240         {
2241             $this->custom_fields->fill_relationships();
2242         }
2243
2244                 $this->is_updated_dependent_fields = false;
2245         $this->fill_in_additional_detail_fields();
2246         $this->fill_in_relationship_fields();
2247 // save related fields values for audit
2248          foreach ($this->get_related_fields() as $rel_field_name)
2249          {
2250              if (! empty($this->$rel_field_name['name']))
2251              {
2252                  $this->fetched_rel_row[$rel_field_name['name']] = $this->$rel_field_name['name'];
2253              }
2254          }
2255         //make a copy of fields in the relationship_fields array. These field values will be used to
2256         //clear relationship.
2257         foreach ( $this->field_defs as $key => $def )
2258         {
2259             if ($def [ 'type' ] == 'relate' && isset ( $def [ 'id_name'] ) && isset ( $def [ 'link'] ) && isset ( $def[ 'save' ])) {
2260                 if (isset($this->$key)) {
2261                     $this->rel_fields_before_value[$key]=$this->$key;
2262                     if (isset($this->$def [ 'id_name']))
2263                         $this->rel_fields_before_value[$def [ 'id_name']]=$this->$def [ 'id_name'];
2264                 }
2265                 else
2266                     $this->rel_fields_before_value[$key]=null;
2267            }
2268         }
2269         if (isset($this->relationship_fields) && is_array($this->relationship_fields))
2270         {
2271             foreach ($this->relationship_fields as $rel_id=>$rel_name)
2272             {
2273                 if (isset($this->$rel_id))
2274                     $this->rel_fields_before_value[$rel_id]=$this->$rel_id;
2275                 else
2276                     $this->rel_fields_before_value[$rel_id]=null;
2277             }
2278         }
2279
2280         // call the custom business logic
2281         $custom_logic_arguments['id'] = $id;
2282         $custom_logic_arguments['encode'] = $encode;
2283         $this->call_custom_logic("after_retrieve", $custom_logic_arguments);
2284         unset($custom_logic_arguments);
2285         return $this;
2286     }
2287
2288     /**
2289      * Sets value from fetched row into the bean.
2290      *
2291      * @param array $row Fetched row
2292      * @todo loop through vardefs instead
2293      * @internal runs into an issue when populating from field_defs for users - corrupts user prefs
2294      *
2295      * Internal function, do not override.
2296      */
2297     function populateFromRow($row)
2298     {
2299         $nullvalue='';
2300         foreach($this->field_defs as $field=>$field_value)
2301         {
2302             if($field == 'user_preferences' && $this->module_dir == 'Users')
2303                 continue;
2304             if(isset($row[$field]))
2305             {
2306                 $this->$field = $row[$field];
2307                 $owner = $field . '_owner';
2308                 if(!empty($row[$owner])){
2309                     $this->$owner = $row[$owner];
2310                 }
2311             }
2312             else
2313             {
2314                 $this->$field = $nullvalue;
2315             }
2316         }
2317     }
2318
2319
2320
2321     /**
2322     * Add any required joins to the list count query.  The joins are required if there
2323     * is a field in the $where clause that needs to be joined.
2324     *
2325     * @param string $query
2326     * @param string $where
2327     *
2328     * Internal Function, do Not override.
2329     */
2330     function add_list_count_joins(&$query, $where)
2331     {
2332         $custom_join = $this->custom_fields->getJOIN();
2333         if($custom_join)
2334         {
2335             $query .= $custom_join['join'];
2336         }
2337
2338     }
2339
2340     /**
2341     * Changes the select expression of the given query to be 'count(*)' so you
2342     * can get the number of items the query will return.  This is used to
2343     * populate the upper limit on ListViews.
2344      *
2345      * @param string $query Select query string
2346      * @return string count query
2347      *
2348      * Internal function, do not override.
2349     */
2350     function create_list_count_query($query)
2351     {
2352         // remove the 'order by' clause which is expected to be at the end of the query
2353         $pattern = '/\sORDER BY.*/is';  // ignores the case
2354         $replacement = '';
2355         $query = preg_replace($pattern, $replacement, $query);
2356         //handle distinct clause
2357         $star = '*';
2358         if(substr_count(strtolower($query), 'distinct')){
2359             if (!empty($this->seed) && !empty($this->seed->table_name ))
2360                 $star = 'DISTINCT ' . $this->seed->table_name . '.id';
2361             else
2362                 $star = 'DISTINCT ' . $this->table_name . '.id';
2363
2364         }
2365
2366         // change the select expression to 'count(*)'
2367         $pattern = '/SELECT(.*?)(\s){1}FROM(\s){1}/is';  // ignores the case
2368         $replacement = 'SELECT count(' . $star . ') c FROM ';
2369
2370         //if the passed query has union clause then replace all instances of the pattern.
2371         //this is very rare. I have seen this happening only from projects module.
2372         //in addition to this added a condition that has  union clause and uses
2373         //sub-selects.
2374         if (strstr($query," UNION ALL ") !== false) {
2375
2376             //separate out all the queries.
2377             $union_qs=explode(" UNION ALL ", $query);
2378             foreach ($union_qs as $key=>$union_query) {
2379                 $star = '*';
2380                 preg_match($pattern, $union_query, $matches);
2381                 if (!empty($matches)) {
2382                     if (stristr($matches[0], "distinct")) {
2383                         if (!empty($this->seed) && !empty($this->seed->table_name ))
2384                             $star = 'DISTINCT ' . $this->seed->table_name . '.id';
2385                         else
2386                             $star = 'DISTINCT ' . $this->table_name . '.id';
2387                     }
2388                 } // if
2389                 $replacement = 'SELECT count(' . $star . ') c FROM ';
2390                 $union_qs[$key] = preg_replace($pattern, $replacement, $union_query,1);
2391             }
2392             $modified_select_query=implode(" UNION ALL ",$union_qs);
2393         } else {
2394             $modified_select_query = preg_replace($pattern, $replacement, $query,1);
2395         }
2396
2397
2398         return $modified_select_query;
2399     }
2400
2401     /**
2402     * This function returns a paged list of the current object type.  It is intended to allow for
2403     * hopping back and forth through pages of data.  It only retrieves what is on the current page.
2404     *
2405     * @internal This method must be called on a new instance.  It trashes the values of all the fields in the current one.
2406     * @param string $order_by
2407     * @param string $where Additional where clause
2408     * @param int $row_offset Optaional,default 0, starting row number
2409     * @param init $limit Optional, default -1
2410     * @param int $max Optional, default -1
2411     * @param boolean $show_deleted Optional, default 0, if set to 1 system will show deleted records.
2412     * @return array Fetched data.
2413     *
2414     * Internal function, do not override.
2415     *
2416     */
2417     function get_list($order_by = "", $where = "", $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $singleSelect=false, $select_fields = array())
2418     {
2419         $GLOBALS['log']->debug("get_list:  order_by = '$order_by' and where = '$where' and limit = '$limit'");
2420         if(isset($_SESSION['show_deleted']))
2421         {
2422             $show_deleted = 1;
2423         }
2424         $order_by=$this->process_order_by($order_by);
2425
2426         if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2427         {
2428             global $current_user;
2429             $owner_where = $this->getOwnerWhere($current_user->id);
2430
2431             //rrs - because $this->getOwnerWhere() can return '' we need to be sure to check for it and
2432             //handle it properly else you could get into a situation where you are create a where stmt like
2433             //WHERE .. AND ''
2434             if(!empty($owner_where)){
2435                 if(empty($where)){
2436                     $where = $owner_where;
2437                 }else{
2438                     $where .= ' AND '.  $owner_where;
2439                 }
2440             }
2441         }
2442         $query = $this->create_new_list_query($order_by, $where,$select_fields,array(), $show_deleted,'',false,null,$singleSelect);
2443         return $this->process_list_query($query, $row_offset, $limit, $max, $where);
2444     }
2445
2446     /**
2447     * Prefixes column names with this bean's table name.
2448     *
2449     * @param string $order_by  Order by clause to be processed
2450     * @param SugarBean $submodule name of the module this order by clause is for
2451     * @return string Processed order by clause
2452     *
2453     * Internal function, do not override.
2454     */
2455     function process_order_by ($order_by, $submodule = null)
2456     {
2457         if (empty($order_by))
2458             return $order_by;
2459         //submodule is empty,this is for list object in focus
2460         if (empty($submodule))
2461         {
2462             $bean_queried = $this;
2463         }
2464         else
2465         {
2466             //submodule is set, so this is for subpanel, use submodule
2467             $bean_queried = $submodule;
2468         }
2469         $elements = explode(',',$order_by);
2470         foreach ($elements as $key=>$value)
2471         {
2472             if (strchr($value,'.') === false)
2473             {
2474                 //value might have ascending and descending decorations
2475                 $list_column = explode(' ',trim($value));
2476                 if (isset($list_column[0]))
2477                 {
2478                     $list_column_name=trim($list_column[0]);
2479                     if (isset($bean_queried->field_defs[$list_column_name]))
2480                     {
2481                         $source=isset($bean_queried->field_defs[$list_column_name]['source']) ? $bean_queried->field_defs[$list_column_name]['source']:'db';
2482                         if (empty($bean_queried->field_defs[$list_column_name]['table']) && $source=='db')
2483                         {
2484                             $list_column[0] = $bean_queried->table_name .".".$list_column[0] ;
2485                         }
2486                         if (empty($bean_queried->field_defs[$list_column_name]['table']) && $source=='custom_fields')
2487                         {
2488                             $list_column[0] = $bean_queried->table_name ."_cstm.".$list_column[0] ;
2489                         }
2490                         // Bug 38803 - Use CONVERT() function when doing an order by on ntext, text, and image fields
2491                         if ($source != 'non-db' && $this->db->isTextType($this->db->getFieldType($bean_queried->field_defs[$list_column_name]))) {
2492                             $list_column[0] = $this->db->convert($list_column[0], "text2char");
2493                         }
2494                         $value = implode(' ',$list_column);
2495                     } else {
2496                         $GLOBALS['log']->debug("process_order_by: ($list_column[0]) does not have a vardef entry.");
2497                     }
2498                 }
2499             }
2500             $elements[$key]=$value;
2501         }
2502         return implode(',', $elements);
2503
2504     }
2505
2506
2507     /**
2508     * Returns a detail object like retrieving of the current object type.
2509     *
2510     * It is intended for use in navigation buttons on the DetailView.  It will pass an offset and limit argument to the sql query.
2511     * @internal This method must be called on a new instance.  It overrides the values of all the fields in the current one.
2512     *
2513     * @param string $order_by
2514     * @param string $where Additional where clause
2515     * @param int $row_offset Optaional,default 0, starting row number
2516     * @param init $limit Optional, default -1
2517     * @param int $max Optional, default -1
2518     * @param boolean $show_deleted Optioanl, default 0, if set to 1 system will show deleted records.
2519     * @return array Fetched data.
2520     *
2521     * Internal function, do not override.
2522     */
2523     function get_detail($order_by = "", $where = "",  $offset = 0, $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)
2524     {
2525         $GLOBALS['log']->debug("get_detail:  order_by = '$order_by' and where = '$where' and limit = '$limit' and offset = '$offset'");
2526         if(isset($_SESSION['show_deleted']))
2527         {
2528             $show_deleted = 1;
2529         }
2530
2531         if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2532         {
2533             global $current_user;
2534             $owner_where = $this->getOwnerWhere($current_user->id);
2535
2536             if(empty($where))
2537             {
2538                 $where = $owner_where;
2539             }
2540             else
2541             {
2542                 $where .= ' AND '.  $owner_where;
2543             }
2544         }
2545         $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted, $offset);
2546
2547         //Add Limit and Offset to query
2548         //$query .= " LIMIT 1 OFFSET $offset";
2549
2550         return $this->process_detail_query($query, $row_offset, $limit, $max, $where, $offset);
2551     }
2552
2553     /**
2554     * Fetches data from all related tables.
2555     *
2556     * @param object $child_seed
2557     * @param string $related_field_name relation to fetch data for
2558     * @param string $order_by Optional, default empty
2559     * @param string $where Optional, additional where clause
2560     * @return array Fetched data.
2561     *
2562     * Internal function, do not override.
2563     */
2564     function get_related_list($child_seed,$related_field_name, $order_by = "", $where = "",
2565     $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)
2566     {
2567         global $layout_edit_mode;
2568         $query_array = array();
2569
2570         if(isset($layout_edit_mode) && $layout_edit_mode)
2571         {
2572             $response = array();
2573             $child_seed->assign_display_fields($child_seed->module_dir);
2574             $response['list'] = array($child_seed);
2575             $response['row_count'] = 1;
2576             $response['next_offset'] = 0;
2577             $response['previous_offset'] = 0;
2578
2579             return $response;
2580         }
2581         $GLOBALS['log']->debug("get_related_list:  order_by = '$order_by' and where = '$where' and limit = '$limit'");
2582         if(isset($_SESSION['show_deleted']))
2583         {
2584             $show_deleted = 1;
2585         }
2586
2587         $this->load_relationship($related_field_name);
2588
2589         if ($this->$related_field_name instanceof Link) {
2590
2591             $query_array = $this->$related_field_name->getQuery(true);
2592         } else {
2593
2594             $query_array = $this->$related_field_name->getQuery(array(
2595                 "return_as_array" => true,
2596                 'where' => '1=1' // hook for 'where' clause in M2MRelationship file
2597                     ));
2598         }
2599
2600         $entire_where = $query_array['where'];
2601         if(!empty($where))
2602         {
2603             if(empty($entire_where))
2604             {
2605                 $entire_where = ' WHERE ' . $where;
2606             }
2607             else
2608             {
2609                 $entire_where .= ' AND ' . $where;
2610             }
2611         }
2612
2613         $query = 'SELECT '.$child_seed->table_name.'.* ' . $query_array['from'] . ' ' . $entire_where;
2614         if(!empty($order_by))
2615         {
2616             $query .= " ORDER BY " . $order_by;
2617         }
2618
2619         return $child_seed->process_list_query($query, $row_offset, $limit, $max, $where);
2620     }
2621
2622
2623     protected static function build_sub_queries_for_union($subpanel_list, $subpanel_def, $parentbean, $order_by)
2624     {
2625         global $layout_edit_mode, $beanFiles, $beanList;
2626         $subqueries = array();
2627         foreach($subpanel_list as $this_subpanel)
2628         {
2629             if(!$this_subpanel->isDatasourceFunction() || ($this_subpanel->isDatasourceFunction()
2630                 && isset($this_subpanel->_instance_properties['generate_select'])
2631                 && $this_subpanel->_instance_properties['generate_select']==true))
2632             {
2633                 //the custom query function must return an array with
2634                 if ($this_subpanel->isDatasourceFunction()) {
2635                     $shortcut_function_name = $this_subpanel->get_data_source_name();
2636                     $parameters=$this_subpanel->get_function_parameters();
2637                     if (!empty($parameters))
2638                     {
2639                         //if the import file function is set, then import the file to call the custom function from
2640                         if (is_array($parameters)  && isset($parameters['import_function_file'])){
2641                             //this call may happen multiple times, so only require if function does not exist
2642                             if(!function_exists($shortcut_function_name)){
2643                                 require_once($parameters['import_function_file']);
2644                             }
2645                             //call function from required file
2646                             $query_array = $shortcut_function_name($parameters);
2647                         }else{
2648                             //call function from parent bean
2649                             $query_array = $parentbean->$shortcut_function_name($parameters);
2650                         }
2651                     }
2652                     else
2653                     {
2654                         $query_array = $parentbean->$shortcut_function_name();
2655                     }
2656                 }  else {
2657                     $related_field_name = $this_subpanel->get_data_source_name();
2658                     if (!$parentbean->load_relationship($related_field_name)){
2659                         unset ($parentbean->$related_field_name);
2660                         continue;
2661                     }
2662                     $query_array = $parentbean->$related_field_name->getSubpanelQuery(array(), true);
2663                 }
2664                 $table_where = preg_replace('/^\s*WHERE/i', '', $this_subpanel->get_where());
2665                 $where_definition = preg_replace('/^\s*WHERE/i', '', $query_array['where']);
2666
2667                 if(!empty($table_where))
2668                 {
2669                     if(empty($where_definition))
2670                     {
2671                         $where_definition = $table_where;
2672                     }
2673                     else
2674                     {
2675                         $where_definition .= ' AND ' . $table_where;
2676                     }
2677                 }
2678
2679                 $submodulename = $this_subpanel->_instance_properties['module'];
2680                 $submoduleclass = $beanList[$submodulename];
2681                 //require_once($beanFiles[$submoduleclass]);
2682
2683                 /** @var SugarBean $submodule */
2684                 $submodule = new $submoduleclass();
2685                 $subwhere = $where_definition;
2686
2687
2688
2689                 $list_fields = $this_subpanel->get_list_fields();
2690                 foreach($list_fields as $list_key=>$list_field)
2691                 {
2692                     if(isset($list_field['usage']) && $list_field['usage'] == 'display_only')
2693                     {
2694                         unset($list_fields[$list_key]);
2695                     }
2696                 }
2697
2698
2699                 if(!$subpanel_def->isCollection() && isset($list_fields[$order_by]) && isset($submodule->field_defs[$order_by])&& (!isset($submodule->field_defs[$order_by]['source']) || $submodule->field_defs[$order_by]['source'] == 'db'))
2700                 {
2701                     $order_by = $submodule->table_name .'.'. $order_by;
2702                 }
2703                 $table_name = $this_subpanel->table_name;
2704                 $panel_name=$this_subpanel->name;
2705                 $params = array();
2706                 $params['distinct'] = $this_subpanel->distinct_query();
2707
2708                 $params['joined_tables'] = $query_array['join_tables'];
2709                 $params['include_custom_fields'] = !$subpanel_def->isCollection();
2710                 $params['collection_list'] = $subpanel_def->get_inst_prop_value('collection_list');
2711
2712                 // use single select in case when sorting by relate field
2713                 $singleSelect = $submodule->is_relate_field($order_by);
2714
2715                 $subquery = $submodule->create_new_list_query('',$subwhere ,$list_fields,$params, 0,'', true,$parentbean, $singleSelect);
2716
2717                 $subquery['select'] = $subquery['select']." , '$panel_name' panel_name ";
2718                 $subquery['from'] = $subquery['from'].$query_array['join'];
2719                 $subquery['query_array'] = $query_array;
2720                 $subquery['params'] = $params;
2721
2722                 $subqueries[] = $subquery;
2723             }
2724         }
2725         return $subqueries;
2726     }
2727
2728     /**
2729     * Constructs a query to fetch data for supanels and list views
2730      *
2731      * It constructs union queries for activities subpanel.
2732      *
2733      * @param SugarBean $parentbean constructing queries for link attributes in this bean
2734      * @param string $order_by Optional, order by clause
2735      * @param string $sort_order Optional, sort order
2736      * @param string $where Optional, additional where clause
2737      *
2738      * Internal Function, do not overide.
2739     */
2740     function get_union_related_list($parentbean, $order_by = "", $sort_order='', $where = "",
2741     $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $subpanel_def)
2742     {
2743         $secondary_queries = array();
2744         global $layout_edit_mode, $beanFiles, $beanList;
2745
2746         if(isset($_SESSION['show_deleted']))
2747         {
2748             $show_deleted = 1;
2749         }
2750         $final_query = '';
2751         $final_query_rows = '';
2752         $subpanel_list=array();
2753         if ($subpanel_def->isCollection())
2754         {
2755             $subpanel_def->load_sub_subpanels();
2756             $subpanel_list=$subpanel_def->sub_subpanels;
2757         }
2758         else
2759         {
2760             $subpanel_list[]=$subpanel_def;
2761         }
2762
2763         $first = true;
2764
2765         //Breaking the building process into two loops. The first loop gets a list of all the sub-queries.
2766         //The second loop merges the queries and forces them to select the same number of columns
2767         //All columns in a sub-subpanel group must have the same aliases
2768         //If the subpanel is a datasource function, it can't be a collection so we just poll that function for the and return that
2769         foreach($subpanel_list as $this_subpanel)
2770         {
2771             if($this_subpanel->isDatasourceFunction() && empty($this_subpanel->_instance_properties['generate_select']))
2772             {
2773                 $shortcut_function_name = $this_subpanel->get_data_source_name();
2774                 $parameters=$this_subpanel->get_function_parameters();
2775                 if (!empty($parameters))
2776                 {
2777                     //if the import file function is set, then import the file to call the custom function from
2778                     if (is_array($parameters)  && isset($parameters['import_function_file'])){
2779                         //this call may happen multiple times, so only require if function does not exist
2780                         if(!function_exists($shortcut_function_name)){
2781                             require_once($parameters['import_function_file']);
2782                         }
2783                         //call function from required file
2784                         $tmp_final_query =  $shortcut_function_name($parameters);
2785                     }else{
2786                         //call function from parent bean
2787                         $tmp_final_query =  $parentbean->$shortcut_function_name($parameters);
2788                     }
2789                 } else {
2790                     $tmp_final_query = $parentbean->$shortcut_function_name();
2791                 }
2792                 if(!$first)
2793                     {
2794                         $final_query_rows .= ' UNION ALL ( '.$parentbean->create_list_count_query($tmp_final_query, $parameters) . ' )';
2795                         $final_query .= ' UNION ALL ( '.$tmp_final_query . ' )';
2796                     } else {
2797                         $final_query_rows = '(' . $parentbean->create_list_count_query($tmp_final_query, $parameters) . ')';
2798                         $final_query = '(' . $tmp_final_query . ')';
2799                         $first = false;
2800                     }
2801                 }
2802         }
2803         //If final_query is still empty, its time to build the sub-queries
2804         if (empty($final_query))
2805         {
2806             $subqueries = SugarBean::build_sub_queries_for_union($subpanel_list, $subpanel_def, $parentbean, $order_by);
2807             $all_fields = array();
2808             foreach($subqueries as $i => $subquery)
2809             {
2810                 $query_fields = $GLOBALS['db']->getSelectFieldsFromQuery($subquery['select']);
2811                 foreach($query_fields as $field => $select)
2812                 {
2813                     if (!in_array($field, $all_fields))
2814                         $all_fields[] = $field;
2815                 }
2816                 $subqueries[$i]['query_fields'] = $query_fields;
2817             }
2818             $first = true;
2819             //Now ensure the queries have the same set of fields in the same order.
2820             foreach($subqueries as $subquery)
2821             {
2822                 $subquery['select'] = "SELECT";
2823                 foreach($all_fields as $field)
2824                 {
2825                     if (!isset($subquery['query_fields'][$field]))
2826                     {
2827                         $subquery['select'] .= " ' ' $field,";
2828                     }
2829                     else
2830                     {
2831                         $subquery['select'] .= " {$subquery['query_fields'][$field]},";
2832                     }
2833                 }
2834                 $subquery['select'] = substr($subquery['select'], 0 , strlen($subquery['select']) - 1);
2835                 //Put the query into the final_query
2836                 $query =  $subquery['select'] . " " . $subquery['from'] . " " . $subquery['where'];
2837                 if(!$first)
2838                 {
2839                     $query = ' UNION ALL ( '.$query . ' )';
2840                     $final_query_rows .= " UNION ALL ";
2841                 } else {
2842                     $query = '(' . $query . ')';
2843                     $first = false;
2844                 }
2845                 $query_array = $subquery['query_array'];
2846                 $select_position=strpos($query_array['select'],"SELECT");
2847                 $distinct_position=strpos($query_array['select'],"DISTINCT");
2848                 if (!empty($subquery['params']['distinct']) && !empty($subpanel_def->table_name))
2849                 {
2850                     $query_rows = "( SELECT count(DISTINCT ". $subpanel_def->table_name . ".id)".  $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2851                 }
2852                 elseif ($select_position !== false && $distinct_position!= false)
2853                 {
2854                     $query_rows = "( ".substr_replace($query_array['select'],"SELECT count(",$select_position,6). ")" .  $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2855                 }
2856                 else
2857                 {
2858                     //resort to default behavior.
2859                     $query_rows = "( SELECT count(*)".  $subquery['from_min'].$query_array['join']. $subquery['where'].' )';
2860                 }
2861                 if(!empty($subquery['secondary_select']))
2862                 {
2863
2864                     $subquerystring= $subquery['secondary_select'] . $subquery['secondary_from'].$query_array['join']. $subquery['where'];
2865                     if (!empty($subquery['secondary_where']))
2866                     {
2867                         if (empty($subquery['where']))
2868                         {
2869                             $subquerystring.=" WHERE " .$subquery['secondary_where'];
2870                         }
2871                         else
2872                         {
2873                             $subquerystring.=" AND " .$subquery['secondary_where'];
2874                         }
2875                     }
2876                     $secondary_queries[]=$subquerystring;
2877                 }
2878                 $final_query .= $query;
2879                 $final_query_rows .= $query_rows;
2880             }
2881         }
2882
2883         if(!empty($order_by))
2884         {
2885             $submodule = false;
2886             if(!$subpanel_def->isCollection())
2887             {
2888                 $submodulename = $subpanel_def->_instance_properties['module'];
2889                 $submoduleclass = $beanList[$submodulename];
2890                 $submodule = new $submoduleclass();
2891             }
2892             if(!empty($submodule) && !empty($submodule->table_name))
2893             {
2894                 $final_query .= " ORDER BY " .$parentbean->process_order_by($order_by, $submodule);
2895
2896             }
2897             else
2898             {
2899                 $final_query .= " ORDER BY ". $order_by . ' ';
2900             }
2901             if(!empty($sort_order))
2902             {
2903                 $final_query .= ' ' .$sort_order;
2904             }
2905         }
2906
2907
2908         if(isset($layout_edit_mode) && $layout_edit_mode)
2909         {
2910             $response = array();
2911             if(!empty($submodule))
2912             {
2913                 $submodule->assign_display_fields($submodule->module_dir);
2914                 $response['list'] = array($submodule);
2915             }
2916             else
2917         {
2918                 $response['list'] = array();
2919             }
2920             $response['parent_data'] = array();
2921             $response['row_count'] = 1;
2922             $response['next_offset'] = 0;
2923             $response['previous_offset'] = 0;
2924
2925             return $response;
2926         }
2927
2928         return $parentbean->process_union_list_query($parentbean, $final_query, $row_offset, $limit, $max, '',$subpanel_def, $final_query_rows, $secondary_queries);
2929     }
2930
2931
2932     /**
2933     * Returns a full (ie non-paged) list of the current object type.
2934     *
2935     * @param string $order_by the order by SQL parameter. defaults to ""
2936     * @param string $where where clause. defaults to ""
2937     * @param boolean $check_dates. defaults to false
2938     * @param int $show_deleted show deleted records. defaults to 0
2939     */
2940     function get_full_list($order_by = "", $where = "", $check_dates=false, $show_deleted = 0)
2941     {
2942         $GLOBALS['log']->debug("get_full_list:  order_by = '$order_by' and where = '$where'");
2943         if(isset($_SESSION['show_deleted']))
2944         {
2945             $show_deleted = 1;
2946         }
2947         $query = $this->create_new_list_query($order_by, $where,array(),array(), $show_deleted);
2948         return $this->process_full_list_query($query, $check_dates);
2949     }
2950
2951     /**
2952      * Return the list query used by the list views and export button. Next generation of create_new_list_query function.
2953      *
2954      * Override this function to return a custom query.
2955      *
2956      * @param string $order_by custom order by clause
2957      * @param string $where custom where clause
2958      * @param array $filter Optioanal
2959      * @param array $params Optional     *
2960      * @param int $show_deleted Optional, default 0, show deleted records is set to 1.
2961      * @param string $join_type
2962      * @param boolean $return_array Optional, default false, response as array
2963      * @param object $parentbean creating a subquery for this bean.
2964      * @param boolean $singleSelect Optional, default false.
2965      * @return String select query string, optionally an array value will be returned if $return_array= true.
2966      */
2967         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)
2968     {
2969         global $beanFiles, $beanList;
2970         $selectedFields = array();
2971         $secondarySelectedFields = array();
2972         $ret_array = array();
2973         $distinct = '';
2974         if($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list') )
2975         {
2976             global $current_user;
2977             $owner_where = $this->getOwnerWhere($current_user->id);
2978             if(empty($where))
2979             {
2980                 $where = $owner_where;
2981             }
2982             else
2983             {
2984                 $where .= ' AND '.  $owner_where;
2985             }
2986         }
2987         if(!empty($params['distinct']))
2988         {
2989             $distinct = ' DISTINCT ';
2990         }
2991         if(empty($filter))
2992         {
2993             $ret_array['select'] = " SELECT $distinct $this->table_name.* ";
2994         }
2995         else
2996         {
2997             $ret_array['select'] = " SELECT $distinct $this->table_name.id ";
2998         }
2999         $ret_array['from'] = " FROM $this->table_name ";
3000         $ret_array['from_min'] = $ret_array['from'];
3001         $ret_array['secondary_from'] = $ret_array['from'] ;
3002         $ret_array['where'] = '';
3003         $ret_array['order_by'] = '';
3004         //secondary selects are selects that need to be run after the primary query to retrieve additional info on main
3005         if($singleSelect)
3006         {
3007             $ret_array['secondary_select']=& $ret_array['select'];
3008             $ret_array['secondary_from'] = & $ret_array['from'];
3009         }
3010         else
3011         {
3012             $ret_array['secondary_select'] = '';
3013         }
3014         $custom_join = false;
3015         if((!isset($params['include_custom_fields']) || $params['include_custom_fields']) &&  isset($this->custom_fields))
3016         {
3017
3018             $custom_join = $this->custom_fields->getJOIN( empty($filter)? true: $filter );
3019             if($custom_join)
3020             {
3021                 $ret_array['select'] .= ' ' .$custom_join['select'];
3022             }
3023         }
3024         if($custom_join)
3025         {
3026             $ret_array['from'] .= ' ' . $custom_join['join'];
3027             // Bug 52490 - Captivea (Sve) - To be able to add custom fields inside where clause in a subpanel
3028             $ret_array['from_min'] .= ' ' . $custom_join['join'];
3029         }
3030         $jtcount = 0;
3031         //LOOP AROUND FOR FIXIN VARDEF ISSUES
3032         require('include/VarDefHandler/listvardefoverride.php');
3033         if (file_exists('custom/include/VarDefHandler/listvardefoverride.php'))
3034         {
3035             require('custom/include/VarDefHandler/listvardefoverride.php');
3036         }
3037
3038         $joined_tables = array();
3039         if(!empty($params['joined_tables']))
3040         {
3041             foreach($params['joined_tables'] as $table)
3042             {
3043                 $joined_tables[$table] = 1;
3044             }
3045         }
3046
3047         if(!empty($filter))
3048         {
3049             $filterKeys = array_keys($filter);
3050             if(is_numeric($filterKeys[0]))
3051             {
3052                 $fields = array();
3053                 foreach($filter as $field)
3054                 {
3055                     $field = strtolower($field);
3056                     //remove out id field so we don't duplicate it
3057                     if ( $field == 'id' && !empty($filter) ) {
3058                         continue;
3059                     }
3060                     if(isset($this->field_defs[$field]))
3061                     {
3062                         $fields[$field]= $this->field_defs[$field];
3063                     }
3064                     else
3065                     {
3066                         $fields[$field] = array('force_exists'=>true);
3067                     }
3068                 }
3069             }else{
3070                 $fields =       $filter;
3071             }
3072         }
3073         else
3074         {
3075             $fields =   $this->field_defs;
3076         }
3077
3078         $used_join_key = array();
3079
3080         foreach($fields as $field=>$value)
3081         {
3082             //alias is used to alias field names
3083             $alias='';
3084             if  (isset($value['alias']))
3085             {
3086                 $alias =' as ' . $value['alias'] . ' ';
3087             }
3088
3089             if(empty($this->field_defs[$field]) || !empty($value['force_blank']) )
3090             {
3091                 if(!empty($filter) && isset($filter[$field]['force_exists']) && $filter[$field]['force_exists'])
3092                 {
3093                     if ( isset($filter[$field]['force_default']) )
3094                         $ret_array['select'] .= ", {$filter[$field]['force_default']} $field ";
3095                     else
3096                     //spaces are a fix for length issue problem with unions.  The union only returns the maximum number of characters from the first select statement.
3097                         $ret_array['select'] .= ", '                                                                                                                                                                                                                                                              ' $field ";
3098                 }
3099                 continue;
3100             }
3101             else
3102             {
3103                 $data = $this->field_defs[$field];
3104             }
3105
3106             //ignore fields that are a part of the collection and a field has been removed as a result of
3107             //layout customization.. this happens in subpanel customizations, use case, from the contacts subpanel
3108             //in opportunities module remove the contact_role/opportunity_role field.
3109             $process_field=true;
3110             if (isset($data['relationship_fields']) and !empty($data['relationship_fields']))
3111             {
3112                 foreach ($data['relationship_fields'] as $field_name)
3113                 {
3114                     if (!isset($fields[$field_name]))
3115                     {
3116                         $process_field=false;
3117                     }
3118                 }
3119             }
3120             if (!$process_field)
3121             {
3122                 continue;
3123             }
3124
3125             if(  (!isset($data['source']) || $data['source'] == 'db') && (!empty($alias) || !empty($filter) ))
3126             {
3127                 $ret_array['select'] .= ", $this->table_name.$field $alias";
3128                 $selectedFields["$this->table_name.$field"] = true;
3129             } else if(  (!isset($data['source']) || $data['source'] == 'custom_fields') && (!empty($alias) || !empty($filter) )) {
3130                 //add this column only if it has NOT already been added to select statement string
3131                 $colPos = strpos($ret_array['select'],"$this->table_name"."_cstm".".$field");
3132                 if(!$colPos || $colPos<0)
3133                 {
3134                     $ret_array['select'] .= ", $this->table_name"."_cstm".".$field $alias";
3135                 }
3136
3137                 $selectedFields["$this->table_name.$field"] = true;
3138             }
3139
3140             if($data['type'] != 'relate' && isset($data['db_concat_fields']))
3141             {
3142                 $ret_array['select'] .= ", " . $this->db->concat($this->table_name, $data['db_concat_fields']) . " as $field";
3143                 $selectedFields[$this->db->concat($this->table_name, $data['db_concat_fields'])] = true;
3144             }
3145             //Custom relate field or relate fields built in module builder which have no link field associated.
3146             if ($data['type'] == 'relate' && (isset($data['custom_module']) || isset($data['ext2']))) {
3147                 $joinTableAlias = 'jt' . $jtcount;
3148                 $relateJoinInfo = $this->custom_fields->getRelateJoin($data, $joinTableAlias);
3149                 $ret_array['select'] .= $relateJoinInfo['select'];
3150                 $ret_array['from'] .= $relateJoinInfo['from'];
3151                 //Replace any references to the relationship in the where clause with the new alias
3152                 //If the link isn't set, assume that search used the local table for the field
3153                 $searchTable = isset($data['link']) ? $relateJoinInfo['rel_table'] : $this->table_name;
3154                 $field_name = $relateJoinInfo['rel_table'] . '.' . !empty($data['name'])?$data['name']:'name';
3155                 $where = preg_replace('/(^|[\s(])' . $field_name . '/' , '${1}' . $relateJoinInfo['name_field'], $where);
3156                 $jtcount++;
3157             }
3158             //Parent Field
3159             if ($data['type'] == 'parent') {
3160                 //See if we need to join anything by inspecting the where clause
3161                 $match = preg_match('/(^|[\s(])parent_(\w+)_(\w+)\.name/', $where, $matches);
3162                 if ($match) {
3163                     $joinTableAlias = 'jt' . $jtcount;
3164                     $joinModule = $matches[2];
3165                     $joinTable = $matches[3];
3166                     $localTable = $this->table_name;
3167                     if (!empty($data['custom_module'])) {
3168                         $localTable .= '_cstm';
3169                     }
3170                     global $beanFiles, $beanList, $module;
3171                     require_once($beanFiles[$beanList[$joinModule]]);
3172                     $rel_mod = new $beanList[$joinModule]();
3173                     $nameField = "$joinTableAlias.name";
3174                     if (isset($rel_mod->field_defs['name']))
3175                     {
3176                         $name_field_def = $rel_mod->field_defs['name'];
3177                         if(isset($name_field_def['db_concat_fields']))
3178                         {
3179                             $nameField = $this->db->concat($joinTableAlias, $name_field_def['db_concat_fields']);
3180                         }
3181                     }
3182                     $ret_array['select'] .= ", $nameField {$data['name']} ";
3183                     $ret_array['from'] .= " LEFT JOIN $joinTable $joinTableAlias
3184                         ON $localTable.{$data['id_name']} = $joinTableAlias.id";
3185                     //Replace any references to the relationship in the where clause with the new alias
3186                     $where = preg_replace('/(^|[\s(])parent_' . $joinModule . '_' . $joinTable . '\.name/', '${1}' . $nameField, $where);
3187                     $jtcount++;
3188                 }
3189             }
3190
3191             if ($this->is_relate_field($field))
3192             {
3193                 $this->load_relationship($data['link']);
3194                 if(!empty($this->$data['link']))
3195                 {
3196                     $params = array();
3197                     if(empty($join_type))
3198                     {
3199                         $params['join_type'] = ' LEFT JOIN ';
3200                     }
3201                     else
3202                     {
3203                         $params['join_type'] = $join_type;
3204                     }
3205                     if(isset($data['join_name']))
3206                     {
3207                         $params['join_table_alias'] = $data['join_name'];
3208                     }
3209                     else
3210                     {
3211                         $params['join_table_alias']     = 'jt' . $jtcount;
3212
3213                     }
3214                     if(isset($data['join_link_name']))
3215                     {
3216                         $params['join_table_link_alias'] = $data['join_link_name'];
3217                     }
3218                     else
3219                     {
3220                         $params['join_table_link_alias'] = 'jtl' . $jtcount;
3221                     }
3222                     $join_primary = !isset($data['join_primary']) || $data['join_primary'];
3223
3224                     $join = $this->$data['link']->getJoin($params, true);
3225                     $used_join_key[] = $join['rel_key'];
3226                     $rel_module = $this->$data['link']->getRelatedModuleName();
3227                     $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');
3228
3229                                         //if rname is set to 'name', and bean files exist, then check if field should be a concatenated name
3230                                         global $beanFiles, $beanList;
3231                                         if($data['rname'] && !empty($beanFiles[$beanList[$rel_module]])) {
3232
3233                                                 //create an instance of the related bean
3234                                                 require_once($beanFiles[$beanList[$rel_module]]);
3235                                                 $rel_mod = new $beanList[$rel_module]();
3236                                                 //if bean has first and last name fields, then name should be concatenated
3237                                                 if(isset($rel_mod->field_name_map['first_name']) && isset($rel_mod->field_name_map['last_name'])){
3238                                                                 $data['db_concat_fields'] = array(0=>'first_name', 1=>'last_name');
3239                                                 }
3240                                         }
3241
3242
3243                                 if($join['type'] == 'many-to-many')
3244                                 {
3245                                         if(empty($ret_array['secondary_select']))
3246                                         {
3247                                                 $ret_array['secondary_select'] = " SELECT $this->table_name.id ref_id  ";
3248
3249                             if(!empty($beanFiles[$beanList[$rel_module]]) && $join_primary)
3250                             {
3251                                 require_once($beanFiles[$beanList[$rel_module]]);
3252                                 $rel_mod = new $beanList[$rel_module]();
3253                                 if(isset($rel_mod->field_defs['assigned_user_id']))
3254                                 {
3255                                     $ret_array['secondary_select'].= " , ".     $params['join_table_alias'] . ".assigned_user_id {$field}_owner, '$rel_module' {$field}_mod";
3256                                 }
3257                                 else
3258                                 {
3259                                     if(isset($rel_mod->field_defs['created_by']))
3260                                     {
3261                                         $ret_array['secondary_select'].= " , ". $params['join_table_alias'] . ".created_by {$field}_owner , '$rel_module' {$field}_mod";
3262                                     }
3263                                 }
3264                             }
3265                         }
3266
3267                         if(isset($data['db_concat_fields']))
3268                         {
3269                             $ret_array['secondary_select'] .= ' , ' . $this->db->concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
3270                         }
3271                         else
3272                         {
3273                             if(!isset($data['relationship_fields']))
3274                             {
3275                                 $ret_array['secondary_select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
3276                             }
3277                         }
3278                         if(!$singleSelect)
3279                         {
3280                             $ret_array['select'] .= ", '                                                                                                                                                                                                                                                              ' $field ";
3281                         }
3282                         $count_used =0;
3283                         foreach($used_join_key as $used_key) {
3284                             if($used_key == $join['rel_key']) $count_used++;
3285                         }
3286                         if($count_used <= 1) {//27416, the $ret_array['secondary_select'] should always generate, regardless the dbtype
3287                             // add rel_key only if it was not aready added
3288                             if(!$singleSelect)
3289                             {
3290                                 $ret_array['select'] .= ", '                                    '  " . $join['rel_key'] . ' ';
3291                             }
3292                             $ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'].'.'. $join['rel_key'] .' ' . $join['rel_key'];
3293                         }
3294                         if(isset($data['relationship_fields']))
3295                         {
3296                             foreach($data['relationship_fields'] as $r_name=>$alias_name)
3297                             {
3298                                 if(!empty( $secondarySelectedFields[$alias_name]))continue;
3299                                 $ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'].'.'. $r_name .' ' . $alias_name;
3300                                 $secondarySelectedFields[$alias_name] = true;
3301                             }
3302                         }
3303                         if(!$table_joined)
3304                         {
3305                             $ret_array['secondary_from'] .= ' ' . $join['join']. ' AND ' . $params['join_table_alias'].'.deleted=0';
3306                             if (isset($data['link_type']) && $data['link_type'] == 'relationship_info' && ($parentbean instanceOf SugarBean))
3307                             {
3308                                 $ret_array['secondary_where'] = $params['join_table_link_alias'] . '.' . $join['rel_key']. "='" .$parentbean->id . "'";
3309                             }
3310                         }
3311                     }
3312                     else
3313                     {
3314                         if(isset($data['db_concat_fields']))
3315                         {
3316                             $ret_array['select'] .= ' , ' . $this->db->concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
3317                         }
3318                         else
3319                         {
3320                             $ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
3321                         }
3322                         if(isset($data['additionalFields'])){
3323                             foreach($data['additionalFields'] as $k=>$v){
3324                                 $ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $k . ' ' . $v;
3325                             }
3326                         }
3327                         if(!$table_joined)
3328                         {
3329                             $ret_array['from'] .= ' ' . $join['join']. ' AND ' . $params['join_table_alias'].'.deleted=0';
3330                             if(!empty($beanList[$rel_module]) && !empty($beanFiles[$beanList[$rel_module]]))
3331                             {
3332                                 require_once($beanFiles[$beanList[$rel_module]]);
3333                                 $rel_mod = new $beanList[$rel_module]();
3334                                 if(isset($value['target_record_key']) && !empty($filter))
3335                                 {
3336                                     $selectedFields[$this->table_name.'.'.$value['target_record_key']] = true;
3337                                     $ret_array['select'] .= " , $this->table_name.{$value['target_record_key']} ";
3338                                 }
3339                                 if(isset($rel_mod->field_defs['assigned_user_id']))
3340                                 {
3341                                     $ret_array['select'] .= ' , ' .$params['join_table_alias'] . '.assigned_user_id ' .  $field . '_owner';
3342                                 }
3343                                 else
3344                                 {
3345                                     $ret_array['select'] .= ' , ' .$params['join_table_alias'] . '.created_by ' .  $field . '_owner';
3346                                 }
3347                                 $ret_array['select'] .= "  , '".$rel_module  ."' " .  $field . '_mod';
3348
3349                             }
3350                         }
3351                     }
3352                     // To fix SOAP stuff where we are trying to retrieve all the accounts data where accounts.id = ..
3353                     // and this code changes accounts to jt4 as there is a self join with the accounts table.
3354                     //Martin fix #27494
3355                     if(isset($data['db_concat_fields'])){
3356                         $buildWhere = false;
3357                         if(in_array('first_name', $data['db_concat_fields']) && in_array('last_name', $data['db_concat_fields']))
3358                         {
3359                            $exp = '/\(\s*?'.$data['name'].'.*?\%\'\s*?\)/';
3360                            if(preg_match($exp, $where, $matches))
3361                            {
3362                                   $search_expression = $matches[0];
3363                                   //Create three search conditions - first + last, first, last
3364                                   $first_name_search = str_replace($data['name'], $params['join_table_alias'] . '.first_name', $search_expression);
3365                                   $last_name_search = str_replace($data['name'], $params['join_table_alias'] . '.last_name', $search_expression);
3366                                                           $full_name_search = str_replace($data['name'], $this->db->concat($params['join_table_alias'], $data['db_concat_fields']), $search_expression);
3367                                                           $buildWhere = true;
3368                                                           $where = str_replace($search_expression, '(' . $full_name_search . ' OR ' . $first_name_search . ' OR ' . $last_name_search . ')', $where);
3369                            }
3370                         }
3371
3372                         if(!$buildWhere)
3373                         {
3374                                $db_field = $this->db->concat($params['join_table_alias'], $data['db_concat_fields']);
3375                                $where = preg_replace('/'.$data['name'].'/', $db_field, $where);
3376                         }
3377                     }else{
3378                         $where = preg_replace('/(^|[\s(])' . $data['name'] . '/', '${1}' . $params['join_table_alias'] . '.'.$data['rname'], $where);
3379                     }
3380                     if(!$table_joined)
3381                     {
3382                         $joined_tables[$params['join_table_alias']]=1;
3383                         $joined_tables[$params['join_table_link_alias']]=1;
3384                     }
3385
3386                     $jtcount++;
3387                 }
3388             }
3389         }
3390         if(!empty($filter))
3391         {
3392             if(isset($this->field_defs['assigned_user_id']) && empty($selectedFields[$this->table_name.'.assigned_user_id']))
3393             {
3394                 $ret_array['select'] .= ", $this->table_name.assigned_user_id ";
3395             }
3396             else if(isset($this->field_defs['created_by']) &&  empty($selectedFields[$this->table_name.'.created_by']))
3397             {
3398                 $ret_array['select'] .= ", $this->table_name.created_by ";
3399             }
3400             if(isset($this->field_defs['system_id']) && empty($selectedFields[$this->table_name.'.system_id']))
3401             {
3402                 $ret_array['select'] .= ", $this->table_name.system_id ";
3403             }
3404
3405         }
3406
3407         if ($ifListForExport) {
3408                 if(isset($this->field_defs['email1'])) {
3409                         $ret_array['select'].= " ,email_addresses.email_address email1";
3410                         $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 ";
3411                 }
3412         }
3413
3414         $where_auto = '1=1';
3415         if($show_deleted == 0)
3416         {
3417             $where_auto = "$this->table_name.deleted=0";
3418         }else if($show_deleted == 1)
3419         {
3420             $where_auto = "$this->table_name.deleted=1";
3421         }
3422         if($where != "")
3423             $ret_array['where'] = " where ($where) AND $where_auto";
3424         else
3425             $ret_array['where'] = " where $where_auto";
3426         if(!empty($order_by))
3427         {
3428             //make call to process the order by clause
3429             $ret_array['order_by'] = " ORDER BY ". $this->process_order_by($order_by);
3430         }
3431         if($singleSelect)
3432         {
3433             unset($ret_array['secondary_where']);
3434             unset($ret_array['secondary_from']);
3435             unset($ret_array['secondary_select']);
3436         }
3437
3438         if($return_array)
3439         {
3440             return $ret_array;
3441         }
3442
3443         return  $ret_array['select'] . $ret_array['from'] . $ret_array['where']. $ret_array['order_by'];
3444     }
3445     /**
3446      * Returns parent record data for objects that store relationship information
3447      *
3448      * @param array $type_info
3449      *
3450      * Interal function, do not override.
3451      */
3452     function retrieve_parent_fields($type_info)
3453     {
3454         $queries = array();
3455         global $beanList, $beanFiles;
3456         $templates = array();
3457         $parent_child_map = array();
3458         foreach($type_info as $children_info)
3459         {
3460             foreach($children_info as $child_info)
3461             {
3462                 if($child_info['type'] == 'parent')
3463                 {
3464                     if(empty($templates[$child_info['parent_type']]))
3465                     {
3466                         //Test emails will have an invalid parent_type, don't try to load the non-existent parent bean
3467                         if ($child_info['parent_type'] == 'test') {
3468                             continue;
3469                         }
3470                         $class = $beanList[$child_info['parent_type']];
3471                         // Added to avoid error below; just silently fail and write message to log
3472                         if ( empty($beanFiles[$class]) ) {
3473                             $GLOBALS['log']->error($this->object_name.'::retrieve_parent_fields() - cannot load class "'.$class.'", skip loading.');
3474                             continue;
3475                         }
3476                         require_once($beanFiles[$class]);
3477                         $templates[$child_info['parent_type']] = new $class();
3478                     }
3479
3480                     if(empty($queries[$child_info['parent_type']]))
3481                     {
3482                         $queries[$child_info['parent_type']] = "SELECT id ";
3483                         $field_def = $templates[$child_info['parent_type']]->field_defs['name'];
3484                         if(isset($field_def['db_concat_fields']))
3485                         {
3486                             $queries[$child_info['parent_type']] .= ' , ' . $this->db->concat($templates[$child_info['parent_type']]->table_name, $field_def['db_concat_fields']) . ' parent_name';
3487                         }
3488                         else
3489                         {
3490                             $queries[$child_info['parent_type']] .= ' , name parent_name';
3491                         }
3492                         if(isset($templates[$child_info['parent_type']]->field_defs['assigned_user_id']))
3493                         {
3494                             $queries[$child_info['parent_type']] .= ", assigned_user_id parent_name_owner , '{$child_info['parent_type']}' parent_name_mod";;
3495                         }else if(isset($templates[$child_info['parent_type']]->field_defs['created_by']))
3496                         {
3497                             $queries[$child_info['parent_type']] .= ", created_by parent_name_owner, '{$child_info['parent_type']}' parent_name_mod";
3498                         }
3499                         $queries[$child_info['parent_type']] .= " FROM " . $templates[$child_info['parent_type']]->table_name ." WHERE id IN ('{$child_info['parent_id']}'";
3500                     }
3501                     else
3502                     {
3503                         if(empty($parent_child_map[$child_info['parent_id']]))
3504                         $queries[$child_info['parent_type']] .= " ,'{$child_info['parent_id']}'";
3505                     }
3506                     $parent_child_map[$child_info['parent_id']][] = $child_info['child_id'];
3507                 }
3508             }
3509         }
3510         $results = array();
3511         foreach($queries as $query)
3512         {
3513             $result = $this->db->query($query . ')');
3514             while($row = $this->db->fetchByAssoc($result))
3515             {
3516                 $results[$row['id']] = $row;
3517             }
3518         }
3519
3520         $child_results = array();
3521         foreach($parent_child_map as $parent_key=>$parent_child)
3522         {
3523             foreach($parent_child as $child)
3524             {
3525                 if(isset( $results[$parent_key]))
3526                 {
3527                     $child_results[$child] = $results[$parent_key];
3528                 }
3529             }
3530         }
3531         return $child_results;
3532     }
3533
3534     /**
3535      * Processes the list query and return fetched row.
3536      *
3537      * Internal function, do not override.
3538      * @param string $query select query to be processed.
3539      * @param int $row_offset starting position
3540      * @param int $limit Optioanl, default -1
3541      * @param int $max_per_page Optional, default -1
3542      * @param string $where Optional, additional filter criteria.
3543      * @return array Fetched data
3544      */
3545     function process_list_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '')
3546     {
3547         global $sugar_config;
3548         $db = DBManagerFactory::getInstance('listviews');
3549         /**
3550         * if the row_offset is set to 'end' go to the end of the list
3551         */
3552         $toEnd = strval($row_offset) == 'end';
3553         $GLOBALS['log']->debug("process_list_query: ".$query);
3554         if($max_per_page == -1)
3555         {
3556             $max_per_page       = $sugar_config['list_max_entries_per_page'];
3557         }
3558         // Check to see if we have a count query available.
3559         if(empty($sugar_config['disable_count_query']) || $toEnd)
3560         {
3561             $count_query = $this->create_list_count_query($query);
3562             if(!empty($count_query) && (empty($limit) || $limit == -1))
3563             {
3564                 // We have a count query.  Run it and get the results.
3565                 $result = $db->query($count_query, true, "Error running count query for $this->object_name List: ");
3566                 $assoc = $db->fetchByAssoc($result);
3567                 if(!empty($assoc['c']))
3568                 {
3569                     $rows_found = $assoc['c'];
3570                     $limit = $sugar_config['list_max_entries_per_page'];
3571                 }
3572                 if( $toEnd)
3573                 {
3574                     $row_offset = (floor(($rows_found -1) / $limit)) * $limit;
3575                 }
3576             }
3577         }
3578         else
3579         {
3580             if((empty($limit) || $limit == -1))
3581             {
3582                 $limit = $max_per_page + 1;
3583                 $max_per_page = $limit;
3584             }
3585
3586         }
3587
3588         if(empty($row_offset))
3589         {
3590             $row_offset = 0;
3591         }
3592         if(!empty($limit) && $limit != -1 && $limit != -99)
3593         {
3594             $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $this->object_name list: ");
3595         }
3596         else
3597         {
3598             $result = $db->query($query,true,"Error retrieving $this->object_name list: ");
3599         }
3600
3601         $list = Array();
3602
3603         $previous_offset = $row_offset - $max_per_page;
3604         $next_offset = $row_offset + $max_per_page;
3605
3606         $class = get_class($this);
3607             //FIXME: Bug? we should remove the magic number -99
3608             //use -99 to return all
3609             $index = $row_offset;
3610             while ($max_per_page == -99 || ($index < $row_offset + $max_per_page))
3611             {
3612                 $row = $db->fetchByAssoc($result);
3613                 if (empty($row)) break;
3614
3615                 //instantiate a new class each time. This is because php5 passes
3616                 //by reference by default so if we continually update $this, we will
3617                 //at the end have a list of all the same objects
3618                 $temp = new $class();
3619
3620                 foreach($this->field_defs as $field=>$value)
3621                 {
3622                     if (isset($row[$field]))
3623                     {
3624                         $temp->$field = $row[$field];
3625                         $owner_field = $field . '_owner';
3626                         if(isset($row[$owner_field]))
3627                         {
3628                             $temp->$owner_field = $row[$owner_field];
3629                         }
3630
3631                         $GLOBALS['log']->debug("$temp->object_name({$row['id']}): ".$field." = ".$temp->$field);
3632                     }else if (isset($row[$this->table_name .'.'.$field]))
3633                     {
3634                         $temp->$field = $row[$this->table_name .'.'.$field];
3635                     }
3636                     else
3637                     {
3638                         $temp->$field = "";
3639                     }
3640                 }
3641
3642                 $temp->check_date_relationships_load();
3643                 $temp->fill_in_additional_list_fields();
3644                 if($temp->hasCustomFields()) $temp->custom_fields->fill_relationships();
3645                 $temp->call_custom_logic("process_record");
3646
3647                 // fix defect #44206. implement the same logic as sugar_currency_format
3648                 // Smarty modifier does.
3649                 if (property_exists($temp, 'currency_id') && -99 == $temp->currency_id)
3650                 {
3651                     // manually retrieve default currency object as long as it's
3652                     // not stored in database and thus cannot be joined in query
3653                     require_once 'modules/Currencies/Currency.php';
3654                     $currency = new Currency();
3655                     $currency->retrieve($temp->currency_id);
3656
3657                     // walk through all currency-related fields
3658                     foreach ($temp->field_defs as $temp_field)
3659                     {
3660                         if (isset($temp_field['type']) && 'relate' == $temp_field['type']
3661                             && isset($temp_field['module'])  && 'Currencies' == $temp_field['module']
3662                             && isset($temp_field['id_name']) && 'currency_id' == $temp_field['id_name'])
3663                         {
3664                             // populate related properties manually
3665                             $temp_property     = $temp_field['name'];
3666                             $currency_property = $temp_field['rname'];
3667                             $temp->$temp_property = $currency->$currency_property;
3668                         }
3669                     }
3670                 }
3671
3672                 $list[] = $temp;
3673
3674                 $index++;
3675             }
3676         if(!empty($sugar_config['disable_count_query']) && !empty($limit))
3677         {
3678
3679             $rows_found = $row_offset + count($list);
3680
3681             unset($list[$limit - 1]);
3682             if(!$toEnd)
3683             {
3684                 $next_offset--;
3685                 $previous_offset++;
3686             }
3687         } else if(!isset($rows_found)){
3688             $rows_found = $row_offset + count($list);
3689         }
3690
3691         $response = Array();
3692         $response['list'] = $list;
3693         $response['row_count'] = $rows_found;
3694         $response['next_offset'] = $next_offset;
3695         $response['previous_offset'] = $previous_offset;
3696         $response['current_offset'] = $row_offset ;
3697         return $response;
3698     }
3699
3700     /**
3701     * Returns the number of rows that the given SQL query should produce
3702      *
3703      * Internal function, do not override.
3704      * @param string $query valid select  query
3705      * @param boolean $is_count_query Optional, Default false, set to true if passed query is a count query.
3706      * @return int count of rows found
3707     */
3708     function _get_num_rows_in_query($query, $is_count_query=false)
3709     {
3710         $num_rows_in_query = 0;
3711         if (!$is_count_query)
3712         {
3713             $count_query = SugarBean::create_list_count_query($query);
3714         } else
3715             $count_query=$query;
3716
3717         $result = $this->db->query($count_query, true, "Error running count query for $this->object_name List: ");
3718         $row_num = 0;
3719         while($row = $this->db->fetchByAssoc($result, true))
3720         {
3721             $num_rows_in_query += current($row);
3722         }
3723
3724         return $num_rows_in_query;
3725     }
3726
3727     /**
3728      * Applies pagination window to union queries used by list view and subpanels,
3729      * executes the query and returns fetched data.
3730      *
3731      * Internal function, do not override.
3732      * @param object $parent_bean
3733      * @param string $query query to be processed.
3734      * @param int $row_offset
3735      * @param int $limit optional, default -1
3736      * @param int $max_per_page Optional, default -1
3737      * @param string $where Custom where clause.
3738      * @param array $subpanel_def definition of sub-panel to be processed
3739      * @param string $query_row_count
3740      * @param array $seconday_queries
3741      * @return array Fetched data.
3742      */
3743     function process_union_list_query($parent_bean, $query,
3744     $row_offset, $limit= -1, $max_per_page = -1, $where = '', $subpanel_def, $query_row_count='', $secondary_queries = array())
3745
3746     {
3747         $db = DBManagerFactory::getInstance('listviews');
3748         /**
3749         * if the row_offset is set to 'end' go to the end of the list
3750         */
3751         $toEnd = strval($row_offset) == 'end';
3752         global $sugar_config;
3753         $use_count_query=false;
3754         $processing_collection=$subpanel_def->isCollection();
3755
3756         $GLOBALS['log']->debug("process_union_list_query: ".$query);
3757         if($max_per_page == -1)
3758         {
3759             $max_per_page       = $sugar_config['list_max_entries_per_subpanel'];
3760         }
3761         if(empty($query_row_count))
3762         {
3763             $query_row_count = $query;
3764         }
3765         $distinct_position=strpos($query_row_count,"DISTINCT");
3766
3767         if ($distinct_position!= false)
3768         {
3769             $use_count_query=true;
3770         }
3771         $performSecondQuery = true;
3772         if(empty($sugar_config['disable_count_query']) || $toEnd)
3773         {
3774             $rows_found = $this->_get_num_rows_in_query($query_row_count,$use_count_query);
3775             if($rows_found < 1)
3776             {
3777                 $performSecondQuery = false;
3778             }
3779             if(!empty($rows_found) && (empty($limit) || $limit == -1))
3780             {
3781                 $limit = $sugar_config['list_max_entries_per_subpanel'];
3782             }
3783             if( $toEnd)
3784             {
3785                 $row_offset = (floor(($rows_found -1) / $limit)) * $limit;
3786
3787             }
3788         }
3789         else
3790         {
3791             if((empty($limit) || $limit == -1))
3792             {
3793                 $limit = $max_per_page + 1;
3794                 $max_per_page = $limit;
3795             }
3796         }
3797
3798         if(empty($row_offset))
3799         {
3800             $row_offset = 0;
3801         }
3802         $list = array();
3803         $previous_offset = $row_offset - $max_per_page;
3804         $next_offset = $row_offset + $max_per_page;
3805
3806         if($performSecondQuery)
3807         {
3808             if(!empty($limit) && $limit != -1 && $limit != -99)
3809             {
3810                 $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $parent_bean->object_name list: ");
3811             }
3812             else
3813             {
3814                 $result = $db->query($query,true,"Error retrieving $this->object_name list: ");
3815             }
3816                 //use -99 to return all
3817
3818                 // get the current row
3819                 $index = $row_offset;
3820                 $row = $db->fetchByAssoc($result);
3821
3822                 $post_retrieve = array();
3823                 $isFirstTime = true;
3824                 while($row)
3825                 {
3826                     $function_fields = array();
3827                     if(($index < $row_offset + $max_per_page || $max_per_page == -99))
3828                     {
3829                         if ($processing_collection)
3830                         {
3831                             $current_bean =$subpanel_def->sub_subpanels[$row['panel_name']]->template_instance;
3832                             if(!$isFirstTime)
3833                             {
3834                                 $class = get_class($subpanel_def->sub_subpanels[$row['panel_name']]->template_instance);
3835                                 $current_bean = new $class();
3836                             }
3837                         } else {
3838                             $current_bean=$subpanel_def->template_instance;
3839                             if(!$isFirstTime)
3840                             {
3841                                 $class = get_class($subpanel_def->template_instance);
3842                                 $current_bean = new $class();
3843                             }
3844                         }
3845                         $isFirstTime = false;
3846                         //set the panel name in the bean instance.
3847                         if (isset($row['panel_name']))
3848                         {
3849                             $current_bean->panel_name=$row['panel_name'];
3850                         }
3851                         foreach($current_bean->field_defs as $field=>$value)
3852                         {
3853
3854                             if (isset($row[$field]))
3855                             {
3856                                 $current_bean->$field = $this->convertField($row[$field], $value);
3857                                 unset($row[$field]);
3858                             }
3859                             else if (isset($row[$this->table_name .'.'.$field]))
3860                             {
3861                                 $current_bean->$field = $this->convertField($row[$this->table_name .'.'.$field], $value);
3862                                 unset($row[$this->table_name .'.'.$field]);
3863                             }
3864                             else
3865                             {
3866                                 $current_bean->$field = "";
3867                                 unset($row[$field]);
3868                             }
3869                             if(isset($value['source']) && $value['source'] == 'function')
3870                             {
3871                                 $function_fields[]=$field;
3872                             }
3873                         }
3874                         foreach($row as $key=>$value)
3875                         {
3876                             $current_bean->$key = $value;
3877                         }
3878                         foreach($function_fields as $function_field)
3879                         {
3880                             $value = $current_bean->field_defs[$function_field];
3881                             $can_execute = true;
3882                             $execute_params = array();
3883                             $execute_function = array();
3884                             if(!empty($value['function_class']))
3885                             {
3886                                 $execute_function[] =   $value['function_class'];
3887                                 $execute_function[] =   $value['function_name'];
3888                             }
3889                             else
3890                             {
3891                                 $execute_function       = $value['function_name'];
3892                             }
3893                             foreach($value['function_params'] as $param )
3894                             {
3895                                 if (empty($value['function_params_source']) or $value['function_params_source']=='parent')
3896                                 {
3897                                     if(empty($this->$param))
3898                                     {
3899                                         $can_execute = false;
3900                                     } else if($param == '$this') {
3901                                         $execute_params[] = $this;
3902                                     }
3903                                     else
3904                                     {
3905                                         $execute_params[] = $this->$param;
3906                                     }
3907                                 } else if ($value['function_params_source']=='this')
3908                                 {
3909                                     if(empty($current_bean->$param))
3910                                     {
3911                                         $can_execute = false;
3912                                     } else if($param == '$this') {
3913                                         $execute_params[] = $current_bean;
3914                                     }
3915                                     else
3916                                     {
3917                                         $execute_params[] = $current_bean->$param;
3918                                     }
3919                                 }
3920                                 else
3921                                 {
3922                                     $can_execute = false;
3923                                 }
3924
3925                             }
3926                             if($can_execute)
3927                             {
3928                                 if(!empty($value['function_require']))
3929                                 {
3930                                     require_once($value['function_require']);
3931                                 }
3932                                 $current_bean->$function_field = call_user_func_array($execute_function, $execute_params);
3933                             }
3934                         }
3935                         if(!empty($current_bean->parent_type) && !empty($current_bean->parent_id))
3936                         {
3937                             if(!isset($post_retrieve[$current_bean->parent_type]))
3938                             {
3939                                 $post_retrieve[$current_bean->parent_type] = array();
3940                             }
3941                             $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');
3942                         }
3943                         //$current_bean->fill_in_additional_list_fields();
3944                         $list[$current_bean->id] = $current_bean;
3945                     }
3946                     // go to the next row
3947                     $index++;
3948                     $row = $db->fetchByAssoc($result);
3949                 }
3950             //now handle retrieving many-to-many relationships
3951             if(!empty($list))
3952             {
3953                 foreach($secondary_queries as $query2)
3954                 {
3955                     $result2 = $db->query($query2);
3956
3957                     $row2 = $db->fetchByAssoc($result2);
3958                     while($row2)
3959                     {
3960                         $id_ref = $row2['ref_id'];
3961
3962                         if(isset($list[$id_ref]))
3963                         {
3964                             foreach($row2 as $r2key=>$r2value)
3965                             {
3966                                 if($r2key != 'ref_id')
3967                                 {
3968                                     $list[$id_ref]->$r2key = $r2value;
3969                                 }
3970                             }
3971                         }
3972                         $row2 = $db->fetchByAssoc($result2);
3973                     }
3974                 }
3975
3976             }
3977
3978             if(isset($post_retrieve))
3979             {
3980                 $parent_fields = $this->retrieve_parent_fields($post_retrieve);
3981             }
3982             else
3983             {
3984                 $parent_fields = array();
3985             }
3986             if(!empty($sugar_config['disable_count_query']) && !empty($limit))
3987             {
3988                 //C.L. Bug 43535 - Use the $index value to set the $rows_found value here
3989                 $rows_found = isset($index) ? $index : $row_offset + count($list);
3990
3991                 if(count($list) >= $limit)
3992                 {
3993                     array_pop($list);
3994                 }
3995                 if(!$toEnd)
3996                 {
3997                     $next_offset--;
3998                     $previous_offset++;
3999                 }
4000             }
4001         }
4002         else
4003         {
4004             $row_found  = 0;
4005             $parent_fields = array();
4006         }
4007         $response = array();
4008         $response['list'] = $list;
4009         $response['parent_data'] = $parent_fields;
4010         $response['row_count'] = $rows_found;
4011         $response['next_offset'] = $next_offset;
4012         $response['previous_offset'] = $previous_offset;
4013         $response['current_offset'] = $row_offset ;
4014         $response['query'] = $query;
4015
4016         return $response;
4017     }
4018
4019     /**
4020      * Applies pagination window to select queries used by detail view,
4021      * executes the query and returns fetched data.
4022      *
4023      * Internal function, do not override.
4024      * @param string $query query to be processed.
4025      * @param int $row_offset
4026      * @param int $limit optional, default -1
4027      * @param int $max_per_page Optional, default -1
4028      * @param string $where Custom where clause.
4029      * @param int $offset Optional, default 0
4030      * @return array Fetched data.
4031      *
4032      */
4033     function process_detail_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '', $offset = 0)
4034     {
4035         global $sugar_config;
4036         $GLOBALS['log']->debug("process_detail_query: ".$query);
4037         if($max_per_page == -1)
4038         {
4039             $max_per_page       = $sugar_config['list_max_entries_per_page'];
4040         }
4041
4042         // Check to see if we have a count query available.
4043         $count_query = $this->create_list_count_query($query);
4044
4045         if(!empty($count_query) && (empty($limit) || $limit == -1))
4046         {
4047             // We have a count query.  Run it and get the results.
4048             $result = $this->db->query($count_query, true, "Error running count query for $this->object_name List: ");
4049             $assoc = $this->db->fetchByAssoc($result);
4050             if(!empty($assoc['c']))
4051             {
4052                 $total_rows = $assoc['c'];
4053             }
4054         }
4055
4056         if(empty($row_offset))
4057         {
4058             $row_offset = 0;
4059         }
4060
4061         $result = $this->db->limitQuery($query, $offset, 1, true,"Error retrieving $this->object_name list: ");
4062
4063         $previous_offset = $row_offset - $max_per_page;
4064         $next_offset = $row_offset + $max_per_page;
4065
4066         $row = $this->db->fetchByAssoc($result);
4067         $this->retrieve($row['id']);
4068
4069         $response = Array();
4070         $response['bean'] = $this;
4071         if (empty($total_rows))
4072             $total_rows=0;
4073         $response['row_count'] = $total_rows;
4074         $response['next_offset'] = $next_offset;
4075         $response['previous_offset'] = $previous_offset;
4076
4077         return $response;
4078     }
4079
4080     /**
4081      * Processes fetched list view data
4082      *
4083      * Internal function, do not override.
4084      * @param string $query query to be processed.
4085      * @param boolean $check_date Optional, default false. if set to true date time values are processed.
4086      * @return array Fetched data.
4087      *
4088      */
4089     function process_full_list_query($query, $check_date=false)
4090     {
4091
4092         $GLOBALS['log']->debug("process_full_list_query: query is ".$query);
4093         $result = $this->db->query($query, false);
4094         $GLOBALS['log']->debug("process_full_list_query: result is ".print_r($result,true));
4095         $class = get_class($this);
4096         $isFirstTime = true;
4097         $bean = new $class();
4098
4099         // We have some data.
4100         while (($row = $bean->db->fetchByAssoc($result)) != null)
4101         {
4102             $row = $this->convertRow($row);
4103             if(!$isFirstTime)
4104             {
4105                 $bean = new $class();
4106             }
4107             $isFirstTime = false;
4108
4109             foreach($bean->field_defs as $field=>$value)
4110             {
4111                 if (isset($row[$field]))
4112                 {
4113                     $bean->$field = $row[$field];
4114                     $GLOBALS['log']->debug("process_full_list: $bean->object_name({$row['id']}): ".$field." = ".$bean->$field);
4115                 }
4116                 else
4117                 {
4118                     $bean->$field = '';
4119                 }
4120             }
4121             if($check_date)
4122             {
4123                 $bean->processed_dates_times = array();
4124                 $bean->check_date_relationships_load();
4125             }
4126             $bean->fill_in_additional_list_fields();
4127             $bean->call_custom_logic("process_record");
4128             $bean->fetched_row = $row;
4129
4130             $list[] = $bean;
4131         }
4132         //}
4133         if (isset($list)) return $list;
4134         else return null;
4135     }
4136
4137     /**
4138     * Tracks the viewing of a detail record.
4139     * This leverages get_summary_text() which is object specific.
4140     *
4141     * Internal function, do not override.
4142     * @param string $user_id - String value of the user that is viewing the record.
4143     * @param string $current_module - String value of the module being processed.
4144     * @param string $current_view - String value of the current view
4145         */
4146         function track_view($user_id, $current_module, $current_view='')
4147         {
4148             $trackerManager = TrackerManager::getInstance();
4149                 if($monitor = $trackerManager->getMonitor('tracker')){
4150                 $monitor->setValue('date_modified', $GLOBALS['timedate']->nowDb());
4151                 $monitor->setValue('user_id', $user_id);
4152                 $monitor->setValue('module_name', $current_module);
4153                 $monitor->setValue('action', $current_view);
4154                 $monitor->setValue('item_id', $this->id);
4155                 $monitor->setValue('item_summary', $this->get_summary_text());
4156                 $monitor->setValue('visible', $this->tracker_visibility);
4157                 $trackerManager->saveMonitor($monitor);
4158                 }
4159         }
4160
4161     /**
4162      * Returns the summary text that should show up in the recent history list for this object.
4163      *
4164      * @return string
4165      */
4166     public function get_summary_text()
4167     {
4168         return "Base Implementation.  Should be overridden.";
4169     }
4170
4171     /**
4172     * This is designed to be overridden and add specific fields to each record.
4173     * This allows the generic query to fill in the major fields, and then targeted
4174     * queries to get related fields and add them to the record.  The contact's
4175     * account for instance.  This method is only used for populating extra fields
4176     * in lists.
4177     */
4178     function fill_in_additional_list_fields(){
4179         if(!empty($this->field_defs['parent_name']) && empty($this->parent_name)){
4180             $this->fill_in_additional_parent_fields();
4181         }
4182     }
4183
4184     /**
4185     * This is designed to be overridden and add specific fields to each record.
4186     * This allows the generic query to fill in the major fields, and then targeted
4187     * queries to get related fields and add them to the record.  The contact's
4188     * account for instance.  This method is only used for populating extra fields
4189     * in the detail form
4190     */
4191     function fill_in_additional_detail_fields()
4192     {
4193         if(!empty($this->field_defs['assigned_user_name']) && !empty($this->assigned_user_id)){
4194
4195             $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
4196
4197         }
4198                 if(!empty($this->field_defs['created_by']) && !empty($this->created_by))
4199                 $this->created_by_name = get_assigned_user_name($this->created_by);
4200                 if(!empty($this->field_defs['modified_user_id']) && !empty($this->modified_user_id))
4201                 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
4202
4203                 if(!empty($this->field_defs['parent_name'])){
4204                         $this->fill_in_additional_parent_fields();
4205                 }
4206     }
4207
4208     /**
4209     * This is desgined to be overridden or called from extending bean. This method
4210     * will fill in any parent_name fields.
4211     */
4212     function fill_in_additional_parent_fields() {
4213
4214         if(!empty($this->parent_id) && !empty($this->last_parent_id) && $this->last_parent_id == $this->parent_id){
4215             return false;
4216         }else{
4217             $this->parent_name = '';
4218         }
4219         if(!empty($this->parent_type)) {
4220             $this->last_parent_id = $this->parent_id;
4221             $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'));
4222             if(!empty($this->parent_first_name) || !empty($this->parent_last_name) ){
4223                 $this->parent_name = $GLOBALS['locale']->getLocaleFormattedName($this->parent_first_name, $this->parent_last_name);
4224             } else if(!empty($this->parent_document_name)){
4225                 $this->parent_name = $this->parent_document_name;
4226             }
4227         }
4228     }
4229
4230 /*
4231      * Fill in a link field
4232      */
4233
4234     function fill_in_link_field( $linkFieldName , $def)
4235     {
4236         $idField = $linkFieldName;
4237         //If the id_name provided really was an ID, don't try to load it as a link. Use the normal link
4238         if (!empty($this->field_defs[$linkFieldName]['type']) && $this->field_defs[$linkFieldName]['type'] == "id" && !empty($def['link']))
4239         {
4240             $linkFieldName = $def['link'];
4241         }
4242         if ($this->load_relationship($linkFieldName))
4243         {
4244             $list=$this->$linkFieldName->get();
4245             $this->$idField = '' ; // match up with null value in $this->populateFromRow()
4246             if (!empty($list))
4247                 $this->$idField = $list[0];
4248         }
4249     }
4250
4251     /**
4252     * Fill in fields where type = relate
4253     */
4254     function fill_in_relationship_fields(){
4255         global $fill_in_rel_depth;
4256         if(empty($fill_in_rel_depth) || $fill_in_rel_depth < 0)
4257             $fill_in_rel_depth = 0;
4258
4259         if($fill_in_rel_depth > 1)
4260             return;
4261
4262         $fill_in_rel_depth++;
4263
4264         foreach($this->field_defs as $field)
4265         {
4266             if(0 == strcmp($field['type'],'relate') && !empty($field['module']))
4267             {
4268                 $name = $field['name'];
4269                 if(empty($this->$name))
4270                 {
4271                     // 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']
4272                     $related_module = $field['module'];
4273                     $id_name = $field['id_name'];
4274
4275                     if (empty($this->$id_name))
4276                     {
4277                        $this->fill_in_link_field($id_name, $field);
4278                     }
4279                     if(!empty($this->$id_name) && ( $this->object_name != $related_module || ( $this->object_name == $related_module && $this->$id_name != $this->id ))){
4280                         if(isset($GLOBALS['beanList'][ $related_module])){
4281                             $class = $GLOBALS['beanList'][$related_module];
4282
4283                             if(!empty($this->$id_name) && file_exists($GLOBALS['beanFiles'][$class]) && isset($this->$name)){
4284                                 require_once($GLOBALS['beanFiles'][$class]);
4285                                 $mod = new $class();
4286
4287                                 // disable row level security in order to be able
4288                                 // to retrieve related bean properties (bug #44928)
4289
4290                                 $mod->retrieve($this->$id_name);
4291
4292                                 if (!empty($field['rname'])) {
4293                                     $this->$name = $mod->$field['rname'];
4294                                 } else if (isset($mod->name)) {
4295                                     $this->$name = $mod->name;
4296                                 }
4297                             }
4298                         }
4299                     }
4300                     if(!empty($this->$id_name) && isset($this->$name))
4301                     {
4302                         if(!isset($field['additionalFields']))
4303                            $field['additionalFields'] = array();
4304                         if(!empty($field['rname']))
4305                         {
4306                             $field['additionalFields'][$field['rname']]= $name;
4307                         }
4308                         else
4309                         {
4310                             $field['additionalFields']['name']= $name;
4311                         }
4312                         $this->getRelatedFields($related_module, $this->$id_name, $field['additionalFields']);
4313                     }
4314                 }
4315             }
4316         }
4317         $fill_in_rel_depth--;
4318     }
4319
4320     /**
4321     * This is a helper function that is used to quickly created indexes when creating tables.
4322     */
4323     function create_index($query)
4324     {
4325         $GLOBALS['log']->info("create_index: $query");
4326
4327         $result = $this->db->query($query, true, "Error creating index:");
4328     }
4329
4330     /**
4331      * This function should be overridden in each module.  It marks an item as deleted.
4332      *
4333      * If it is not overridden, then marking this type of item is not allowed
4334          */
4335         function mark_deleted($id)
4336         {
4337                 global $current_user;
4338                 $date_modified = $GLOBALS['timedate']->nowDb();
4339                 if(isset($_SESSION['show_deleted']))
4340                 {
4341                         $this->mark_undeleted($id);
4342                 }
4343                 else
4344                 {
4345                         // call the custom business logic
4346                         $custom_logic_arguments['id'] = $id;
4347                         $this->call_custom_logic("before_delete", $custom_logic_arguments);
4348             $this->deleted = 1;
4349             $this->mark_relationships_deleted($id);
4350             if ( isset($this->field_defs['modified_user_id']) ) {
4351                 if (!empty($current_user)) {
4352                     $this->modified_user_id = $current_user->id;
4353                 } else {
4354                     $this->modified_user_id = 1;
4355                 }
4356                 $query = "UPDATE $this->table_name set deleted=1 , date_modified = '$date_modified', modified_user_id = '$this->modified_user_id' where id='$id'";
4357             } else {
4358                 $query = "UPDATE $this->table_name set deleted=1 , date_modified = '$date_modified' where id='$id'";
4359             }
4360             $this->db->query($query, true,"Error marking record deleted: ");
4361
4362             SugarRelationship::resaveRelatedBeans();
4363
4364             // Take the item off the recently viewed lists
4365             $tracker = new Tracker();
4366             $tracker->makeInvisibleForAll($id);
4367
4368
4369             // call the custom business logic
4370             $this->call_custom_logic("after_delete", $custom_logic_arguments);
4371         }
4372     }
4373
4374     /**
4375      * Restores data deleted by call to mark_deleted() function.
4376      *
4377      * Internal function, do not override.
4378     */
4379     function mark_undeleted($id)
4380     {
4381         // call the custom business logic
4382         $custom_logic_arguments['id'] = $id;
4383         $this->call_custom_logic("before_restore", $custom_logic_arguments);
4384
4385                 $date_modified = $GLOBALS['timedate']->nowDb();
4386                 $query = "UPDATE $this->table_name set deleted=0 , date_modified = '$date_modified' where id='$id'";
4387                 $this->db->query($query, true,"Error marking record undeleted: ");
4388
4389         // call the custom business logic
4390         $this->call_custom_logic("after_restore", $custom_logic_arguments);
4391     }
4392
4393    /**
4394     * This function deletes relationships to this object.  It should be overridden
4395     * to handle the relationships of the specific object.
4396     * This function is called when the item itself is being deleted.
4397     *
4398     * @param int $id id of the relationship to delete
4399     */
4400    function mark_relationships_deleted($id)
4401    {
4402     $this->delete_linked($id);
4403    }
4404
4405     /**
4406     * This function is used to execute the query and create an array template objects
4407     * from the resulting ids from the query.
4408     * It is currently used for building sub-panel arrays.
4409     *
4410     * @param string $query - the query that should be executed to build the list
4411     * @param object $template - The object that should be used to copy the records.
4412     * @param int $row_offset Optional, default 0
4413     * @param int $limit Optional, default -1
4414     * @return array
4415     */
4416     function build_related_list($query, &$template, $row_offset = 0, $limit = -1)
4417     {
4418         $GLOBALS['log']->debug("Finding linked records $this->object_name: ".$query);
4419         $db = DBManagerFactory::getInstance('listviews');
4420
4421         if(!empty($row_offset) && $row_offset != 0 && !empty($limit) && $limit != -1)
4422         {
4423             $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $template->object_name list: ");
4424         }
4425         else
4426         {
4427             $result = $db->query($query, true);
4428         }
4429
4430         $list = Array();
4431         $isFirstTime = true;
4432         $class = get_class($template);
4433         while($row = $this->db->fetchByAssoc($result))
4434         {
4435             if(!$isFirstTime)
4436             {
4437                 $template = new $class();
4438             }
4439             $isFirstTime = false;
4440             $record = $template->retrieve($row['id']);
4441
4442             if($record != null)
4443             {
4444                 // this copies the object into the array
4445                 $list[] = $template;
4446             }
4447         }
4448         return $list;
4449     }
4450
4451   /**
4452     * This function is used to execute the query and create an array template objects
4453     * from the resulting ids from the query.
4454     * It is currently used for building sub-panel arrays. It supports an additional
4455     * where clause that is executed as a filter on the results
4456     *
4457     * @param string $query - the query that should be executed to build the list
4458     * @param object $template - The object that should be used to copy the records.
4459     */
4460   function build_related_list_where($query, &$template, $where='', $in='', $order_by, $limit='', $row_offset = 0)
4461   {
4462     $db = DBManagerFactory::getInstance('listviews');
4463     // No need to do an additional query
4464     $GLOBALS['log']->debug("Finding linked records $this->object_name: ".$query);
4465     if(empty($in) && !empty($query))
4466     {
4467         $idList = $this->build_related_in($query);
4468         $in = $idList['in'];
4469     }
4470     // MFH - Added Support For Custom Fields in Searches
4471     $custom_join="";
4472     if(isset($this->custom_fields)) {
4473         $custom_join = $this->custom_fields->getJOIN();
4474     }
4475
4476     $query = "SELECT id ";
4477
4478     if (!empty($custom_join)) {
4479         $query .= $custom_join['select'];
4480     }
4481     $query .= " FROM $this->table_name ";
4482
4483     if (!empty($custom_join) && !empty($custom_join['join'])) {
4484         $query .= " " . $custom_join['join'];
4485     }
4486
4487     $query .= " WHERE deleted=0 AND id IN $in";
4488     if(!empty($where))
4489     {
4490         $query .= " AND $where";
4491     }
4492
4493
4494     if(!empty($order_by))
4495     {
4496         $query .= "ORDER BY $order_by";
4497     }
4498     if (!empty($limit))
4499     {
4500         $result = $db->limitQuery($query, $row_offset, $limit,true,"Error retrieving $this->object_name list: ");
4501     }
4502     else
4503     {
4504         $result = $db->query($query, true);
4505     }
4506
4507     $list = Array();
4508     $isFirstTime = true;
4509     $class = get_class($template);
4510
4511     $disable_security_flag = ($template->disable_row_level_security) ? true : false;
4512     while($row = $db->fetchByAssoc($result))
4513     {
4514         if(!$isFirstTime)
4515         {
4516             $template = new $class();
4517             $template->disable_row_level_security = $disable_security_flag;
4518         }
4519         $isFirstTime = false;
4520         $record = $template->retrieve($row['id']);
4521         if($record != null)
4522         {
4523             // this copies the object into the array
4524             $list[] = $template;
4525         }
4526     }
4527
4528     return $list;
4529   }
4530
4531     /**
4532      * Constructs an comma separated list of ids from passed query results.
4533      *
4534      * @param string @query query to be executed.
4535      *
4536      */
4537     function build_related_in($query)
4538     {
4539         $idList = array();
4540         $result = $this->db->query($query, true);
4541         $ids = '';
4542         while($row = $this->db->fetchByAssoc($result))
4543         {
4544             $idList[] = $row['id'];
4545             if(empty($ids))
4546             {
4547                 $ids = "('" . $row['id'] . "'";
4548             }
4549             else
4550             {
4551                 $ids .= ",'" . $row['id'] . "'";
4552             }
4553         }
4554         if(empty($ids))
4555         {
4556             $ids = "('')";
4557         }else{
4558             $ids .= ')';
4559         }
4560
4561         return array('list'=>$idList, 'in'=>$ids);
4562     }
4563
4564     /**
4565     * Optionally copies values from fetched row into the bean.
4566     *
4567     * Internal function, do not override.
4568     *
4569     * @param string $query - the query that should be executed to build the list
4570     * @param object $template - The object that should be used to copy the records
4571     * @param array $field_list List of  fields.
4572     * @return array
4573     */
4574     function build_related_list2($query, &$template, &$field_list)
4575     {
4576         $GLOBALS['log']->debug("Finding linked values $this->object_name: ".$query);
4577
4578         $result = $this->db->query($query, true);
4579
4580         $list = Array();
4581         $isFirstTime = true;
4582         $class = get_class($template);
4583         while($row = $this->db->fetchByAssoc($result))
4584         {
4585             // Create a blank copy
4586             $copy = $template;
4587             if(!$isFirstTime)
4588             {
4589                 $copy = new $class();
4590             }
4591             $isFirstTime = false;
4592             foreach($field_list as $field)
4593             {
4594                 // Copy the relevant fields
4595                 $copy->$field = $row[$field];
4596
4597             }
4598
4599             // this copies the object into the array
4600             $list[] = $copy;
4601         }
4602
4603         return $list;
4604     }
4605
4606     /**
4607      * Let implementing classes to fill in row specific columns of a list view form
4608      *
4609      */
4610     function list_view_parse_additional_sections(&$list_form)
4611     {
4612     }
4613     /**
4614      * Assigns all of the values into the template for the list view
4615      */
4616     function get_list_view_array()
4617     {
4618         static $cache = array();
4619         // cn: bug 12270 - sensitive fields being passed arbitrarily in listViews
4620         $sensitiveFields = array('user_hash' => '');
4621
4622         $return_array = Array();
4623         global $app_list_strings, $mod_strings;
4624         foreach($this->field_defs as $field=>$value){
4625
4626             if(isset($this->$field)){
4627
4628                 // cn: bug 12270 - sensitive fields being passed arbitrarily in listViews
4629                 if(isset($sensitiveFields[$field]))
4630                     continue;
4631                 if(!isset($cache[$field]))
4632                     $cache[$field] = strtoupper($field);
4633
4634                 //Fields hidden by Dependent Fields
4635                 if (isset($value['hidden']) && $value['hidden'] === true) {
4636                         $return_array[$cache[$field]] = "";
4637
4638                 }
4639                 //cn: if $field is a _dom, detect and return VALUE not KEY
4640                 //cl: empty function check for meta-data enum types that have values loaded from a function
4641                 else if (((!empty($value['type']) && ($value['type'] == 'enum' || $value['type'] == 'radioenum') ))  && empty($value['function'])){
4642                     if(!empty($value['options']) && !empty($app_list_strings[$value['options']][$this->$field])){
4643                         $return_array[$cache[$field]] = $app_list_strings[$value['options']][$this->$field];
4644                     }
4645                     //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.
4646                     elseif(!empty($value['options']) && !empty($mod_strings[$value['options']][$this->$field]))
4647                     {
4648                         $return_array[$cache[$field]] = $mod_strings[$value['options']][$this->$field];
4649                     }
4650                     else{
4651                         $return_array[$cache[$field]] = $this->$field;
4652                     }
4653                     //end bug 21672
4654 // tjy: no need to do this str_replace as the changes in 29994 for ListViewGeneric.tpl for translation handle this now
4655 //                              }elseif(!empty($value['type']) && $value['type'] == 'multienum'&& empty($value['function'])){
4656 //                                      $return_array[strtoupper($field)] = str_replace('^,^', ', ', $this->$field );
4657                 }elseif(!empty($value['custom_module']) && $value['type'] != 'currency'){
4658 //                                      $this->format_field($value);
4659                     $return_array[$cache[$field]] = $this->$field;
4660                 }else{
4661                     $return_array[$cache[$field]] = $this->$field;
4662                 }
4663                 // handle "Assigned User Name"
4664                 if($field == 'assigned_user_name'){
4665                     $return_array['ASSIGNED_USER_NAME'] = get_assigned_user_name($this->assigned_user_id);
4666                 }
4667             }
4668         }
4669         return $return_array;
4670     }
4671     /**
4672      * Override this function to set values in the array used to render list view data.
4673      *
4674      */
4675     function get_list_view_data()
4676     {
4677         return $this->get_list_view_array();
4678     }
4679
4680     /**
4681      * Construct where clause from a list of name-value pairs.
4682      * @param array $fields_array Name/value pairs for column checks
4683      * @param boolean $deleted Optional, default true, if set to false deleted filter will not be added.
4684      * @return string The WHERE clause
4685      */
4686     function get_where($fields_array, $deleted=true)
4687     {
4688         $where_clause = "";
4689         foreach ($fields_array as $name=>$value)
4690         {
4691             if (!empty($where_clause)) {
4692                 $where_clause .= " AND ";
4693             }
4694             $name = $this->db->getValidDBName($name);
4695
4696             $where_clause .= "$name = ".$this->db->quoted($value,false);
4697         }
4698         if(!empty($where_clause)) {
4699             if($deleted) {
4700                 return "WHERE $where_clause AND deleted=0";
4701             } else {
4702                 return "WHERE $where_clause";
4703             }
4704         } else {
4705             return "";
4706         }
4707     }
4708
4709
4710     /**
4711      * Constructs a select query and fetch 1 row using this query, and then process the row
4712      *
4713      * Internal function, do not override.
4714      * @param array @fields_array  array of name value pairs used to construct query.
4715      * @param boolean $encode Optional, default true, encode fetched data.
4716      * @param boolean $deleted Optional, default true, if set to false deleted filter will not be added.
4717      * @return object Instance of this bean with fetched data.
4718      */
4719     function retrieve_by_string_fields($fields_array, $encode=true, $deleted=true)
4720     {
4721         $where_clause = $this->get_where($fields_array, $deleted);
4722         if(isset($this->custom_fields))
4723         $custom_join = $this->custom_fields->getJOIN();
4724         else $custom_join = false;
4725         if($custom_join)
4726         {
4727             $query = "SELECT $this->table_name.*". $custom_join['select']. " FROM $this->table_name " . $custom_join['join'];
4728         }
4729         else
4730         {
4731             $query = "SELECT $this->table_name.* FROM $this->table_name ";
4732         }
4733         $query .= " $where_clause";
4734         $GLOBALS['log']->debug("Retrieve $this->object_name: ".$query);
4735         //requireSingleResult has been deprecated.
4736         //$result = $this->db->requireSingleResult($query, true, "Retrieving record $where_clause:");
4737         $result = $this->db->limitQuery($query,0,1,true, "Retrieving record $where_clause:");
4738
4739
4740         if( empty($result))
4741         {
4742             return null;
4743         }
4744         $row = $this->db->fetchByAssoc($result, $encode);
4745         if(empty($row))
4746         {
4747             return null;
4748         }
4749         // Removed getRowCount-if-clause earlier and insert duplicates_found here as it seems that we have found something
4750         // if we didn't return null in the previous clause.
4751         $this->duplicates_found = true;
4752         $row = $this->convertRow($row);
4753         $this->fetched_row = $row;
4754         $this->fromArray($row);
4755                 $this->is_updated_dependent_fields = false;
4756         $this->fill_in_additional_detail_fields();
4757         return $this;
4758     }
4759
4760     /**
4761     * This method is called during an import before inserting a bean
4762     * Define an associative array called $special_fields
4763     * the keys are user defined, and don't directly map to the bean's fields
4764     * the value is the method name within that bean that will do extra
4765     * processing for that field. example: 'full_name'=>'get_names_from_full_name'
4766     *
4767     */
4768     function process_special_fields()
4769     {
4770         foreach ($this->special_functions as $func_name)
4771         {
4772             if ( method_exists($this,$func_name) )
4773             {
4774                 $this->$func_name();
4775             }
4776         }
4777     }
4778
4779     /**
4780      * Override this function to build a where clause based on the search criteria set into bean .
4781      * @abstract
4782      */
4783     function build_generic_where_clause($value)
4784     {
4785     }
4786
4787     function getRelatedFields($module, $id, $fields, $return_array = false){
4788         if(empty($GLOBALS['beanList'][$module]))return '';
4789         $object = BeanFactory::getObjectName($module);
4790
4791         VardefManager::loadVardef($module, $object);
4792         if(empty($GLOBALS['dictionary'][$object]['table']))return '';
4793         $table = $GLOBALS['dictionary'][$object]['table'];
4794         $query  = 'SELECT id';
4795         foreach($fields as $field=>$alias){
4796             if(!empty($GLOBALS['dictionary'][$object]['fields'][$field]['db_concat_fields'])){
4797                 $query .= ' ,' .$this->db->concat($table, $GLOBALS['dictionary'][$object]['fields'][$field]['db_concat_fields']) .  ' as ' . $alias ;
4798             }else if(!empty($GLOBALS['dictionary'][$object]['fields'][$field]) &&
4799                 (empty($GLOBALS['dictionary'][$object]['fields'][$field]['source']) ||
4800                 $GLOBALS['dictionary'][$object]['fields'][$field]['source'] != "non-db"))
4801             {
4802                 $query .= ' ,' .$table . '.' . $field . ' as ' . $alias;
4803             }
4804             if(!$return_array)$this->$alias = '';
4805         }
4806         if($query == 'SELECT id' || empty($id)){
4807             return '';
4808         }
4809
4810
4811         if(isset($GLOBALS['dictionary'][$object]['fields']['assigned_user_id']))
4812         {
4813             $query .= " , ".    $table  . ".assigned_user_id owner";
4814
4815         }
4816         else if(isset($GLOBALS['dictionary'][$object]['fields']['created_by']))
4817         {
4818             $query .= " , ".    $table . ".created_by owner";
4819
4820         }
4821         $query .=  ' FROM ' . $table . ' WHERE deleted=0 AND id=';
4822         $result = $GLOBALS['db']->query($query . "'$id'" );
4823         $row = $GLOBALS['db']->fetchByAssoc($result);
4824         if($return_array){
4825             return $row;
4826         }
4827         $owner = (empty($row['owner']))?'':$row['owner'];
4828         foreach($fields as $alias){
4829             $this->$alias = (!empty($row[$alias]))? $row[$alias]: '';
4830             $alias = $alias  .'_owner';
4831             $this->$alias = $owner;
4832             $a_mod = $alias  .'_mod';
4833             $this->$a_mod = $module;
4834         }
4835
4836
4837     }
4838
4839
4840     function &parse_additional_headers(&$list_form, $xTemplateSection)
4841     {
4842         return $list_form;
4843     }
4844
4845     function assign_display_fields($currentModule)
4846     {
4847         global $timedate;
4848         foreach($this->column_fields as $field)
4849         {
4850             if(isset($this->field_name_map[$field]) && empty($this->$field))
4851             {
4852                 if($this->field_name_map[$field]['type'] != 'date' && $this->field_name_map[$field]['type'] != 'enum')
4853                 $this->$field = $field;
4854                 if($this->field_name_map[$field]['type'] == 'date')
4855                 {
4856                     $this->$field = $timedate->to_display_date('1980-07-09');
4857                 }
4858                 if($this->field_name_map[$field]['type'] == 'enum')
4859                 {
4860                     $dom = $this->field_name_map[$field]['options'];
4861                     global $current_language, $app_list_strings;
4862                     $mod_strings = return_module_language($current_language, $currentModule);
4863
4864                     if(isset($mod_strings[$dom]))
4865                     {
4866                         $options = $mod_strings[$dom];
4867                         foreach($options as $key=>$value)
4868                         {
4869                             if(!empty($key) && empty($this->$field ))
4870                             {
4871                                 $this->$field = $key;
4872                             }
4873                         }
4874                     }
4875                     if(isset($app_list_strings[$dom]))
4876                     {
4877                         $options = $app_list_strings[$dom];
4878                         foreach($options as $key=>$value)
4879                         {
4880                             if(!empty($key) && empty($this->$field ))
4881                             {
4882                                 $this->$field = $key;
4883                             }
4884                         }
4885                     }
4886
4887
4888                 }
4889             }
4890         }
4891     }
4892
4893     /*
4894     *   RELATIONSHIP HANDLING
4895     */
4896
4897     function set_relationship($table, $relate_values, $check_duplicates = true,$do_update=false,$data_values=null)
4898     {
4899         $where = '';
4900
4901                 // make sure there is a date modified
4902                 $date_modified = $this->db->convert("'".$GLOBALS['timedate']->nowDb()."'", 'datetime');
4903
4904         $row=null;
4905         if($check_duplicates)
4906         {
4907             $query = "SELECT * FROM $table ";
4908             $where = "WHERE deleted = '0'  ";
4909             foreach($relate_values as $name=>$value)
4910             {
4911                 $where .= " AND $name = '$value' ";
4912             }
4913             $query .= $where;
4914             $result = $this->db->query($query, false, "Looking For Duplicate Relationship:" . $query);
4915             $row=$this->db->fetchByAssoc($result);
4916         }
4917
4918         if(!$check_duplicates || empty($row) )
4919         {
4920             unset($relate_values['id']);
4921             if ( isset($data_values))
4922             {
4923                 $relate_values = array_merge($relate_values,$data_values);
4924             }
4925             $query = "INSERT INTO $table (id, ". implode(',', array_keys($relate_values)) . ", date_modified) VALUES ('" . create_guid() . "', " . "'" . implode("', '", $relate_values) . "', ".$date_modified.")" ;
4926
4927             $this->db->query($query, false, "Creating Relationship:" . $query);
4928         }
4929         else if ($do_update)
4930         {
4931             $conds = array();
4932             foreach($data_values as $key=>$value)
4933             {
4934                 array_push($conds,$key."='".$this->db->quote($value)."'");
4935             }
4936             $query = "UPDATE $table SET ". implode(',', $conds).",date_modified=".$date_modified." ".$where;
4937             $this->db->query($query, false, "Updating Relationship:" . $query);
4938         }
4939     }
4940
4941     function retrieve_relationships($table, $values, $select_id)
4942     {
4943         $query = "SELECT $select_id FROM $table WHERE deleted = 0  ";
4944         foreach($values as $name=>$value)
4945         {
4946             $query .= " AND $name = '$value' ";
4947         }
4948         $query .= " ORDER BY $select_id ";
4949         $result = $this->db->query($query, false, "Retrieving Relationship:" . $query);
4950         $ids = array();
4951         while($row = $this->db->fetchByAssoc($result))
4952         {
4953             $ids[] = $row;
4954         }
4955         return $ids;
4956     }
4957
4958     // TODO: this function needs adjustment
4959     function loadLayoutDefs()
4960     {
4961         global $layout_defs;
4962         if(empty( $this->layout_def) && file_exists('modules/'. $this->module_dir . '/layout_defs.php'))
4963         {
4964             include_once('modules/'. $this->module_dir . '/layout_defs.php');
4965             if(file_exists('custom/modules/'. $this->module_dir . '/Ext/Layoutdefs/layoutdefs.ext.php'))
4966             {
4967                 include_once('custom/modules/'. $this->module_dir . '/Ext/Layoutdefs/layoutdefs.ext.php');
4968             }
4969             if ( empty( $layout_defs[get_class($this)]))
4970             {
4971                 echo "\$layout_defs[" . get_class($this) . "]; does not exist";
4972             }
4973
4974             $this->layout_def = $layout_defs[get_class($this)];
4975         }
4976     }
4977
4978     /**
4979     * Trigger custom logic for this module that is defined for the provided hook
4980     * The custom logic file is located under custom/modules/[CURRENT_MODULE]/logic_hooks.php.
4981     * That file should define the $hook_version that should be used.
4982     * It should also define the $hook_array.  The $hook_array will be a two dimensional array
4983     * the first dimension is the name of the event, the second dimension is the information needed
4984     * to fire the hook.  Each entry in the top level array should be defined on a single line to make it
4985     * easier to automatically replace this file.  There should be no contents of this file that are not replacable.
4986     *
4987     * $hook_array['before_save'][] = Array(1, testtype, 'custom/modules/Leads/test12.php', 'TestClass', 'lead_before_save_1');
4988     * This sample line creates a before_save hook.  The hooks are procesed in the order in which they
4989     * are added to the array.  The second dimension is an array of:
4990     *           processing index (for sorting before exporting the array)
4991     *           A logic type hook
4992     *           label/type
4993     *           php file to include
4994     *           php class the method is in
4995     *           php method to call
4996     *
4997     * The method signature for version 1 hooks is:
4998     * function NAME(&$bean, $event, $arguments)
4999     *           $bean - $this bean passed in by reference.
5000     *           $event - The string for the current event (i.e. before_save)
5001     *           $arguments - An array of arguments that are specific to the event.
5002     */
5003     function call_custom_logic($event, $arguments = null)
5004     {
5005         if(!isset($this->processed) || $this->processed == false){
5006             //add some logic to ensure we do not get into an infinite loop
5007             if(!empty($this->logicHookDepth[$event])) {
5008                 if($this->logicHookDepth[$event] > $this->max_logic_depth)
5009                     return;
5010             }else
5011                 $this->logicHookDepth[$event] = 0;
5012
5013             //we have to put the increment operator here
5014             //otherwise we may never increase the depth for that event in the case
5015             //where one event will trigger another as in the case of before_save and after_save
5016             //Also keeping the depth per event allow any number of hooks to be called on the bean
5017             //and we only will return if one event gets caught in a loop. We do not increment globally
5018             //for each event called.
5019             $this->logicHookDepth[$event]++;
5020
5021             //method defined in 'include/utils/LogicHook.php'
5022
5023             $logicHook = new LogicHook();
5024             $logicHook->setBean($this);
5025             $logicHook->call_custom_logic($this->module_dir, $event, $arguments);
5026             $this->logicHookDepth[$event]--;
5027         }
5028     }
5029
5030
5031     /*  When creating a custom field of type Dropdown, it creates an enum row in the DB.
5032      A typical get_list_view_array() result will have the *KEY* value from that drop-down.
5033      Since custom _dom objects are flat-files included in the $app_list_strings variable,
5034      We need to generate a key-key pair to get the true value like so:
5035      ([module]_cstm->fields_meta_data->$app_list_strings->*VALUE*)*/
5036     function getRealKeyFromCustomFieldAssignedKey($name)
5037     {
5038         if ($this->custom_fields->avail_fields[$name]['ext1'])
5039         {
5040             $realKey = 'ext1';
5041         }
5042         elseif ($this->custom_fields->avail_fields[$name]['ext2'])
5043         {
5044             $realKey = 'ext2';
5045         }
5046         elseif ($this->custom_fields->avail_fields[$name]['ext3'])
5047         {
5048             $realKey = 'ext3';
5049         }
5050         else
5051         {
5052             $GLOBALS['log']->fatal("SUGARBEAN: cannot find Real Key for custom field of type dropdown - cannot return Value.");
5053             return false;
5054         }
5055         if(isset($realKey))
5056         {
5057             return $this->custom_fields->avail_fields[$name][$realKey];
5058         }
5059     }
5060
5061     function bean_implements($interface)
5062     {
5063         return false;
5064     }
5065     /**
5066     * Check whether the user has access to a particular view for the current bean/module
5067     * @param $view string required, the view to determine access for i.e. DetailView, ListView...
5068     * @param $is_owner bool optional, this is part of the ACL check if the current user is an owner they will receive different access
5069     */
5070     function ACLAccess($view,$is_owner='not_set')
5071     {
5072         global $current_user;
5073         if($current_user->isAdminForModule($this->getACLCategory())) {
5074             return true;
5075         }
5076         $not_set = false;
5077         if($is_owner == 'not_set')
5078         {
5079             $not_set = true;
5080             $is_owner = $this->isOwner($current_user->id);
5081         }
5082
5083         // If we don't implement ACLs, return true.
5084         if(!$this->bean_implements('ACL'))
5085         return true;
5086         $view = strtolower($view);
5087         switch ($view)
5088         {
5089             case 'list':
5090             case 'index':
5091             case 'listview':
5092                 return ACLController::checkAccess($this->module_dir,'list', true);
5093             case 'edit':
5094             case 'save':
5095                 if( !$is_owner && $not_set && !empty($this->id)){
5096                     $class = get_class($this);
5097                     $temp = new $class();
5098                     if(!empty($this->fetched_row) && !empty($this->fetched_row['id']) && !empty($this->fetched_row['assigned_user_id']) && !empty($this->fetched_row['created_by'])){
5099                         $temp->populateFromRow($this->fetched_row);
5100                     }else{
5101                         $temp->retrieve($this->id);
5102                     }
5103                     $is_owner = $temp->isOwner($current_user->id);
5104                 }
5105             case 'popupeditview':
5106             case 'editview':
5107                 return ACLController::checkAccess($this->module_dir,'edit', $is_owner, $this->acltype);
5108             case 'view':
5109             case 'detail':
5110             case 'detailview':
5111                 return ACLController::checkAccess($this->module_dir,'view', $is_owner, $this->acltype);
5112             case 'delete':
5113                 return ACLController::checkAccess($this->module_dir,'delete', $is_owner, $this->acltype);
5114             case 'export':
5115                 return ACLController::checkAccess($this->module_dir,'export', $is_owner, $this->acltype);
5116             case 'import':
5117                 return ACLController::checkAccess($this->module_dir,'import', true, $this->acltype);
5118         }
5119         //if it is not one of the above views then it should be implemented on the page level
5120         return true;
5121     }
5122
5123     /**
5124     * Get owner field
5125     *
5126     * @return STRING
5127     */
5128     function getOwnerField($returnFieldName = false)
5129     {
5130         if (isset($this->field_defs['assigned_user_id']))
5131         {
5132             return $returnFieldName? 'assigned_user_id': $this->assigned_user_id;
5133         }
5134
5135         if (isset($this->field_defs['created_by']))
5136         {
5137             return $returnFieldName? 'created_by': $this->created_by;
5138         }
5139
5140         return '';
5141     }
5142
5143     /**
5144     * Returns true of false if the user_id passed is the owner
5145     *
5146     * @param GUID $user_id
5147     * @return boolean
5148     */
5149     function isOwner($user_id)
5150     {
5151         //if we don't have an id we must be the owner as we are creating it
5152         if(!isset($this->id))
5153         {
5154             return true;
5155         }
5156         //if there is an assigned_user that is the owner
5157         if(isset($this->assigned_user_id))
5158         {
5159             if($this->assigned_user_id == $user_id) return true;
5160             return false;
5161         }
5162         else
5163         {
5164             //other wise if there is a created_by that is the owner
5165             if(isset($this->created_by) && $this->created_by == $user_id)
5166             {
5167                 return true;
5168             }
5169         }
5170         return false;
5171     }
5172     /**
5173     * Gets there where statement for checking if a user is an owner
5174     *
5175     * @param GUID $user_id
5176     * @return STRING
5177     */
5178     function getOwnerWhere($user_id)
5179     {
5180         if(isset($this->field_defs['assigned_user_id']))
5181         {
5182             return " $this->table_name.assigned_user_id ='$user_id' ";
5183         }
5184         if(isset($this->field_defs['created_by']))
5185         {
5186             return " $this->table_name.created_by ='$user_id' ";
5187         }
5188         return '';
5189     }
5190
5191     /**
5192     *
5193     * Used in order to manage ListView links and if they should
5194     * links or not based on the ACL permissions of the user
5195     *
5196     * @return ARRAY of STRINGS
5197     */
5198     function listviewACLHelper()
5199     {
5200         $array_assign = array();
5201         if($this->ACLAccess('DetailView'))
5202         {
5203             $array_assign['MAIN'] = 'a';
5204         }
5205         else
5206         {
5207             $array_assign['MAIN'] = 'span';
5208         }
5209         return $array_assign;
5210     }
5211
5212     /**
5213     * returns this bean as an array
5214     *
5215     * @return array of fields with id, name, access and category
5216     */
5217     function toArray($dbOnly = false, $stringOnly = false, $upperKeys=false)
5218     {
5219         static $cache = array();
5220         $arr = array();
5221
5222         foreach($this->field_defs as $field=>$data)
5223         {
5224             if( !$dbOnly || !isset($data['source']) || $data['source'] == 'db')
5225             if(!$stringOnly || is_string($this->$field))
5226             if($upperKeys)
5227             {
5228                                 if(!isset($cache[$field])){
5229                                     $cache[$field] = strtoupper($field);
5230                                 }
5231                 $arr[$cache[$field]] = $this->$field;
5232             }
5233             else
5234             {
5235                 if(isset($this->$field)){
5236                     $arr[$field] = $this->$field;
5237                 }else{
5238                     $arr[$field] = '';
5239                 }
5240             }
5241         }
5242         return $arr;
5243     }
5244
5245     /**
5246     * Converts an array into an acl mapping name value pairs into files
5247     *
5248     * @param Array $arr
5249     */
5250     function fromArray($arr)
5251     {
5252         foreach($arr as $name=>$value)
5253         {
5254             $this->$name = $value;
5255         }
5256     }
5257
5258     /**
5259      * Convert row data from DB format to internal format
5260      * Mostly useful for dates/times
5261      * @param array $row
5262      * @return array $row
5263      */
5264     public function convertRow($row)
5265     {
5266         foreach($this->field_defs as $name => $fieldDef)
5267                 {
5268                     // skip empty fields and non-db fields
5269             if (isset($name) && !empty($row[$name])) {
5270                 $row[$name] = $this->convertField($row[$name], $fieldDef);
5271             }
5272         }
5273                 return $row;
5274     }
5275
5276     /**
5277      * Converts the field value based on the provided fieldDef
5278      * @param $fieldvalue
5279      * @param $fieldDef
5280      * @return string
5281      */
5282     public function convertField($fieldvalue, $fieldDef)
5283     {
5284         if (!empty($fieldvalue)) {
5285             if (!(isset($fieldDef['source']) &&
5286                 !in_array($fieldDef['source'], array('db', 'custom_fields', 'relate'))
5287                 && !isset($fieldDef['dbType']))
5288             ) {
5289                 // fromConvert other fields
5290                 $fieldvalue = $this->db->fromConvert($fieldvalue, $this->db->getFieldType($fieldDef));
5291             }
5292         }
5293         return $fieldvalue;
5294     }
5295
5296     /**
5297      * Loads a row of data into instance of a bean. The data is passed as an array to this function
5298      *
5299      * @param array $arr row of data fetched from the database.
5300      * @return  nothing
5301      *
5302      * Internal function do not override.
5303      */
5304     function loadFromRow($arr)
5305     {
5306         $this->populateFromRow($arr);
5307         $this->processed_dates_times = array();
5308         $this->check_date_relationships_load();
5309
5310         $this->fill_in_additional_list_fields();
5311
5312         if($this->hasCustomFields())$this->custom_fields->fill_relationships();
5313         $this->call_custom_logic("process_record");
5314     }
5315
5316     function hasCustomFields()
5317     {
5318         return !empty($GLOBALS['dictionary'][$this->object_name]['custom_fields']);
5319     }
5320
5321    /**
5322     * Ensure that fields within order by clauses are properly qualified with
5323     * their tablename.  This qualification is a requirement for sql server support.
5324     *
5325     * @param string $order_by original order by from the query
5326     * @param string $qualify prefix for columns in the order by list.
5327     * @return  prefixed
5328     *
5329     * Internal function do not override.
5330     */
5331    function create_qualified_order_by( $order_by, $qualify)
5332    {    // 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
5333     if (empty($order_by))
5334     {
5335         return $order_by;
5336     }
5337     $order_by_clause = " ORDER BY ";
5338     $tmp = explode(",", $order_by);
5339     $comma = ' ';
5340     foreach ( $tmp as $stmp)
5341     {
5342         $stmp = (substr_count($stmp, ".") > 0?trim($stmp):"$qualify." . trim($stmp));
5343         $order_by_clause .= $comma . $stmp;
5344         $comma = ", ";
5345     }
5346     return $order_by_clause;
5347    }
5348
5349    /**
5350     * Combined the contents of street field 2 thru 4 into the main field
5351     *
5352     * @param string $street_field
5353     */
5354
5355    function add_address_streets(
5356        $street_field
5357        )
5358     {
5359         $street_field_2 = $street_field.'_2';
5360         $street_field_3 = $street_field.'_3';
5361         $street_field_4 = $street_field.'_4';
5362         if ( isset($this->$street_field_2)) {
5363             $this->$street_field .= "\n". $this->$street_field_2;
5364             unset($this->$street_field_2);
5365         }
5366         if ( isset($this->$street_field_3)) {
5367             $this->$street_field .= "\n". $this->$street_field_3;
5368             unset($this->$street_field_3);
5369         }
5370         if ( isset($this->$street_field_4)) {
5371             $this->$street_field .= "\n". $this->$street_field_4;
5372             unset($this->$street_field_4);
5373         }
5374         if ( isset($this->$street_field)) {
5375             $this->$street_field = trim($this->$street_field, "\n");
5376         }
5377     }
5378
5379     protected function getEncryptKey()
5380     {
5381         if(empty(self::$field_key)) {
5382             self::$field_key = blowfishGetKey('encrypt_field');
5383         }
5384         return self::$field_key;
5385     }
5386
5387 /**
5388  * Encrpyt and base64 encode an 'encrypt' field type in the bean using Blowfish. The default system key is stored in cache/Blowfish/{keytype}
5389  * @param STRING value -plain text value of the bean field.
5390  * @return string
5391  */
5392     function encrpyt_before_save($value)
5393     {
5394         require_once("include/utils/encryption_utils.php");
5395         return blowfishEncode($this->getEncryptKey(), $value);
5396     }
5397
5398 /**
5399  * Decode and decrypt a base 64 encoded string with field type 'encrypt' in this bean using Blowfish.
5400  * @param STRING value - an encrypted and base 64 encoded string.
5401  * @return string
5402  */
5403     function decrypt_after_retrieve($value)
5404     {
5405         if(empty($value)) return $value; // no need to decrypt empty
5406         require_once("include/utils/encryption_utils.php");
5407         return blowfishDecode($this->getEncryptKey(), $value);
5408     }
5409
5410     /**
5411     * Moved from save() method, functionality is the same, but this is intended to handle
5412     * Optimistic locking functionality.
5413     */
5414     private function _checkOptimisticLocking($action, $isUpdate){
5415         if($this->optimistic_lock && !isset($_SESSION['o_lock_fs'])){
5416             if(isset($_SESSION['o_lock_id']) && $_SESSION['o_lock_id'] == $this->id && $_SESSION['o_lock_on'] == $this->object_name)
5417             {
5418                 if($action == 'Save' && $isUpdate && isset($this->modified_user_id) && $this->has_been_modified_since($_SESSION['o_lock_dm'], $this->modified_user_id))
5419                 {
5420                     $_SESSION['o_lock_class'] = get_class($this);
5421                     $_SESSION['o_lock_module'] = $this->module_dir;
5422                     $_SESSION['o_lock_object'] = $this->toArray();
5423                     $saveform = "<form name='save' id='save' method='POST'>";
5424                     foreach($_POST as $key=>$arg)
5425                     {
5426                         $saveform .= "<input type='hidden' name='". addslashes($key) ."' value='". addslashes($arg) ."'>";
5427                     }
5428                     $saveform .= "</form><script>document.getElementById('save').submit();</script>";
5429                     $_SESSION['o_lock_save'] = $saveform;
5430                     header('Location: index.php?module=OptimisticLock&action=LockResolve');
5431                     die();
5432                 }
5433                 else
5434                 {
5435                     unset ($_SESSION['o_lock_object']);
5436                     unset ($_SESSION['o_lock_id']);
5437                     unset ($_SESSION['o_lock_dm']);
5438                 }
5439             }
5440         }
5441         else
5442         {
5443             if(isset($_SESSION['o_lock_object']))       { unset ($_SESSION['o_lock_object']); }
5444             if(isset($_SESSION['o_lock_id']))           { unset ($_SESSION['o_lock_id']); }
5445             if(isset($_SESSION['o_lock_dm']))           { unset ($_SESSION['o_lock_dm']); }
5446             if(isset($_SESSION['o_lock_fs']))           { unset ($_SESSION['o_lock_fs']); }
5447             if(isset($_SESSION['o_lock_save']))         { unset ($_SESSION['o_lock_save']); }
5448         }
5449     }
5450
5451     /**
5452     * Send assignment notifications and invites for meetings and calls
5453     */
5454     private function _sendNotifications($check_notify){
5455         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.
5456            && !$this->isOwner($this->created_by) )  // cn: bug 42727 no need to send email to owner (within workflow)
5457         {
5458             $admin = new Administration();
5459             $admin->retrieveSettings();
5460             $sendNotifications = false;
5461
5462             if ($admin->settings['notify_on'])
5463             {
5464                 $GLOBALS['log']->info("Notifications: user assignment has changed, checking if user receives notifications");
5465                 $sendNotifications = true;
5466             }
5467             elseif(isset($_REQUEST['send_invites']) && $_REQUEST['send_invites'] == 1)
5468             {
5469                 // cn: bug 5795 Send Invites failing for Contacts
5470                 $sendNotifications = true;
5471             }
5472             else
5473             {
5474                 $GLOBALS['log']->info("Notifications: not sending e-mail, notify_on is set to OFF");
5475             }
5476
5477
5478             if($sendNotifications == true)
5479             {
5480                 $notify_list = $this->get_notification_recipients();
5481                 foreach ($notify_list as $notify_user)
5482                 {
5483                     $this->send_assignment_notifications($notify_user, $admin);
5484                 }
5485             }
5486         }
5487     }
5488
5489
5490     /**
5491      * Called from ImportFieldSanitize::relate(), when creating a new bean in a related module. Will
5492      * copies fields over from the current bean into the related. Designed to be overriden in child classes.
5493      *
5494      * @param SugarBean $newbean newly created related bean
5495      */
5496     public function populateRelatedBean(
5497         SugarBean $newbean
5498         )
5499     {
5500     }
5501
5502     /**
5503      * Called during the import process before a bean save, to handle any needed pre-save logic when
5504      * importing a record
5505      */
5506     public function beforeImportSave()
5507     {
5508     }
5509
5510     /**
5511      * Called during the import process after a bean save, to handle any needed post-save logic when
5512      * importing a record
5513      */
5514     public function afterImportSave()
5515     {
5516     }
5517
5518     /**
5519      * This function is designed to cache references to field arrays that were previously stored in the
5520      * bean files and have since been moved to separate files. Was previously in include/CacheHandler.php
5521      *
5522      * @deprecated
5523      * @param $module_dir string the module directory
5524      * @param $module string the name of the module
5525      * @param $key string the type of field array we are referencing, i.e. list_fields, column_fields, required_fields
5526      **/
5527     private function _loadCachedArray(
5528         $module_dir,
5529         $module,
5530         $key
5531         )
5532     {
5533         static $moduleDefs = array();
5534
5535         $fileName = 'field_arrays.php';
5536
5537         $cache_key = "load_cached_array.$module_dir.$module.$key";
5538         $result = sugar_cache_retrieve($cache_key);
5539         if(!empty($result))
5540         {
5541                 // Use SugarCache::EXTERNAL_CACHE_NULL_VALUE to store null values in the cache.
5542                 if($result == SugarCache::EXTERNAL_CACHE_NULL_VALUE)
5543                 {
5544                         return null;
5545                 }
5546
5547             return $result;
5548         }
5549
5550         if(file_exists('modules/'.$module_dir.'/'.$fileName))
5551         {
5552             // If the data was not loaded, try loading again....
5553             if(!isset($moduleDefs[$module]))
5554             {
5555                 include('modules/'.$module_dir.'/'.$fileName);
5556                 $moduleDefs[$module] = $fields_array;
5557             }
5558             // Now that we have tried loading, make sure it was loaded
5559             if(empty($moduleDefs[$module]) || empty($moduleDefs[$module][$module][$key]))
5560             {
5561                 // It was not loaded....  Fail.  Cache null to prevent future repeats of this calculation
5562                                 sugar_cache_put($cache_key, SugarCache::EXTERNAL_CACHE_NULL_VALUE);
5563                 return  null;
5564             }
5565
5566             // It has been loaded, cache the result.
5567             sugar_cache_put($cache_key, $moduleDefs[$module][$module][$key]);
5568             return $moduleDefs[$module][$module][$key];
5569         }
5570
5571         // It was not loaded....  Fail.  Cache null to prevent future repeats of this calculation
5572         sugar_cache_put($cache_key, SugarCache::EXTERNAL_CACHE_NULL_VALUE);
5573                 return null;
5574         }
5575
5576     /**
5577      * Returns the ACL category for this module; defaults to the SugarBean::$acl_category if defined
5578      * otherwise it is SugarBean::$module_dir
5579      *
5580      * @return string
5581      */
5582     public function getACLCategory()
5583     {
5584         return !empty($this->acl_category)?$this->acl_category:$this->module_dir;
5585     }
5586
5587     /**
5588      * Returns the query used for the export functionality for a module. Override this method if you wish
5589      * to have a custom query to pull this data together instead
5590      *
5591      * @param string $order_by
5592      * @param string $where
5593      * @return string SQL query
5594      */
5595         public function create_export_query($order_by, $where)
5596         {
5597                 return $this->create_new_list_query($order_by, $where, array(), array(), 0, '', false, $this, true, true);
5598         }
5599
5600     /**
5601      * Determine whether the given field is a relate field
5602      *
5603      * @param string $field Field name
5604      * @return bool
5605      */
5606     protected function is_relate_field($field)
5607     {
5608         if (!isset($this->field_defs[$field]))
5609         {
5610             return false;
5611         }
5612
5613         $field_def = $this->field_defs[$field];
5614
5615         return isset($field_def['type'])
5616             && $field_def['type'] == 'relate'
5617             && isset($field_def['link']);
5618     }
5619 }