]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SugarObjects/VardefManager.php
Release 6.5.0
[Github/sugarcrm.git] / include / SugarObjects / VardefManager.php
1 <?php
2 /*********************************************************************************
3  * SugarCRM Community Edition is a customer relationship management program developed by
4  * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
5  * 
6  * This program is free software; you can redistribute it and/or modify it under
7  * the terms of the GNU Affero General Public License version 3 as published by the
8  * Free Software Foundation with the addition of the following permission added
9  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
11  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12  * 
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
16  * details.
17  * 
18  * You should have received a copy of the GNU Affero General Public License along with
19  * this program; if not, see http://www.gnu.org/licenses or write to the Free
20  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  * 02110-1301 USA.
22  * 
23  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
24  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25  * 
26  * The interactive user interfaces in modified source and object code versions
27  * of this program must display Appropriate Legal Notices, as required under
28  * Section 5 of the GNU Affero General Public License version 3.
29  * 
30  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
31  * these Appropriate Legal Notices must retain the display of the "Powered by
32  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
33  * technical reasons, the Appropriate Legal Notices must display the words
34  * "Powered by SugarCRM".
35  ********************************************************************************/
36
37
38 /**
39  * Vardefs management
40  * @api
41  */
42 class VardefManager{
43     static $custom_disabled_modules = array();
44     static $linkFields;
45
46     /**
47      * this method is called within a vardefs.php file which extends from a SugarObject.
48      * It is meant to load the vardefs from the SugarObject.
49      */
50     static function createVardef($module, $object, $templates = array('default'), $object_name = false)
51     {
52         global $dictionary;
53
54         include_once('modules/TableDictionary.php');
55
56         //reverse the sort order so priority goes highest to lowest;
57         $templates = array_reverse($templates);
58         foreach ($templates as $template)
59         {
60             VardefManager::addTemplate($module, $object, $template, $object_name);
61         }
62         LanguageManager::createLanguageFile($module, $templates);
63
64         if (isset(VardefManager::$custom_disabled_modules[$module]))
65         {
66             $vardef_paths = array(
67                 'custom/modules/' . $module . '/Ext/Vardefs/vardefs.ext.php',
68                 'custom/Extension/modules/' . $module . '/Ext/Vardefs/vardefs.php'
69             );
70
71             //search a predefined set of locations for the vardef files
72             foreach ($vardef_paths as $path)
73             {
74                 if (file_exists($path)) {
75                     require($path);
76                 }
77             }
78         }
79     }
80
81     /**
82      * Enables/Disables the loading of custom vardefs for a module.
83      * @param String $module Module to be enabled/disabled
84      * @param Boolean $enable true to enable, false to disable
85      * @return  null
86      */
87     public static function setCustomAllowedForModule($module, $enable) {
88         if ($enable && isset($custom_disabled_modules[$module])) {
89               unset($custom_disabled_modules[$module]);
90         } else if (!$enable) {
91               $custom_disabled_modules[$module] = true;
92         }
93     }
94
95     static function addTemplate($module, $object, $template, $object_name=false){
96         if($template == 'default')$template = 'basic';
97         $templates = array();
98         $fields = array();
99         if(empty($object_name))$object_name = $object;
100         $_object_name = strtolower($object_name);
101         if(!empty($GLOBALS['dictionary'][$object]['table'])){
102             $table_name = $GLOBALS['dictionary'][$object]['table'];
103         }else{
104             $table_name = strtolower($module);
105         }
106
107         if(empty($templates[$template])){
108             $path = 'include/SugarObjects/templates/' . $template . '/vardefs.php';
109             if(file_exists($path)){
110                 require($path);
111                 $templates[$template] = $vardefs;
112             }else{
113                 $path = 'include/SugarObjects/implements/' . $template . '/vardefs.php';
114                 if(file_exists($path)){
115                     require($path);
116                     $templates[$template] = $vardefs;
117                 }
118             }
119         }
120        
121         if(!empty($templates[$template])){
122             if(empty($GLOBALS['dictionary'][$object]['fields']))$GLOBALS['dictionary'][$object]['fields'] = array();
123             if(empty($GLOBALS['dictionary'][$object]['relationships']))$GLOBALS['dictionary'][$object]['relationships'] = array();
124             if(empty($GLOBALS['dictionary'][$object]['indices']))$GLOBALS['dictionary'][$object]['indices'] = array();
125             $GLOBALS['dictionary'][$object]['fields'] = array_merge($templates[$template]['fields'], $GLOBALS['dictionary'][$object]['fields']);
126             if(!empty($templates[$template]['relationships']))$GLOBALS['dictionary'][$object]['relationships'] = array_merge($templates[$template]['relationships'], $GLOBALS['dictionary'][$object]['relationships']);
127             if(!empty($templates[$template]['indices']))$GLOBALS['dictionary'][$object]['indices'] = array_merge($templates[$template]['indices'], $GLOBALS['dictionary'][$object]['indices']);
128             // maintain a record of this objects inheritance from the SugarObject templates...
129             $GLOBALS['dictionary'][$object]['templates'][ $template ] = $template ;
130         }
131     }
132
133
134     /**
135      * Remove invalid field definitions
136      * @static
137      * @param Array $fieldDefs
138      * @return  Array
139      */
140     static function cleanVardefs($fieldDefs)
141     {
142         foreach($fieldDefs as $field => $defs)
143         {
144             if (empty($def['name']) || empty($def['type']))
145             {
146                 unset($fieldDefs[$field]);
147             }
148         }
149
150         return $fieldDefs;
151     }
152
153     /**
154      * Save the dictionary object to the cache
155      * @param string $module the name of the module
156      * @param string $object the name of the object
157      */
158     static function saveCache($module,$object, $additonal_objects= array()){
159
160         if (empty($GLOBALS['dictionary'][$object]))
161             $object = BeanFactory::getObjectName($module);
162         $file = create_cache_directory('modules/' . $module . '/' . $object . 'vardefs.php');
163
164         $out="<?php \n \$GLOBALS[\"dictionary\"][\"". $object . "\"]=" . var_export($GLOBALS['dictionary'][$object], true) .";";
165         sugar_file_put_contents_atomic($file, $out);
166         if ( sugar_is_file($file) && is_readable($file)) {
167             include($file);
168         }
169
170         // put the item in the sugar cache.
171         $key = "VardefManager.$module.$object";
172         //Sometimes bad definitions can get in from left over extensions or file system lag(caching). We need to clean those.
173         $data = self::cleanVardefs($GLOBALS['dictionary'][$object]);
174         sugar_cache_put($key,$data);
175     }
176
177     /**
178      * clear out the vardef cache. If we receive a module name then just clear the vardef cache for that module
179      * otherwise clear out the cache for every module
180      * @param string module_dir the module_dir to clear, if not specified then clear
181      *                      clear vardef cache for all modules.
182      * @param string object_name the name of the object we are clearing this is for sugar_cache
183      */
184     static function clearVardef($module_dir = '', $object_name = ''){
185         //if we have a module name specified then just remove that vardef file
186         //otherwise go through each module and remove the vardefs.php
187         if(!empty($module_dir) && !empty($object_name)){
188             VardefManager::_clearCache($module_dir, $object_name);
189         }else{
190             global $beanList;
191             foreach($beanList as $module_dir => $object_name){
192                 VardefManager::_clearCache($module_dir, $object_name);
193             }
194         }
195     }
196
197     /**
198      * PRIVATE function used within clearVardefCache so we do not repeat logic
199      * @param string module_dir the module_dir to clear
200      * @param string object_name the name of the object we are clearing this is for sugar_cache
201      */
202     static function _clearCache($module_dir = '', $object_name = ''){
203         if(!empty($module_dir) && !empty($object_name)){
204
205             //Some modules like cases have a bean name that doesn't match the object name
206             if (empty($GLOBALS['dictionary'][$object_name])) {
207                 $newName = BeanFactory::getObjectName($module_dir);
208                 $object_name = $newName != false ? $newName : $object_name;
209             }
210
211             $file = sugar_cached('modules/').$module_dir.'/' . $object_name . 'vardefs.php';
212
213             if(file_exists($file)){
214                 unlink($file);
215                 $key = "VardefManager.$module_dir.$object_name";
216                 sugar_cache_clear($key);
217             }
218         }
219     }
220
221     /**
222      * Given a module, search all of the specified locations, and any others as specified
223      * in order to refresh the cache file
224      *
225      * @param string $module the given module we want to load the vardefs for
226      * @param string $object the given object we wish to load the vardefs for
227      * @param array $additional_search_paths an array which allows a consumer to pass in additional vardef locations to search
228      */
229     static function refreshVardefs($module, $object, $additional_search_paths = null, $cacheCustom = true, $params = array()){
230         // Some of the vardefs do not correctly define dictionary as global.  Declare it first.
231         global $dictionary, $beanList;
232         $vardef_paths = array(
233                     'modules/'.$module.'/vardefs.php',
234                     'custom/modules/'.$module.'/Ext/Vardefs/vardefs.ext.php',
235                     'custom/Extension/modules/'.$module.'/Ext/Vardefs/vardefs.php'
236                  );
237
238         // Add in additional search paths if they were provided.
239         if(!empty($additional_search_paths) && is_array($additional_search_paths))
240         {
241             $vardef_paths = array_merge($vardef_paths, $additional_search_paths);
242         }
243         $found = false;
244         //search a predefined set of locations for the vardef files
245         foreach($vardef_paths as $path){
246             if(file_exists($path)){
247                 require($path);
248                 $found = true;
249             }
250         }
251         //Some modules have multiple beans, we need to see if this object has a module_dir that is different from its module_name
252         if(!$found){
253             $temp = BeanFactory::newBean($module);
254             if ($temp)
255             {
256                 $object_name = BeanFactory::getObjectName($temp->module_dir);
257                 if ($temp && $temp->module_dir != $temp->module_name && !empty($object_name))
258                 {
259                     self::refreshVardefs($temp->module_dir, $object_name, $additional_search_paths, $cacheCustom);
260                 }
261             }
262         }
263
264         //Some modules like cases have a bean name that doesn't match the object name
265         if (empty($dictionary[$object])) {
266             $newName = BeanFactory::getObjectName($module);
267             $object = $newName != false ? $newName : $object;
268         }
269
270         //load custom fields into the vardef cache
271         if($cacheCustom){
272             require_once("modules/DynamicFields/DynamicField.php");
273             $df = new DynamicField ($module) ;
274             $df->buildCache($module, false);
275         }
276
277         //great! now that we have loaded all of our vardefs.
278         //let's go save them to the cache file.
279         if(!empty($dictionary[$object])) {
280             VardefManager::saveCache($module, $object);
281         }
282     }
283
284     /**
285      * @static
286      * @param  $module
287      * @param  $object
288      * @return array|bool  returns a list of all fields in the module of type 'link'.
289      */
290     protected static function getLinkFieldsForModule($module, $object)
291     {
292         global $dictionary;
293         //Some modules like cases have a bean name that doesn't match the object name
294         if (empty($dictionary[$object])) {
295             $newName = BeanFactory::getObjectName($module);
296             $object = $newName != false ? $newName : $object;
297         }
298         if (empty($dictionary[$object])) {
299             self::loadVardef($module, $object, false, array('ignore_rel_calc_fields' => true));
300         }
301         if (empty($dictionary[$object]))
302         {
303             $GLOBALS['log']->debug("Failed to load vardefs for $module:$object in linkFieldsForModule<br/>");
304             return false;
305         }
306
307         //Cache link fields for this call in a static variable
308         if (!isset(self::$linkFields))
309             self::$linkFields = array();
310
311         if (isset(self::$linkFields[$object]))
312             return self::$linkFields[$object];
313
314         $vardef = $dictionary[$object];
315         $links = array();
316         foreach($vardef['fields'] as $name => $def)
317         {
318             //Look through all link fields for related modules that have calculated fields that use that relationship
319             if(!empty($def['type']) && $def['type'] == 'link' && !empty($def['relationship']))
320             {
321                 $links[$name] = $def;
322             }
323         }
324
325         self::$linkFields[$object] = $links;
326
327         return $links;
328     }
329
330
331     public static function getLinkFieldForRelationship($module, $object, $relName)
332     {
333         $cacheKey = "LFR{$module}{$object}{$relName}";
334         $cacheValue = sugar_cache_retrieve($cacheKey);
335         if(!empty($cacheValue))
336             return $cacheValue;
337
338         $relLinkFields = self::getLinkFieldsForModule($module, $object);
339         $matches = array();
340         if (!empty($relLinkFields))
341         {
342             foreach($relLinkFields as $rfName => $rfDef)
343             {
344                 if ($rfDef['relationship'] == $relName)
345                 {
346                     $matches[] = $rfDef;
347                 }
348             }
349         }
350         if (empty($matches))
351             return false;
352         if (sizeof($matches) == 1)
353             $results = $matches[0];
354         else
355             //For relationships where both sides are the same module, more than one link will be returned
356             $results = $matches;
357
358         sugar_cache_put($cacheKey, $results);
359         return $results ;
360     }
361
362
363
364     /**
365      * applyGlobalAccountRequirements
366      *
367      * This method ensures that the account_name relationships are set to always be required if the configuration file specifies
368      * so.  For more information on this require_accounts parameter, please see the administrators guide or go to the
369      * developers.sugarcrm.com website to find articles relating to the use of this field.
370      *
371      * @param Array $vardef The vardefs of the module to apply the account_name field requirement to
372      * @return Array $vardef The vardefs of the module with the updated required setting based on the system configuration
373      */
374     static function applyGlobalAccountRequirements($vardef)
375     {
376         if (isset($GLOBALS['sugar_config']['require_accounts']))
377         {
378             if (isset($vardef['fields'])
379                 && isset($vardef['fields']['account_name'])
380                 && isset($vardef['fields']['account_name']['type'])
381                 && $vardef['fields']['account_name']['type'] == 'relate'
382                 && isset($vardef['fields']['account_name']['required']))
383             {
384                 $vardef['fields']['account_name']['required'] = $GLOBALS['sugar_config']['require_accounts'];
385             }
386
387         }
388         return $vardef;
389     }
390
391
392     /**
393      * load the vardefs for a given module and object
394      * @param string $module the given module we want to load the vardefs for
395      * @param string $object the given object we wish to load the vardefs for
396      * @param bool   $refresh whether or not we wish to refresh the cache file.
397      */
398     static function loadVardef($module, $object, $refresh=false, $params = array()){
399         //here check if the cache file exists, if it does then load it, if it doesn't
400         //then call refreshVardef
401         //if either our session or the system is set to developerMode then refresh is set to true
402         if(inDeveloperMode() || !empty($_SESSION['developerMode'])){
403             $refresh = true;
404         }
405         // Retrieve the vardefs from cache.
406         $key = "VardefManager.$module.$object";
407
408         if(!$refresh)
409         {
410             $return_result = sugar_cache_retrieve($key);
411             $return_result = self::applyGlobalAccountRequirements($return_result);
412
413             if(!empty($return_result))
414             {
415                 $GLOBALS['dictionary'][$object] = $return_result;
416                 return;
417             }
418         }
419
420         // Some of the vardefs do not correctly define dictionary as global.  Declare it first.
421         global $dictionary;
422         if(empty($GLOBALS['dictionary'][$object]) || $refresh){
423             //if the consumer has demanded a refresh or the cache/modules... file
424             //does not exist, then we should do out and try to reload things
425
426                         $cachedfile = sugar_cached('modules/'). $module . '/' . $object . 'vardefs.php';
427                         if($refresh || !file_exists($cachedfile)){
428                                 VardefManager::refreshVardefs($module, $object, null, true, $params);
429                         }
430
431             //at this point we should have the cache/modules/... file
432             //which was created from the refreshVardefs so let's try to load it.
433             if(file_exists($cachedfile))
434             {
435                 if (is_readable($cachedfile))
436                 {
437                     include_once($cachedfile);
438                 }
439                 // now that we hae loaded the data from disk, put it in the cache.
440                 if(!empty($GLOBALS['dictionary'][$object]))
441                 {
442                     $GLOBALS['dictionary'][$object] = self::applyGlobalAccountRequirements($GLOBALS['dictionary'][$object]);
443                     sugar_cache_put($key,$GLOBALS['dictionary'][$object]);
444                 }
445             }
446         }
447     }
448
449 }