]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/DynamicFields/DynamicField.php
Release 6.3.0
[Github/sugarcrm.git] / modules / DynamicFields / DynamicField.php
1 <?php
2 if (! defined ( 'sugarEntry' ) || ! sugarEntry)
3     die ( 'Not A Valid Entry Point' ) ;
4
5 /*********************************************************************************
6  * SugarCRM Community Edition is a customer relationship management program developed by
7  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8  * 
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU Affero General Public License version 3 as published by the
11  * Free Software Foundation with the addition of the following permission added
12  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
13  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
14  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
15  * 
16  * This program is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
19  * details.
20  * 
21  * You should have received a copy of the GNU Affero General Public License along with
22  * this program; if not, see http://www.gnu.org/licenses or write to the Free
23  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24  * 02110-1301 USA.
25  * 
26  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
27  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
28  * 
29  * The interactive user interfaces in modified source and object code versions
30  * of this program must display Appropriate Legal Notices, as required under
31  * Section 5 of the GNU Affero General Public License version 3.
32  * 
33  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
34  * these Appropriate Legal Notices must retain the display of the "Powered by
35  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
36  * technical reasons, the Appropriate Legal Notices must display the words
37  * "Powered by SugarCRM".
38  ********************************************************************************/
39
40
41 class DynamicField {
42
43     var $use_existing_labels = false; // this value is set to true by install_custom_fields() in ModuleInstaller.php; everything else expects it to be false
44     var $base_path = "";
45
46     function DynamicField($module = '') {
47         $this->module = (! empty ( $module )) ? $module :( (isset($_REQUEST['module']) && ! empty($_REQUEST['module'])) ? $_REQUEST ['module'] : '');
48         $this->base_path = "custom/Extension/modules/{$this->module}/Ext/Vardefs";
49     }
50
51    function getModuleName()
52     {
53         return $this->module ;
54     }
55
56     /*
57      * As DynamicField has a counterpart in MBModule, provide the MBModule function getPackagename() here also
58      */
59     function getPackageName()
60     {
61         return null ;
62     }
63
64     function deleteCache(){
65     }
66
67
68     /**
69     * This will add the bean as a reference in this object as well as building the custom field cache if it has not been built
70     * LOADS THE BEAN IF THE BEAN IS NOT BEING PASSED ALONG IN SETUP IT SHOULD BE SET PRIOR TO SETUP
71     *
72     * @param SUGARBEAN $bean
73     */
74     function setup($bean = null) {
75         if ($bean) {
76             $this->bean = $bean;
77         }
78         if (isset ( $this->bean->module_dir )) {
79             $this->module = $this->bean->module_dir;
80         }
81         if(!isset($GLOBALS['dictionary'][$this->bean->object_name]['custom_fields'])){
82             $this->buildCache ( $this->module );
83         }
84     }
85
86     function setLabel( $language='en_us' , $key , $value )
87     {
88         $params [ "label_" . $key ] = $value;
89         require_once 'modules/ModuleBuilder/parsers/parser.label.php' ;
90         $parser = new ParserLabel ( $this->module ) ;
91         $parser->handleSave( $params , $language);
92     }
93
94     /**
95     * Builds the cache for custom fields based on the vardefs
96     *
97     * @param STRING $module
98     * @return unknown
99     */
100     function buildCache($module = false) {
101         //We can't build the cache while installing as the required database tables may not exist.
102         if (!empty($GLOBALS['installing']) && $GLOBALS['installing'] == true|| !$GLOBALS['db'])
103             return false;
104         if($module == '../data')return false;
105
106         static $results = array ( ) ;
107
108         $where = '';
109         if (! empty ( $module )) {
110             $where .= " custom_module='$module' AND ";
111             unset( $results[ $module ] ) ; // clear out any old results for the module as $results is declared static
112         }
113         else
114         {
115             $results = array ( ) ; // clear out results - if we remove a module we don't want to have its old vardefs hanging around
116         }
117
118         $GLOBALS['log']->debug('rebuilding cache for ' . $module);
119         $query = "SELECT * FROM fields_meta_data WHERE $where deleted = 0";
120
121         $result = $GLOBALS['db']->query ( $query );
122         require_once ('modules/DynamicFields/FieldCases.php');
123
124         // retrieve the field definition from the fields_meta_data table
125         // using 'encode'=false to fetchByAssoc to prevent any pre-formatting of the base metadata
126         // for immediate use in HTML. This metadata will be further massaged by get_field_def() and so should not be pre-formatted
127         while ( $row = $GLOBALS['db']->fetchByAssoc ( $result , -1 ,false ) ) {
128             $field = get_widget ( $row ['type'] );
129
130             foreach ( $row as $key => $value ) {
131                 $field->$key = $value;
132             }
133             $field->default = $field->default_value;
134             $vardef = $field->get_field_def ();
135             $vardef ['id'] = $row ['id'];
136             $vardef ['custom_module'] = $row ['custom_module'];
137             if (empty ( $vardef ['source'] ))
138                 $vardef ['source'] = 'custom_fields';
139             if (empty ( $results [$row ['custom_module']] ))
140                 $results [$row ['custom_module']] = array ( );
141             $results [$row ['custom_module']] [$row ['name']] = $vardef;
142         }
143         if (empty ( $module )) {
144             foreach ( $results as $module => $result ) {
145                 $this->saveToVardef ( $module, $result );
146             }
147         } else {
148             if (! empty ( $results [$module] )) {
149                 $this->saveToVardef ( $module, $results [$module] );
150             }else{
151                 $this->saveToVardef ( $module, false );
152             }
153         }
154         return true;
155
156     }
157
158     /**
159     * Returns the widget for a custom field from the fields_meta_data table.
160     */
161     function getFieldWidget($module, $fieldName) {
162         if (empty($module) || empty($fieldName)){
163             sugar_die("Unable to load widget for '$module' : '$fieldName'");
164         }
165         $query = "SELECT * FROM fields_meta_data WHERE custom_module='$module' AND name='$fieldName' AND deleted = 0";
166         $result = $GLOBALS['db']->query ( $query );
167         require_once ('modules/DynamicFields/FieldCases.php');
168         if ( $row = $GLOBALS['db']->fetchByAssoc ( $result ) ) {
169             $field = get_widget ( $row ['type'] );
170             $field->populateFromRow($row);
171             return $field;
172         }
173     }
174
175
176     /**
177     * Updates the cached vardefs with the custom field information stored in result
178     *
179     * @param string $module
180     * @param array $result
181     */
182     function saveToVardef($module,$result) {
183
184         global $beanList;
185         if (! empty ( $beanList [$module] )) {
186             $object = BeanFactory::getObjectName($module);
187
188             if(empty($GLOBALS['dictionary'][$object]['fields'])){
189                 //if the vardef isn't loaded let's try loading it.
190                 VardefManager::refreshVardefs($module,$object, null, false);
191                 //if it's still not loaded we really don't have anything useful to cache
192                 if(empty($GLOBALS['dictionary'][$object]['fields']))return;
193             }
194             $GLOBALS ['dictionary'] [$object] ['custom_fields'] = false;
195             if (! empty ( $GLOBALS ['dictionary'] [$object] )) {
196                 if (! empty ( $result )) {
197                     // First loop to add
198
199                 foreach ( $result as $field ) {
200                     foreach($field as $k=>$v){
201                         //allows values for custom fields to be defined outside of the scope of studio
202                         if(!isset($GLOBALS ['dictionary'] [$object] ['fields'] [$field ['name']][$k])){
203                             $GLOBALS ['dictionary'] [$object] ['fields'] [$field ['name']][$k] = $v;
204                         }
205                     }
206                 }
207
208                     // Second loop to remove
209                     foreach ( $GLOBALS ['dictionary'] [$object] ['fields'] as $name => $fieldDef ) {
210
211                         if (isset ( $fieldDef ['custom_module'] )) {
212                             if (! isset ( $result [$name] )) {
213                                 unset ( $GLOBALS ['dictionary'] [$object] ['fields'] [$name] );
214                             } else {
215                                 $GLOBALS ['dictionary'] [$object] ['custom_fields'] = true;
216                             }
217                         }
218
219                     } //if
220                 }
221             }
222             $manager = new VardefManager ( );
223             $manager->saveCache ( $this->module, $object );
224         }
225     }
226
227     /**
228     * returns either false or an array containing the select and join parameter for a query using custom fields
229     * @param $expandedList boolean      If true, return a list of all fields with source=custom_fields in the select instead of the standard _cstm.*
230     *     This is required for any downstream construction of a SQL statement where we need to manipulate the select list,
231     *     for example, listviews with custom relate fields where the value comes from join rather than from the custom table
232     *
233     * @return array select=>select columns, join=>prebuilt join statement
234     */
235   function getJOIN( $expandedList = false , $includeRelates = false, &$where = false){
236         if(!$this->bean->hasCustomFields()){
237             return false;
238         }
239
240         if (empty($expandedList) )
241         {
242             $select = ",{$this->bean->table_name}_cstm.*" ;
243         }
244         else
245         {
246             $select = '';
247             $isList = is_array($expandedList);
248             foreach($this->bean->field_defs as $name=>$field)
249             {
250                 if (!empty($field['source']) && $field['source'] == 'custom_fields' && (!$isList || !empty($expandedList[$name]))){
251                     // assumption: that the column name in _cstm is the same as the field name. Currently true.
252                     // however, two types of dynamic fields do not have columns in the custom table - html fields (they're readonly) and flex relates (parent_name doesn't exist)
253                     if ( $field['type'] != 'html' && $name != 'parent_name')
254                         $select .= ",{$this->bean->table_name}_cstm.{$name}" ;
255                 }
256             }
257         }
258         $join = " LEFT JOIN " .$this->bean->table_name. "_cstm ON " .$this->bean->table_name. ".id = ". $this->bean->table_name. "_cstm.id_c ";
259
260         if ($includeRelates) {
261             $jtAlias = "relJoin";
262             $jtCount = 1;
263             foreach($this->bean->field_defs as $name=>$field)
264             {
265                 if ($field['type'] == 'relate' && isset($field['custom_module'])) {
266                     $relateJoinInfo = $this->getRelateJoin($field, $jtAlias.$jtCount);
267                     $select .= $relateJoinInfo['select'];
268                     $join .= $relateJoinInfo['from'];
269                     //bug 27654 martin
270                     if ($where)
271                     {
272                         $pattern = '/'.$field['name'].'\slike/i';
273                         $replacement = $relateJoinInfo['name_field'].' like';
274                         $where = preg_replace($pattern,$replacement,$where);
275                     }
276                     $jtCount++;
277                 }
278             }
279         }
280
281         return array('select'=>$select, 'join'=>$join);
282
283     }
284
285    function getRelateJoin($field_def, $joinTableAlias) {
286         if (empty($field_def['type']) || $field_def['type'] != "relate") {
287             return false;
288         }
289         global $beanFiles, $beanList, $module;
290         $rel_module = $field_def['module'];
291         if(empty($beanFiles[$beanList[$rel_module]])) {
292             return false;
293         }
294
295         require_once($beanFiles[$beanList[$rel_module]]);
296         $rel_mod = new $beanList[$rel_module]();
297         $rel_table = $rel_mod->table_name;
298         if (isset($rel_mod->field_defs['name']))
299         {
300             $name_field_def = $rel_mod->field_defs['name'];
301             if(isset($name_field_def['db_concat_fields']))
302             {
303                 $name_field = db_concat($joinTableAlias, $name_field_def['db_concat_fields']);
304             }
305             //If the name field is non-db, we need to find another field to display
306             else if(!empty($rel_mod->field_defs['name']['source']) && $rel_mod->field_defs['name']['source'] == "non-db" && !empty($field_def['rname']))
307             {
308                 $name_field = "$joinTableAlias." . $field_def['rname'];
309             }
310             else
311             {
312                 $name_field = "$joinTableAlias.name";
313             }
314         }
315         $tableName = isset($field_def['custom_module']) ? "{$this->bean->table_name}_cstm" : $this->bean->table_name ;
316         $relID = $field_def['id_name'];
317         $ret_array['rel_table'] = $rel_table;
318         $ret_array['name_field'] = $name_field;
319         $ret_array['select'] = ", {$tableName}.{$relID}, {$name_field} {$field_def['name']} ";
320         $ret_array['from'] = " LEFT JOIN $rel_table $joinTableAlias ON $tableName.$relID = $joinTableAlias.id"
321                             . " AND $joinTableAlias.deleted=0 ";
322         return $ret_array;
323    }
324
325    /**
326     * Fills in all the custom fields of type relate relationships for an object
327     *
328     */
329    function fill_relationships(){
330         global $beanList, $beanFiles;
331         if(!empty($this->bean->relDepth)) {
332             if($this->bean->relDepth > 1)return;
333         }else{
334             $this->bean->relDepth = 0;
335         }
336         foreach($this->bean->field_defs as $field){
337             if(empty($field['source']) || $field['source'] != 'custom_fields')continue;
338             if($field['type'] == 'relate'){
339                 $related_module =$field['ext2'];
340                 $name = $field['name'];
341                 if (empty($this->bean->$name)) { //Don't load the relationship twice
342                     $id_name = $field['id_name'];
343                     if(isset($beanList[ $related_module])){
344                         $class = $beanList[$related_module];
345
346                         if(file_exists($beanFiles[$class]) && isset($this->bean->$name)){
347                             require_once($beanFiles[$class]);
348                             $mod = new $class();
349                             $mod->relDepth = $this->bean->relDepth + 1;
350                             $mod->retrieve($this->bean->$id_name);
351                             $this->bean->$name = $mod->name;
352                         }
353                     }
354                 }
355             }
356         }
357     }
358
359     /**
360      * Process the save action for sugar bean custom fields
361      *
362      * @param boolean $isUpdate
363      */
364      function save($isUpdate){
365
366         if($this->bean->hasCustomFields() && isset($this->bean->id)){
367
368             if($isUpdate){
369                 $query = "UPDATE ". $this->bean->table_name. "_cstm SET ";
370             }
371             $queryInsert = "INSERT INTO ". $this->bean->table_name. "_cstm (id_c";
372             $values = "('".$this->bean->id."'";
373             $first = true;
374             foreach($this->bean->field_defs as $name=>$field){
375
376                 if(empty($field['source']) || $field['source'] != 'custom_fields')continue;
377                 if($field['type'] == 'html' || $field['type'] == 'parent')continue;
378                 if(isset($this->bean->$name)){
379                     $quote = "'";
380
381                     if(in_array($field['type'], array('int', 'float', 'double', 'uint', 'ulong', 'long', 'short', 'tinyint', 'currency', 'decimal'))) {
382                         $quote = '';
383                         if(!isset($this->bean->$name) || !is_numeric($this->bean->$name) ){
384                             if($field['required']){
385                                 $this->bean->$name = 0;
386                             }else{
387                                 $this->bean->$name = 'NULL';
388                             }
389                         }
390                     }
391                     if ( $field['type'] == 'bool' ) {
392                         if ( $this->bean->$name === FALSE )
393                             $this->bean->$name = '0';
394                         elseif ( $this->bean->$name === TRUE )
395                             $this->bean->$name = '1';
396                     }
397
398                     $val = $this->bean->$name;
399                                         if(($field['type'] == 'date' || $field['type'] == 'datetimecombo') && (empty($this->bean->$name )|| $this->bean->$name == '1900-01-01')){
400                         $quote = '';
401                         $val = 'NULL';
402                         $this->bean->$name = ''; // do not set it to string 'NULL'
403                     }
404                     if($isUpdate){
405                         if($first){
406                             $query .= " $name=$quote".$GLOBALS['db']->quote($val)."$quote";
407
408                         }else{
409                             $query .= " ,$name=$quote".$GLOBALS['db']->quote($val)."$quote";
410                         }
411                     }
412                     $first = false;
413                     $queryInsert .= " ,$name";
414                     $values .= " ,$quote". $GLOBALS['db']->quote($val). "$quote";
415                 }
416             }
417             if($isUpdate){
418                 $query.= " WHERE id_c='" . $this->bean->id ."'";
419
420             }
421
422             $queryInsert .= " ) VALUES $values )";
423             if(!$first){
424                 if(!$isUpdate){
425                     $GLOBALS['db']->query($queryInsert);
426                 }else{
427                     $checkquery = "SELECT id_c FROM {$this->bean->table_name}_cstm WHERE id_c = '{$this->bean->id}'";
428                     if ( $GLOBALS['db']->getOne($checkquery) )
429                         $result = $GLOBALS['db']->query($query);
430                     else
431                         $GLOBALS['db']->query($queryInsert);
432                 }
433             }
434         }
435
436     }
437     /**
438      * Deletes the field from fields_meta_data and drops the database column then it rebuilds the cache
439      * Use the widgets get_db_modify_alter_table() method to get the table sql - some widgets do not need any custom table modifications
440      * @param STRING $name - field name
441      */
442     function deleteField($widget){
443         require_once('modules/DynamicFields/templates/Fields/TemplateField.php');
444         global $beanList;
445         if (!($widget instanceof TemplateField)) {
446             $field_name = $widget;
447             $widget = new TemplateField();
448             $widget->name = $field_name;
449         }
450         $object_name = $beanList[$this->module];
451
452         //Some modules like cases have a bean name that doesn't match the object name
453         if (empty($GLOBALS['dictionary'][$object_name])) {
454             $newName = BeanFactory::getObjectName($this->module);
455             $object_name = $newName != false ? $newName : $object_name;
456         }
457
458         $GLOBALS['db']->query("DELETE FROM fields_meta_data WHERE id='" . $this->module . $widget->name . "'");
459         $sql = $widget->get_db_delete_alter_table( $this->bean->table_name . "_cstm" ) ;
460         if (! empty( $sql ) )
461             $GLOBALS['db']->query( $sql );
462
463         $this->removeVardefExtension($widget);
464         VardefManager::clearVardef();
465         VardefManager::refreshVardefs($this->module, $object_name);
466
467     }
468
469     /*
470      * Method required by the TemplateRelatedTextField->save() method
471      * Taken from MBModule's implementation
472      */
473     function fieldExists($name = '', $type = ''){
474         // must get the vardefs from the GLOBAL array as $bean->field_defs does not contain the values from the cache at this point
475         // TODO: fix this - saveToVardefs() updates GLOBAL['dictionary'] correctly, obtaining its information directly from the fields_meta_data table via buildCache()...
476         $vardefs = $GLOBALS['dictionary'][$this->bean->object_name]['fields'];
477         if(!empty($vardefs)){
478             if(empty($type) && empty($name))
479                 return false;
480             else if(empty($type))
481                 return !empty($vardefs[$name]);
482             else if(empty($name)){
483                 foreach($vardefs as $def){
484                     if($def['type'] == $type)
485                         return true;
486                 }
487                 return false;
488             }else
489                 return (!empty($vardefs[$name]) && ($vardefs[$name]['type'] == $type));
490         }else{
491             return false;
492         }
493     }
494
495
496     /**
497      * Adds a custom field using a field object
498      *
499      * @param Field Object $field
500      * @return boolean
501      */
502     function addFieldObject(&$field){
503         $GLOBALS['log']->debug('adding field');
504         $object_name = $this->module;
505         $db_name = $field->name;
506
507         $fmd = new FieldsMetaData();
508         $id =  $fmd->retrieve($object_name.$db_name,true, false);
509         $is_update = false;
510         $label = strtoupper( $field->label );
511         if(!empty($id)){
512             $is_update = true;
513         }else{
514             $db_name = $this->getDBName($field->name);
515             $field->name = $db_name;
516         }
517         $this->createCustomTable();
518         $fmd->id = $object_name.$db_name;
519         $fmd->custom_module= $object_name;
520         $fmd->name = $db_name;
521         $fmd->vname = $label;
522         $fmd->type = $field->type;
523         $fmd->help = $field->help;
524         if (!empty($field->len))
525             $fmd->len = $field->len; // tyoung bug 15407 - was being set to $field->size so changes weren't being saved
526         $fmd->required = ($field->required ? 1 : 0);
527         $fmd->default_value = $field->default;
528         $fmd->ext1 = $field->ext1;
529         $fmd->ext2 = $field->ext2;
530         $fmd->ext3 = $field->ext3;
531         $fmd->ext4 = (isset($field->ext4) ? $field->ext4 : '');
532         $fmd->comments = $field->comment;
533         $fmd->massupdate = $field->massupdate;
534         $fmd->importable = ( isset ( $field->importable ) ) ? $field->importable : null ;
535         $fmd->duplicate_merge = $field->duplicate_merge;
536         $fmd->audited =$field->audited;
537         $fmd->reportable = ($field->reportable ? 1 : 0);
538         if(!$is_update){
539             $fmd->new_with_id=true;
540         }
541         $fmd->save();
542         $this->buildCache($this->module);
543         if($field){
544             if(!$is_update){
545                 //Do two SQL calls here in this case
546                 //The first is to create the column in the custom table without the default value
547                 //The second is to modify the column created in the custom table to set the default value
548                 //We do this so that the existing entries in the custom table don't have the default value set
549                 $field->default = '';
550                 $field->default_value = '';
551                 // resetting default and default_value does not work for multienum and causes trouble for mssql
552                 // so using a temporary variable here to indicate that we don't want default for this query
553                 if ($GLOBALS['db']->dbType == 'mssql') {
554                     $field->no_default = 1;
555                 }
556                 $query = $field->get_db_add_alter_table($this->bean->table_name . '_cstm');
557                 // unsetting temporary member variable
558                 if ($GLOBALS['db']->dbType == 'mssql') {
559                     unset($field->no_default);
560                 }
561                 if(!empty($query)){
562                         $GLOBALS['db']->query($query);
563                         $field->default = $fmd->default_value;
564                         $field->default_value = $fmd->default_value;
565                         $query = $field->get_db_modify_alter_table($this->bean->table_name . '_cstm');
566                         if(!empty($query)){
567                                 $GLOBALS['db']->query($query);
568                         }
569                 }
570             }else{
571                 $query = $field->get_db_modify_alter_table($this->bean->table_name . '_cstm');
572                 if(!empty($query)){
573                         $GLOBALS['db']->query($query);
574                 }
575             }
576             $this->saveExtendedAttributes($field, array_keys($fmd->field_defs));
577         }
578
579         return true;
580     }
581
582     function saveExtendedAttributes($field, $column_fields)
583     {
584             require_once ('modules/ModuleBuilder/parsers/StandardField.php') ;
585             require_once ('modules/DynamicFields/FieldCases.php') ;
586             global $beanList;
587
588             $to_save = array();
589             $base_field = get_widget ( $field->type) ;
590         foreach ($field->vardef_map as $property => $fmd_col){
591
592             if (!isset($field->$property) || in_array($fmd_col, $column_fields) || in_array($property, $column_fields)
593                 || $this->isDefaultValue($property, $field->$property, $base_field)
594                 || $property == "action" || $property == "label_value" || $property == "label"
595                 || (substr($property, 0,3) == 'ext' && strlen($property) == 4))
596             {
597                 continue;
598             }
599             $to_save[$property] =
600                 is_string($field->$property) ? htmlspecialchars_decode($field->$property, ENT_QUOTES) : $field->$property;
601         }
602         $bean_name = $beanList[$this->module];
603
604         $this->writeVardefExtension($bean_name, $field, $to_save);
605     }
606
607     protected function isDefaultValue($property, $value, $baseField)
608     {
609         switch ($property) {
610             case "importable":
611                 return ( $value === 'true' || $value === '1' || $value === true || $value === 1 ); break;
612             case "required":
613             case "audited":
614             case "massupdate":
615                 return ( $value === 'false' || $value === '0' || $value === false || $value === 0); break;
616             case "default_value":
617             case "default":
618             case "help":
619             case "comments":
620                 return ($value == "");
621             case "duplicate_merge":
622                 return ( $value === 'false' || $value === '0' || $value === false || $value === 0 || $value === "disabled"); break;
623         }
624
625         if (isset($baseField->$property))
626         {
627             return $baseField->$property == $value;
628         }
629
630         return false;
631     }
632
633     protected function writeVardefExtension($bean_name, $field, $def_override)
634     {
635         //Hack for the broken cases module
636         $vBean = $bean_name == "aCase" ? "Case" : $bean_name;
637         $file_loc = "$this->base_path/sugarfield_{$field->name}.php";
638
639         $out =  "<?php\n // created: " . date('Y-m-d H:i:s') . "\n";
640         foreach ($def_override as $property => $val)
641         {
642             $out .= override_value_to_string_recursive(array($vBean, "fields", $field->name, $property), "dictionary", $val) . "\n";
643         }
644
645         $out .= "\n ?>";
646
647         if (!file_exists($this->base_path))
648             mkdir_recursive($this->base_path);
649
650         if( $fh = @sugar_fopen( $file_loc, 'w' ) )
651         {
652             fputs( $fh, $out);
653             fclose( $fh );
654             return true ;
655         }
656         else
657         {
658             return false ;
659         }
660     }
661
662     protected function removeVardefExtension($field)
663     {
664         $file_loc = "$this->base_path/sugarfield_{$field->name}.php";
665
666         if (is_file($file_loc))
667         {
668             unlink($file_loc);
669         }
670     }
671
672
673     /**
674      * DEPRECIATED: Use addFieldObject instead.
675      * Adds a Custom Field using parameters
676      *
677      * @param unknown_type $name
678      * @param unknown_type $label
679      * @param unknown_type $type
680      * @param unknown_type $max_size
681      * @param unknown_type $required_option
682      * @param unknown_type $default_value
683      * @param unknown_type $ext1
684      * @param unknown_type $ext2
685      * @param unknown_type $ext3
686      * @param unknown_type $audited
687      * @param unknown_type $mass_update
688      * @param unknown_type $ext4
689      * @param unknown_type $help
690      * @param unknown_type $duplicate_merge
691      * @param unknown_type $comment
692      * @return boolean
693      */
694     function addField($name,$label='', $type='Text',$max_size='255',$required_option='optional', $default_value='', $ext1='', $ext2='', $ext3='',$audited=0, $mass_update = 0 , $ext4='', $help='',$duplicate_merge=0, $comment=''){
695         require_once('modules/DynamicFields/templates/Fields/TemplateField.php');
696         $field = new TemplateField();
697         $field->label = $label;
698         if(empty($field->label)){
699             $field->label = $name;
700         }
701         $field->name = $name;
702         $field->type = $type;
703         $field->len = $max_size;
704         $field->required = (!empty($required_option) && $required_option != 'optional');
705         $field->default = $default_value;
706         $field->ext1 = $ext1;
707         $field->ext2 = $ext2;
708         $field->ext3 = $ext3;
709         $field->ext4 = $ext4;
710         $field->help = $help;
711         $field->comments = $comment;
712         $field->massupdate = $mass_update;
713         $field->duplicate_merge = $duplicate_merge;
714         $field->audited = $audited;
715         $field->reportable = 1;
716         return $this->addFieldObject($field);
717     }
718
719     /**
720      * Creates the custom table with an id of id_c
721      *
722      */
723     function createCustomTable($execute = true){
724         $out = "";
725         if (!$GLOBALS['db']->tableExists($this->bean->table_name."_cstm")) {
726             $GLOBALS['log']->debug('creating custom table for '. $this->bean->table_name);
727             $query = 'CREATE TABLE '.$this->bean->table_name.'_cstm ( ';
728             $query .='id_c ' . $this->bean->dbManager->helper->getColumnType('id') .' NOT NULL';
729             $query .=', PRIMARY KEY ( id_c ) )';
730             if($GLOBALS['db']->dbType == 'mysql'){
731                 $query .= ' CHARACTER SET utf8 COLLATE utf8_general_ci';
732             }
733             $out = $query . "\n";
734             if ($execute)
735                 $GLOBALS['db']->query($query);
736             $out .= $this->add_existing_custom_fields($execute);
737         }
738
739         return $out;
740     }
741
742     /**
743      * Updates the db schema and adds any custom fields we have used if the custom table was dropped
744      *
745      */
746     function add_existing_custom_fields($execute = true){
747         $out = "";
748         if($this->bean->hasCustomFields()){
749                 foreach($this->bean->field_defs as $name=>$data){
750                         if(empty($data['source']) || $data['source'] != 'custom_fields')
751                     continue;
752                     $out .= $this->add_existing_custom_field($data, $execute);
753                 }
754         }
755         return $out;
756     }
757
758     function add_existing_custom_field($data, $execute = true)
759     {
760
761         $field = get_widget ( $data ['type'] );
762         $field->populateFromRow($data);
763         $query = "/*MISSING IN DATABASE - {$data['name']} -  ROW*/\n"
764                 . $field->get_db_add_alter_table($this->bean->table_name . '_cstm');
765         $out = $query . "\n";
766         if ($execute)
767             $GLOBALS['db']->query($query);
768
769         return $out;
770     }
771
772     public function repairCustomFields($execute = true)
773     {
774         $out = $this->createCustomTable($execute);
775         //If the table didn't exist, createCustomTable will have returned all the SQL to create and populate it
776         if (!empty($out))
777             return "/*Checking Custom Fields for module : {$this->module} */\n$out";
778         //Otherwise make sure all the custom fields defined in the vardefs exist in the custom table.
779         //We aren't checking for data types, just that the column exists.
780         $db = $GLOBALS['db'];
781         $tablename = $this->bean->table_name."_cstm";
782         $compareFieldDefs = $db->getHelper()->get_columns($tablename);
783         foreach($this->bean->field_defs as $name=>$data){
784             if(empty($data['source']) || $data['source'] != 'custom_fields')
785                 continue;
786             /**
787              * @bug 43471
788              * @issue 43471
789              * @itr 23441
790              *
791              * force the name to be lower as it needs to be lower since that is how it's put into the key
792              * in the get_columns() call above.
793              */
794             if(!empty($compareFieldDefs[strtolower($name)])) {
795                 continue;
796             }
797             $out .= $this->add_existing_custom_field($data, $execute);
798         }
799         if (!empty($out))
800             $out = "/*Checking Custom Fields for module : {$this->module} */\n$out";
801
802         return $out;
803     }
804
805     /**
806      * Adds a label to the module's mod_strings for the current language
807      * Note that the system label name
808      *
809      * @param string $displayLabel The label value to be displayed
810      * @return string The core of the system label name - returns currency_id5 for example, when the full label would then be LBL_CURRENCY_ID5
811      * TODO: Only the core is returned for historical reasons - switch to return the real system label
812      */
813     function addLabel ( $displayLabel )
814     {
815         $mod_strings = return_module_language($GLOBALS[ 'current_language' ], $this->module);
816         $limit = 10;
817         $count = 0;
818         $field_key = $this->getDBName($displayLabel, false);
819         $systemLabel = $field_key;
820         if(!$this->use_existing_labels){ // use_existing_labels defaults to false in this module; as of today, only set to true by ModuleInstaller.php
821             while( isset( $mod_strings [ $systemLabel ] ) && $count <= $limit )
822             {
823                 $systemLabel = $field_key. "_$count";
824                 $count++;
825             }
826         }
827         $selMod = (!empty($_REQUEST['view_module'])) ? $_REQUEST['view_module'] : $this->module;
828         require_once 'modules/ModuleBuilder/parsers/parser.label.php' ;
829         $parser = new ParserLabel ( $selMod , isset ( $_REQUEST [ 'view_package' ] ) ? $_REQUEST [ 'view_package' ] : null ) ;
830         $parser->handleSave ( array('label_'. $systemLabel => $displayLabel ) , $GLOBALS [ 'current_language' ] ) ;
831
832         return $systemLabel;
833     }
834
835     /**
836      * Returns a Database Safe Name
837      *
838      * @param STRING $name
839      * @param BOOLEAN $_C do we append _c to the name
840      * @return STRING
841      */
842     function getDBName($name, $_C= true){
843         static $cached_results = array();
844         if(!empty($cached_results[$name]))
845         {
846             return $cached_results[$name];
847         }
848         $exclusions = array('parent_type', 'parent_id', 'currency_id', 'parent_name');
849         // Remove any non-db friendly characters
850         $return_value = preg_replace("/[^\w]+/","_",$name);
851         if($_C == true && !in_array($return_value, $exclusions) && substr($return_value, -2) != '_c'){
852             $return_value .= '_c';
853         }
854         $cached_results[$name] = $return_value;
855         return $return_value;
856     }
857
858     function setWhereClauses(&$where_clauses){
859         if (isset($this->avail_fields)) {
860             foreach($this->avail_fields as $name=>$value){
861                 if(!empty($_REQUEST[$name])){
862                     $where_clauses[] = $this->bean->table_name . "_cstm.$name LIKE '". $GLOBALS['db']->quote($_REQUEST[$name]). "%'";
863                 }
864             }
865         }
866
867     }
868
869     /////////////////////////BACKWARDS COMPATABILITY MODE FOR PRE 5.0 MODULES\\\\\\\\\\\\\\\\\\\\\\\\\\\
870     ////////////////////////////END BACKWARDS COMPATABILITY MODE FOR PRE 5.0 MODULES\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
871
872     /**
873      *
874      * DEPRECATED
875      loads fields into the bean
876      This used to be called during the retrieve process now it is done through a join
877      Restored from pre-r30895 to maintain support for custom code that may have called retrieve() directly
878      */
879
880     function retrieve()
881     {
882         if(!isset($this->bean)){
883             $GLOBALS['log']->fatal("DynamicField retrieve, bean not instantiated: ".var_export(debug_print_backtrace(), true));
884             return false;
885         }
886
887         if(!$this->bean->hasCustomFields()){
888             return false;
889         }
890
891         $query = "SELECT * FROM ".$this->bean->table_name."_cstm WHERE id_c='".$this->bean->id."'";
892         $result = $GLOBALS['db']->query($query);
893         $row = $GLOBALS['db']->fetchByAssoc($result);
894
895         if($row)
896         {
897             foreach($row as $name=>$value)
898             {
899                 // originally in pre-r30895 we checked if this field was in avail_fields i.e., in fields_meta_data and not deleted
900                 // with the removal of avail_fields post-r30895 we have simplified this - we now retrieve every custom field even if previously deleted
901                 // this is considered harmless as the value although set in the bean will not otherwise be used (nothing else works off the list of fields in the bean)
902                 $this->bean->$name = $value;
903             }
904         }
905
906     }
907
908    function populateXTPL($xtpl, $view) {
909
910         if($this->bean->hasCustomFields()){
911             $results = $this->getAllFieldsView($view, 'xtpl');
912             foreach($results as $name=>$value){
913                 if(is_array($value['xtpl']))
914                 {
915                     foreach($value['xtpl'] as $xName=>$xValue)
916                     {
917                         $xtpl->assign(strtoupper($xName), $xValue);
918                     }
919                 } else {
920                     $xtpl->assign(strtoupper($name), $value['xtpl']);
921                 }
922             }
923         }
924
925     }
926
927     function populateAllXTPL($xtpl, $view){
928         $this->populateXTPL($xtpl, $view);
929
930     }
931
932     function getAllFieldsView($view, $type){
933          require_once ('modules/DynamicFields/FieldCases.php');
934          $results = array();
935          foreach($this->bean->field_defs as $name=>$data){
936             if(empty($data['source']) || $data['source'] != 'custom_fields')
937             {
938                 continue;
939             }
940             $field = get_widget ( $data ['type'] );
941             $field->populateFromRow($data);
942             $field->view = $view;
943             $field->bean = $this->bean;
944             switch(strtolower($type))
945             {
946                 case 'xtpl':
947                     $results[$name] = array('xtpl'=>$field->get_xtpl());
948                     break;
949                 case 'html':
950                     $results[$name] = array('html'=> $field->get_html(), 'label'=> $field->get_html_label(), 'fieldType'=>$field->data_type, 'isCustom' =>true);
951                     break;
952             }
953
954         }
955         return $results;
956     }
957
958     ////////////////////////////END BACKWARDS COMPATABILITY MODE FOR PRE 5.0 MODULES\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
959 }
960
961 ?>