forked from bkilgore/sugarcrm_dev
/
SugarBean.php
5909 lines (5350 loc) · 224 KB
/
SugarBean.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Description: Defines the base class for all data entities used throughout the
* application. The base class including its methods and variables is designed to
* be overloaded with module-specific methods and variables particular to the
* module's base entity class.
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
*******************************************************************************/
require_once('modules/DynamicFields/DynamicField.php');
require_once("data/Relationships/RelationshipFactory.php");
/**
* SugarBean is the base class for all business objects in Sugar. It implements
* the primary functionality needed for manipulating business objects: create,
* retrieve, update, delete. It allows for searching and retrieving list of records.
* It allows for retrieving related objects (e.g. contacts related to a specific account).
*
* In the current implementation, there can only be one bean per folder.
* Naming convention has the bean name be the same as the module and folder name.
* All bean names should be singular (e.g. Contact). The primary table name for
* a bean should be plural (e.g. contacts).
* @api
*/
class SugarBean
{
/**
* A pointer to the database object
*
* @var DBManager
*/
var $db;
/**
* Unique object identifier
*
* @var string
*/
public $id;
/**
* When createing a bean, you can specify a value in the id column as
* long as that value is unique. During save, if the system finds an
* id, it assumes it is an update. Setting new_with_id to true will
* make sure the system performs an insert instead of an update.
*
* @var BOOL -- default false
*/
var $new_with_id = false;
/**
* How deep logic hooks can go
* @var int
*/
protected $max_logic_depth = 10;
/**
* Disble vardefs. This should be set to true only for beans that do not have varders. Tracker is an example
*
* @var BOOL -- default false
*/
var $disable_vardefs = false;
/**
* holds the full name of the user that an item is assigned to. Only used if notifications
* are turned on and going to be sent out.
*
* @var String
*/
var $new_assigned_user_name;
/**
* An array of booleans. This array is cleared out when data is loaded.
* As date/times are converted, a "1" is placed under the key, the field is converted.
*
* @var Array of booleans
*/
var $processed_dates_times = array();
/**
* Whether to process date/time fields for storage in the database in GMT
*
* @var BOOL
*/
var $process_save_dates =true;
/**
* This signals to the bean that it is being saved in a mass mode.
* Examples of this kind of save are import and mass update.
* We turn off notificaitons of this is the case to make things more efficient.
*
* @var BOOL
*/
var $save_from_post = true;
/**
* When running a query on related items using the method: retrieve_by_string_fields
* this value will be set to true if more than one item matches the search criteria.
*
* @var BOOL
*/
var $duplicates_found = false;
/**
* true if this bean has been deleted, false otherwise.
*
* @var BOOL
*/
var $deleted = 0;
/**
* Should the date modified column of the bean be updated during save?
* This is used for admin level functionality that should not be updating
* the date modified. This is only used by sync to allow for updates to be
* replicated in a way that will not cause them to be replicated back.
*
* @var BOOL
*/
var $update_date_modified = true;
/**
* Should the modified by column of the bean be updated during save?
* This is used for admin level functionality that should not be updating
* the modified by column. This is only used by sync to allow for updates to be
* replicated in a way that will not cause them to be replicated back.
*
* @var BOOL
*/
var $update_modified_by = true;
/**
* Setting this to true allows for updates to overwrite the date_entered
*
* @var BOOL
*/
var $update_date_entered = false;
/**
* This allows for seed data to be created without using the current uesr to set the id.
* This should be replaced by altering the current user before the call to save.
*
* @var unknown_type
*/
//TODO This should be replaced by altering the current user before the call to save.
var $set_created_by = true;
var $team_set_id;
/**
* The database table where records of this Bean are stored.
*
* @var String
*/
var $table_name = '';
/**
* This is the singular name of the bean. (i.e. Contact).
*
* @var String
*/
var $object_name = '';
/** Set this to true if you query contains a sub-select and bean is converting both select statements
* into count queries.
*/
var $ungreedy_count=false;
/**
* The name of the module folder for this type of bean.
*
* @var String
*/
var $module_dir = '';
var $module_name = '';
var $field_name_map;
var $field_defs;
var $custom_fields;
var $column_fields = array();
var $list_fields = array();
var $additional_column_fields = array();
var $relationship_fields = array();
var $current_notify_user;
var $fetched_row=false;
var $fetched_rel_row = array();
var $layout_def;
var $force_load_details = false;
var $optimistic_lock = false;
var $disable_custom_fields = false;
var $number_formatting_done = false;
var $process_field_encrypted=false;
/*
* The default ACL type
*/
var $acltype = 'module';
var $additional_meta_fields = array();
/**
* Set to true in the child beans if the module supports importing
*/
var $importable = false;
/**
* Set to true in the child beans if the module use the special notification template
*/
var $special_notification = false;
/**
* Set to true if the bean is being dealt with in a workflow
*/
var $in_workflow = false;
/**
*
* By default it will be true but if any module is to be kept non visible
* to tracker, then its value needs to be overriden in that particular module to false.
*
*/
var $tracker_visibility = true;
/**
* Used to pass inner join string to ListView Data.
*/
var $listview_inner_join = array();
/**
* Set to true in <modules>/Import/views/view.step4.php if a module is being imported
*/
var $in_import = false;
/**
* A way to keep track of the loaded relationships so when we clone the object we can unset them.
*
* @var array
*/
protected $loaded_relationships = array();
/**
* set to true if dependent fields updated
*/
protected $is_updated_dependent_fields = false;
/**
* Blowfish encryption key
* @var string
*/
static protected $field_key;
/**
* Cache of fields which can contain files
*
* @var array
*/
static protected $fileFields = array();
/**
* Constructor for the bean, it performs following tasks:
*
* 1. Initalized a database connections
* 2. Load the vardefs for the module implemeting the class. cache the entries
* if needed
* 3. Setup row-level security preference
* All implementing classes must call this constructor using the parent::SugarBean() class.
*
*/
function SugarBean()
{
global $dictionary, $current_user;
static $loaded_defs = array();
$this->db = DBManagerFactory::getInstance();
if (empty($this->module_name))
$this->module_name = $this->module_dir;
if((false == $this->disable_vardefs && empty($loaded_defs[$this->object_name])) || !empty($GLOBALS['reload_vardefs']))
{
VardefManager::loadVardef($this->module_dir, $this->object_name);
// build $this->column_fields from the field_defs if they exist
if (!empty($dictionary[$this->object_name]['fields'])) {
foreach ($dictionary[$this->object_name]['fields'] as $key=>$value_array) {
$column_fields[] = $key;
if(!empty($value_array['required']) && !empty($value_array['name'])) {
$this->required_fields[$value_array['name']] = 1;
}
}
$this->column_fields = $column_fields;
}
//setup custom fields
if(!isset($this->custom_fields) &&
empty($this->disable_custom_fields))
{
$this->setupCustomFields($this->module_dir);
}
//load up field_arrays from CacheHandler;
if(empty($this->list_fields))
$this->list_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'list_fields');
if(empty($this->column_fields))
$this->column_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'column_fields');
if(empty($this->required_fields))
$this->required_fields = $this->_loadCachedArray($this->module_dir, $this->object_name, 'required_fields');
if(isset($GLOBALS['dictionary'][$this->object_name]) && !$this->disable_vardefs)
{
$this->field_name_map = $dictionary[$this->object_name]['fields'];
$this->field_defs = $dictionary[$this->object_name]['fields'];
if(!empty($dictionary[$this->object_name]['optimistic_locking']))
{
$this->optimistic_lock=true;
}
}
$loaded_defs[$this->object_name]['column_fields'] =& $this->column_fields;
$loaded_defs[$this->object_name]['list_fields'] =& $this->list_fields;
$loaded_defs[$this->object_name]['required_fields'] =& $this->required_fields;
$loaded_defs[$this->object_name]['field_name_map'] =& $this->field_name_map;
$loaded_defs[$this->object_name]['field_defs'] =& $this->field_defs;
}
else
{
$this->column_fields =& $loaded_defs[$this->object_name]['column_fields'] ;
$this->list_fields =& $loaded_defs[$this->object_name]['list_fields'];
$this->required_fields =& $loaded_defs[$this->object_name]['required_fields'];
$this->field_name_map =& $loaded_defs[$this->object_name]['field_name_map'];
$this->field_defs =& $loaded_defs[$this->object_name]['field_defs'];
$this->added_custom_field_defs = true;
if(!isset($this->custom_fields) &&
empty($this->disable_custom_fields))
{
$this->setupCustomFields($this->module_dir, false);
}
if(!empty($dictionary[$this->object_name]['optimistic_locking']))
{
$this->optimistic_lock=true;
}
}
if($this->bean_implements('ACL') && !empty($GLOBALS['current_user'])){
$this->acl_fields = (isset($dictionary[$this->object_name]['acl_fields']) && $dictionary[$this->object_name]['acl_fields'] === false)?false:true;
}
$this->populateDefaultValues();
}
/**
* Returns the object name. If object_name is not set, table_name is returned.
*
* All implementing classes must set a value for the object_name variable.
*
* @param array $arr row of data fetched from the database.
* @return nothing
*
*/
function getObjectName()
{
if ($this->object_name)
return $this->object_name;
// This is a quick way out. The generated metadata files have the table name
// as the key. The correct way to do this is to override this function
// in bean and return the object name. That requires changing all the beans
// as well as put the object name in the generator.
return $this->table_name;
}
/**
* Returns a list of fields with their definitions that have the audited property set to true.
* Before calling this function, check whether audit has been enabled for the table/module or not.
* You would set the audit flag in the implemting module's vardef file.
*
* @return array
* @see is_AuditEnabled
*
* Internal function, do not override.
*/
function getAuditEnabledFieldDefinitions()
{
$aclcheck = $this->bean_implements('ACL');
$is_owner = $this->isOwner($GLOBALS['current_user']->id);
if (!isset($this->audit_enabled_fields))
{
$this->audit_enabled_fields=array();
foreach ($this->field_defs as $field => $properties)
{
if (
(
!empty($properties['Audited']) || !empty($properties['audited']))
)
{
$this->audit_enabled_fields[$field]=$properties;
}
}
}
return $this->audit_enabled_fields;
}
/**
* Return true if auditing is enabled for this object
* You would set the audit flag in the implemting module's vardef file.
*
* @return boolean
*
* Internal function, do not override.
*/
function is_AuditEnabled()
{
global $dictionary;
if (isset($dictionary[$this->getObjectName()]['audited']))
{
return $dictionary[$this->getObjectName()]['audited'];
}
else
{
return false;
}
}
/**
* Returns the name of the audit table.
* Audit table's name is based on implementing class' table name.
*
* @return String Audit table name.
*
* Internal function, do not override.
*/
function get_audit_table_name()
{
return $this->getTableName().'_audit';
}
/**
* Returns the name of the custom table.
* Custom table's name is based on implementing class' table name.
*
* @return String Custom table name.
*
* Internal function, do not override.
*/
public function get_custom_table_name()
{
return $this->getTableName().'_cstm';
}
/**
* If auditing is enabled, create the audit table.
*
* Function is used by the install scripts and a repair utility in the admin panel.
*
* Internal function, do not override.
*/
function create_audit_table()
{
global $dictionary;
$table_name=$this->get_audit_table_name();
require('metadata/audit_templateMetaData.php');
// Bug: 52583 Need ability to customize template for audit tables
$custom = 'custom/metadata/audit_templateMetaData_' . $this->getTableName() . '.php';
if (file_exists($custom))
{
require($custom);
}
$fieldDefs = $dictionary['audit']['fields'];
$indices = $dictionary['audit']['indices'];
// Renaming template indexes to fit the particular audit table (removed the brittle hard coding)
foreach($indices as $nr => $properties){
$indices[$nr]['name'] = 'idx_' . strtolower($this->getTableName()) . '_' . $properties['name'];
}
$engine = null;
if(isset($dictionary['audit']['engine'])) {
$engine = $dictionary['audit']['engine'];
} else if(isset($dictionary[$this->getObjectName()]['engine'])) {
$engine = $dictionary[$this->getObjectName()]['engine'];
}
$this->db->createTableParams($table_name, $fieldDefs, $indices, $engine);
}
/**
* Returns the implementing class' table name.
*
* All implementing classes set a value for the table_name variable. This value is returned as the
* table name. If not set, table name is extracted from the implementing module's vardef.
*
* @return String Table name.
*
* Internal function, do not override.
*/
public function getTableName()
{
if(isset($this->table_name))
{
return $this->table_name;
}
global $dictionary;
return $dictionary[$this->getObjectName()]['table'];
}
/**
* Returns field definitions for the implementing module.
*
* The definitions were loaded in the constructor.
*
* @return Array Field definitions.
*
* Internal function, do not override.
*/
function getFieldDefinitions()
{
return $this->field_defs;
}
/**
* Returns index definitions for the implementing module.
*
* The definitions were loaded in the constructor.
*
* @return Array Index definitions.
*
* Internal function, do not override.
*/
function getIndices()
{
global $dictionary;
if(isset($dictionary[$this->getObjectName()]['indices']))
{
return $dictionary[$this->getObjectName()]['indices'];
}
return array();
}
/**
* Returns field definition for the requested field name.
*
* The definitions were loaded in the constructor.
*
* @param string field name,
* @return Array Field properties or boolean false if the field doesn't exist
*
* Internal function, do not override.
*/
function getFieldDefinition($name)
{
if ( !isset($this->field_defs[$name]) )
return false;
return $this->field_defs[$name];
}
/**
* Returnss definition for the id field name.
*
* The definitions were loaded in the constructor.
*
* @return Array Field properties.
*
* Internal function, do not override.
*/
function getPrimaryFieldDefinition()
{
$def = $this->getFieldDefinition("id");
if(empty($def)) {
$def = $this->getFieldDefinition(0);
}
if (empty($def)) {
$defs = $this->field_defs;
reset($defs);
$def = current($defs);
}
return $def;
}
/**
* Returns the value for the requested field.
*
* When a row of data is fetched using the bean, all fields are created as variables in the context
* of the bean and then fetched values are set in these variables.
*
* @param string field name,
* @return varies Field value.
*
* Internal function, do not override.
*/
function getFieldValue($name)
{
if (!isset($this->$name)){
return FALSE;
}
if($this->$name === TRUE){
return 1;
}
if($this->$name === FALSE){
return 0;
}
return $this->$name;
}
/**
* Basically undoes the effects of SugarBean::populateDefaultValues(); this method is best called right after object
* initialization.
*/
public function unPopulateDefaultValues()
{
if ( !is_array($this->field_defs) )
return;
foreach ($this->field_defs as $field => $value) {
if( !empty($this->$field)
&& ((isset($value['default']) && $this->$field == $value['default']) || (!empty($value['display_default']) && $this->$field == $value['display_default']))
) {
$this->$field = null;
continue;
}
if(!empty($this->$field) && !empty($value['display_default']) && in_array($value['type'], array('date', 'datetime', 'datetimecombo')) &&
$this->$field == $this->parseDateDefault($value['display_default'], ($value['type'] != 'date'))) {
$this->$field = null;
}
}
}
/**
* Create date string from default value
* like '+1 month'
* @param string $value
* @param bool $time Should be expect time set too?
* @return string
*/
protected function parseDateDefault($value, $time = false)
{
global $timedate;
if($time) {
$dtAry = explode('&', $value, 2);
$dateValue = $timedate->getNow(true)->modify($dtAry[0]);
if(!empty($dtAry[1])) {
$timeValue = $timedate->fromString($dtAry[1]);
$dateValue->setTime($timeValue->hour, $timeValue->min, $timeValue->sec);
}
return $timedate->asUser($dateValue);
} else {
return $timedate->asUserDate($timedate->getNow(true)->modify($value));
}
}
function populateDefaultValues($force=false){
if ( !is_array($this->field_defs) )
return;
foreach($this->field_defs as $field=>$value){
if((isset($value['default']) || !empty($value['display_default'])) && ($force || empty($this->$field))){
$type = $value['type'];
switch($type){
case 'date':
if(!empty($value['display_default'])){
$this->$field = $this->parseDateDefault($value['display_default']);
}
break;
case 'datetime':
case 'datetimecombo':
if(!empty($value['display_default'])){
$this->$field = $this->parseDateDefault($value['display_default'], true);
}
break;
case 'multienum':
if(empty($value['default']) && !empty($value['display_default']))
$this->$field = $value['display_default'];
else
$this->$field = $value['default'];
break;
case 'bool':
if(isset($this->$field)){
break;
}
default:
if ( isset($value['default']) && $value['default'] !== '' ) {
$this->$field = htmlentities($value['default'], ENT_QUOTES, 'UTF-8');
} else {
$this->$field = '';
}
} //switch
}
} //foreach
}
/**
* Removes relationship metadata cache.
*
* Every module that has relationships defined with other modules, has this meta data cached. The cache is
* stores in 2 locations: relationships table and file system. This method clears the cache from both locations.
*
* @param string $key module whose meta cache is to be cleared.
* @param string $db database handle.
* @param string $tablename table name
* @param string $dictionary vardef for the module
* @param string $module_dir name of subdirectory where module is installed.
*
* @return Nothing
* @static
*
* Internal function, do not override.
*/
function removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir)
{
//load the module dictionary if not supplied.
if ((!isset($dictionary) or empty($dictionary)) && !empty($module_dir))
{
$filename='modules/'. $module_dir . '/vardefs.php';
if(file_exists($filename))
{
include($filename);
}
}
if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
{
$GLOBALS['log']->fatal("removeRelationshipMeta: Metadata for table ".$tablename. " does not exist");
display_notice("meta data absent for table ".$tablename." keyed to $key ");
}
else
{
if (isset($dictionary[$key]['relationships']))
{
$RelationshipDefs = $dictionary[$key]['relationships'];
foreach ($RelationshipDefs as $rel_name)
{
Relationship::delete($rel_name,$db);
}
}
}
}
/**
* This method has been deprecated.
*
* @see removeRelationshipMeta()
* @deprecated 4.5.1 - Nov 14, 2006
* @static
*/
function remove_relationship_meta($key,$db,$log,$tablename,$dictionary,$module_dir)
{
SugarBean::removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
}
/**
* Populates the relationship meta for a module.
*
* It is called during setup/install. It is used statically to create relationship meta data for many-to-many tables.
*
* @param string $key name of the object.
* @param object $db database handle.
* @param string $tablename table, meta data is being populated for.
* @param array dictionary vardef dictionary for the object. *
* @param string module_dir name of subdirectory where module is installed.
* @param boolean $iscustom Optional,set to true if module is installed in a custom directory. Default value is false.
* @static
*
* Internal function, do not override.
*/
function createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir,$iscustom=false)
{
//load the module dictionary if not supplied.
if (empty($dictionary) && !empty($module_dir))
{
if($iscustom)
{
$filename='custom/modules/' . $module_dir . '/Ext/Vardefs/vardefs.ext.php';
}
else
{
if ($key == 'User')
{
// a very special case for the Employees module
// this must be done because the Employees/vardefs.php does an include_once on
// Users/vardefs.php
$filename='modules/Users/vardefs.php';
}
else
{
$filename='modules/'. $module_dir . '/vardefs.php';
}
}
if(file_exists($filename))
{
include($filename);
// cn: bug 7679 - dictionary entries defined as $GLOBALS['name'] not found
if(empty($dictionary) || !empty($GLOBALS['dictionary'][$key]))
{
$dictionary = $GLOBALS['dictionary'];
}
}
else
{
$GLOBALS['log']->debug("createRelationshipMeta: no metadata file found" . $filename);
return;
}
}
if (!is_array($dictionary) or !array_key_exists($key, $dictionary))
{
$GLOBALS['log']->fatal("createRelationshipMeta: Metadata for table ".$tablename. " does not exist");
display_notice("meta data absent for table ".$tablename." keyed to $key ");
}
else
{
if (isset($dictionary[$key]['relationships']))
{
$RelationshipDefs = $dictionary[$key]['relationships'];
$delimiter=',';
global $beanList;
$beanList_ucase=array_change_key_case ( $beanList ,CASE_UPPER);
foreach ($RelationshipDefs as $rel_name=>$rel_def)
{
if (isset($rel_def['lhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['lhs_module'])])) {
$GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' lhs module is missing ' . $rel_def['lhs_module']);
continue;
}
if (isset($rel_def['rhs_module']) and !isset($beanList_ucase[strtoupper($rel_def['rhs_module'])])) {
$GLOBALS['log']->debug('skipping orphaned relationship record ' . $rel_name . ' rhs module is missing ' . $rel_def['rhs_module']);
continue;
}
//check whether relationship exists or not first.
if (Relationship::exists($rel_name,$db))
{
$GLOBALS['log']->debug('Skipping, reltionship already exists '.$rel_name);
}
else
{
$seed = BeanFactory::getBean("Relationships");
$keys = array_keys($seed->field_defs);
$toInsert = array();
foreach($keys as $key)
{
if ($key == "id")
{
$toInsert[$key] = create_guid();
}
else if ($key == "relationship_name")
{
$toInsert[$key] = $rel_name;
}
else if (isset($rel_def[$key]))
{
$toInsert[$key] = $rel_def[$key];
}
//todo specify defaults if meta not defined.
}
$column_list = implode(",", array_keys($toInsert));
$value_list = "'" . implode("','", array_values($toInsert)) . "'";
//create the record. todo add error check.
$insert_string = "INSERT into relationships (" .$column_list. ") values (".$value_list.")";
$db->query($insert_string, true);
}
}
}
else
{
//todo
//log informational message stating no relationships meta was set for this bean.
}
}
}
/**
* This method has been deprecated.
* @see createRelationshipMeta()
* @deprecated 4.5.1 - Nov 14, 2006
* @static
*/
function create_relationship_meta($key,&$db,&$log,$tablename,$dictionary,$module_dir)
{
SugarBean::createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir);
}
/**
* Handle the following when a SugarBean object is cloned
*
* Currently all this does it unset any relationships that were created prior to cloning the object
*
* @api
*/
public function __clone()
{
if(!empty($this->loaded_relationships)) {
foreach($this->loaded_relationships as $rel) {
unset($this->$rel);
}
}
}
/**
* Loads the request relationship. This method should be called before performing any operations on the related data.
*
* This method searches the vardef array for the requested attribute's definition. If the attribute is of the type
* link then it creates a similary named variable and loads the relationship definition.
*
* @param string $rel_name relationship/attribute name.
* @return nothing.
*/
function load_relationship($rel_name)
{
$GLOBALS['log']->debug("SugarBean[{$this->object_name}].load_relationships, Loading relationship (".$rel_name.").");
if (empty($rel_name))
{
$GLOBALS['log']->error("SugarBean.load_relationships, Null relationship name passed.");
return false;
}
$fieldDefs = $this->getFieldDefinitions();
//find all definitions of type link.
if (!empty($fieldDefs[$rel_name]))
{
//initialize a variable of type Link
require_once('data/Link2.php');
$class = load_link_class($fieldDefs[$rel_name]);
if (isset($this->$rel_name) && $this->$rel_name instanceof $class) {
return true;
}
//if rel_name is provided, search the fieldef array keys by name.
if (isset($fieldDefs[$rel_name]['type']) && $fieldDefs[$rel_name]['type'] == 'link')
{
if ($class == "Link2")
$this->$rel_name = new $class($rel_name, $this);
else
$this->$rel_name = new $class($fieldDefs[$rel_name]['relationship'], $this, $fieldDefs[$rel_name]);
if (empty($this->$rel_name) ||
(method_exists($this->$rel_name, "loadedSuccesfully") && !$this->$rel_name->loadedSuccesfully()))
{
unset($this->$rel_name);
return false;
}
// keep track of the loaded relationships
$this->loaded_relationships[] = $rel_name;
return true;
}