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