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