Completed
Push — master ( 24ce66...da2f36 )
by Adam
25:35
created
include/SugarObjects/SugarRegistry.php 1 patch
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,5 +1,7 @@
 block discarded – undo
1 1
 <?php
2
-if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if (!defined('sugarEntry') || !sugarEntry) {
3
+    die('Not A Valid Entry Point');
4
+}
3 5
 /*********************************************************************************
4 6
  * SugarCRM Community Edition is a customer relationship management program developed by
5 7
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
Please login to merge, or discard this patch.
include/SugarObjects/VardefManager.php 3 patches
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -89,9 +89,9 @@  discard block
 block discarded – undo
89 89
      */
90 90
     public static function setCustomAllowedForModule($module, $enable) {
91 91
         if ($enable && isset($custom_disabled_modules[$module])) {
92
-              unset($custom_disabled_modules[$module]);
92
+                unset($custom_disabled_modules[$module]);
93 93
         } else if (!$enable) {
94
-              $custom_disabled_modules[$module] = true;
94
+                $custom_disabled_modules[$module] = true;
95 95
         }
96 96
     }
97 97
 
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
                     'modules/'.$module.'/vardefs.php',
237 237
                     'custom/modules/'.$module.'/Ext/Vardefs/vardefs.ext.php',
238 238
                     'custom/Extension/modules/'.$module.'/Ext/Vardefs/vardefs.php'
239
-                 );
239
+                    );
240 240
 
241 241
         // Add in additional search paths if they were provided.
242 242
         if(!empty($additional_search_paths) && is_array($additional_search_paths))
@@ -426,10 +426,10 @@  discard block
 block discarded – undo
426 426
             //if the consumer has demanded a refresh or the cache/modules... file
427 427
             //does not exist, then we should do out and try to reload things
428 428
 
429
-			$cachedfile = sugar_cached('modules/'). $module . '/' . $object . 'vardefs.php';
430
-			if($refresh || !file_exists($cachedfile)){
431
-				VardefManager::refreshVardefs($module, $object, null, true, $params);
432
-			}
429
+            $cachedfile = sugar_cached('modules/'). $module . '/' . $object . 'vardefs.php';
430
+            if($refresh || !file_exists($cachedfile)){
431
+                VardefManager::refreshVardefs($module, $object, null, true, $params);
432
+            }
433 433
 
434 434
             //at this point we should have the cache/modules/... file
435 435
             //which was created from the refreshVardefs so let's try to load it.
Please login to merge, or discard this patch.
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
  * Vardefs management
43 43
  * @api
44 44
  */
45
-class VardefManager{
45
+class VardefManager {
46 46
     static $custom_disabled_modules = array();
47 47
     static $linkFields;
48 48
 
@@ -67,8 +67,8 @@  discard block
 block discarded – undo
67 67
         if (isset(VardefManager::$custom_disabled_modules[$module]))
68 68
         {
69 69
             $vardef_paths = array(
70
-                'custom/modules/' . $module . '/Ext/Vardefs/vardefs.ext.php',
71
-                'custom/Extension/modules/' . $module . '/Ext/Vardefs/vardefs.php'
70
+                'custom/modules/'.$module.'/Ext/Vardefs/vardefs.ext.php',
71
+                'custom/Extension/modules/'.$module.'/Ext/Vardefs/vardefs.php'
72 72
             );
73 73
 
74 74
             //search a predefined set of locations for the vardef files
@@ -95,41 +95,41 @@  discard block
 block discarded – undo
95 95
         }
96 96
     }
97 97
 
98
-    static function addTemplate($module, $object, $template, $object_name=false){
99
-        if($template == 'default')$template = 'basic';
98
+    static function addTemplate($module, $object, $template, $object_name = false) {
99
+        if ($template == 'default')$template = 'basic';
100 100
         $templates = array();
101 101
         $fields = array();
102
-        if(empty($object_name))$object_name = $object;
102
+        if (empty($object_name))$object_name = $object;
103 103
         $_object_name = strtolower($object_name);
104
-        if(!empty($GLOBALS['dictionary'][$object]['table'])){
104
+        if (!empty($GLOBALS['dictionary'][$object]['table'])) {
105 105
             $table_name = $GLOBALS['dictionary'][$object]['table'];
106
-        }else{
106
+        } else {
107 107
             $table_name = strtolower($module);
108 108
         }
109 109
 
110
-        if(empty($templates[$template])){
111
-            $path = 'include/SugarObjects/templates/' . $template . '/vardefs.php';
112
-            if(file_exists($path)){
110
+        if (empty($templates[$template])) {
111
+            $path = 'include/SugarObjects/templates/'.$template.'/vardefs.php';
112
+            if (file_exists($path)) {
113 113
                 require($path);
114 114
                 $templates[$template] = $vardefs;
115
-            }else{
116
-                $path = 'include/SugarObjects/implements/' . $template . '/vardefs.php';
117
-                if(file_exists($path)){
115
+            } else {
116
+                $path = 'include/SugarObjects/implements/'.$template.'/vardefs.php';
117
+                if (file_exists($path)) {
118 118
                     require($path);
119 119
                     $templates[$template] = $vardefs;
120 120
                 }
121 121
             }
122 122
         }
123 123
        
124
-        if(!empty($templates[$template])){
125
-            if(empty($GLOBALS['dictionary'][$object]['fields']))$GLOBALS['dictionary'][$object]['fields'] = array();
126
-            if(empty($GLOBALS['dictionary'][$object]['relationships']))$GLOBALS['dictionary'][$object]['relationships'] = array();
127
-            if(empty($GLOBALS['dictionary'][$object]['indices']))$GLOBALS['dictionary'][$object]['indices'] = array();
124
+        if (!empty($templates[$template])) {
125
+            if (empty($GLOBALS['dictionary'][$object]['fields']))$GLOBALS['dictionary'][$object]['fields'] = array();
126
+            if (empty($GLOBALS['dictionary'][$object]['relationships']))$GLOBALS['dictionary'][$object]['relationships'] = array();
127
+            if (empty($GLOBALS['dictionary'][$object]['indices']))$GLOBALS['dictionary'][$object]['indices'] = array();
128 128
             $GLOBALS['dictionary'][$object]['fields'] = array_merge($templates[$template]['fields'], $GLOBALS['dictionary'][$object]['fields']);
129
-            if(!empty($templates[$template]['relationships']))$GLOBALS['dictionary'][$object]['relationships'] = array_merge($templates[$template]['relationships'], $GLOBALS['dictionary'][$object]['relationships']);
130
-            if(!empty($templates[$template]['indices']))$GLOBALS['dictionary'][$object]['indices'] = array_merge($templates[$template]['indices'], $GLOBALS['dictionary'][$object]['indices']);
129
+            if (!empty($templates[$template]['relationships']))$GLOBALS['dictionary'][$object]['relationships'] = array_merge($templates[$template]['relationships'], $GLOBALS['dictionary'][$object]['relationships']);
130
+            if (!empty($templates[$template]['indices']))$GLOBALS['dictionary'][$object]['indices'] = array_merge($templates[$template]['indices'], $GLOBALS['dictionary'][$object]['indices']);
131 131
             // maintain a record of this objects inheritance from the SugarObject templates...
132
-            $GLOBALS['dictionary'][$object]['templates'][ $template ] = $template ;
132
+            $GLOBALS['dictionary'][$object]['templates'][$template] = $template;
133 133
         }
134 134
     }
135 135
 
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
      */
143 143
     static function cleanVardefs($fieldDefs)
144 144
     {
145
-        if(isset($fieldDefs['fields'])) {
145
+        if (isset($fieldDefs['fields'])) {
146 146
             foreach ($fieldDefs['fields'] as $field => $defs) {
147 147
                 if (empty($defs['name']) || empty($defs['type'])) {
148 148
                     unset($fieldDefs['fields'][$field]);
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
      * @param string $module the name of the module
159 159
      * @param string $object the name of the object
160 160
      */
161
-    static function saveCache($module,$object, $additonal_objects= array()){
161
+    static function saveCache($module, $object, $additonal_objects = array()) {
162 162
 
163 163
         if (empty($GLOBALS['dictionary'][$object]))
164 164
             $object = BeanFactory::getObjectName($module);
@@ -166,17 +166,17 @@  discard block
 block discarded – undo
166 166
         //Sometimes bad definitions can get in from left over extensions or file system lag(caching). We need to clean those.
167 167
         $data = self::cleanVardefs($GLOBALS['dictionary'][$object]);
168 168
 
169
-        $file = create_cache_directory('modules/' . $module . '/' . $object . 'vardefs.php');
169
+        $file = create_cache_directory('modules/'.$module.'/'.$object.'vardefs.php');
170 170
 
171
-        $out="<?php \n \$GLOBALS[\"dictionary\"][\"". $object . "\"]=" . var_export($data, true) .";";
171
+        $out = "<?php \n \$GLOBALS[\"dictionary\"][\"".$object."\"]=".var_export($data, true).";";
172 172
         sugar_file_put_contents_atomic($file, $out);
173
-        if ( is_file($file) && is_readable($file)) {
173
+        if (is_file($file) && is_readable($file)) {
174 174
             include($file);
175 175
         }
176 176
 
177 177
         // put the item in the sugar cache.
178 178
         $key = "VardefManager.$module.$object";
179
-        sugar_cache_put($key,$data);
179
+        sugar_cache_put($key, $data);
180 180
     }
181 181
 
182 182
     /**
@@ -186,14 +186,14 @@  discard block
 block discarded – undo
186 186
      *                      clear vardef cache for all modules.
187 187
      * @param string object_name the name of the object we are clearing this is for sugar_cache
188 188
      */
189
-    static function clearVardef($module_dir = '', $object_name = ''){
189
+    static function clearVardef($module_dir = '', $object_name = '') {
190 190
         //if we have a module name specified then just remove that vardef file
191 191
         //otherwise go through each module and remove the vardefs.php
192
-        if(!empty($module_dir) && !empty($object_name)){
192
+        if (!empty($module_dir) && !empty($object_name)) {
193 193
             VardefManager::_clearCache($module_dir, $object_name);
194
-        }else{
194
+        } else {
195 195
             global $beanList;
196
-            foreach($beanList as $module_dir => $object_name){
196
+            foreach ($beanList as $module_dir => $object_name) {
197 197
                 VardefManager::_clearCache($module_dir, $object_name);
198 198
             }
199 199
         }
@@ -204,8 +204,8 @@  discard block
 block discarded – undo
204 204
      * @param string module_dir the module_dir to clear
205 205
      * @param string object_name the name of the object we are clearing this is for sugar_cache
206 206
      */
207
-    static function _clearCache($module_dir = '', $object_name = ''){
208
-        if(!empty($module_dir) && !empty($object_name)){
207
+    static function _clearCache($module_dir = '', $object_name = '') {
208
+        if (!empty($module_dir) && !empty($object_name)) {
209 209
 
210 210
             //Some modules like cases have a bean name that doesn't match the object name
211 211
             if (empty($GLOBALS['dictionary'][$object_name])) {
@@ -213,9 +213,9 @@  discard block
 block discarded – undo
213 213
                 $object_name = $newName != false ? $newName : $object_name;
214 214
             }
215 215
 
216
-            $file = sugar_cached('modules/').$module_dir.'/' . $object_name . 'vardefs.php';
216
+            $file = sugar_cached('modules/').$module_dir.'/'.$object_name.'vardefs.php';
217 217
 
218
-            if(file_exists($file)){
218
+            if (file_exists($file)) {
219 219
                 unlink($file);
220 220
                 $key = "VardefManager.$module_dir.$object_name";
221 221
                 sugar_cache_clear($key);
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
      * @param string $object the given object we wish to load the vardefs for
232 232
      * @param array $additional_search_paths an array which allows a consumer to pass in additional vardef locations to search
233 233
      */
234
-    static function refreshVardefs($module, $object, $additional_search_paths = null, $cacheCustom = true, $params = array()){
234
+    static function refreshVardefs($module, $object, $additional_search_paths = null, $cacheCustom = true, $params = array()) {
235 235
         // Some of the vardefs do not correctly define dictionary as global.  Declare it first.
236 236
         global $dictionary, $beanList;
237 237
         $vardef_paths = array(
@@ -241,20 +241,20 @@  discard block
 block discarded – undo
241 241
                  );
242 242
 
243 243
         // Add in additional search paths if they were provided.
244
-        if(!empty($additional_search_paths) && is_array($additional_search_paths))
244
+        if (!empty($additional_search_paths) && is_array($additional_search_paths))
245 245
         {
246 246
             $vardef_paths = array_merge($vardef_paths, $additional_search_paths);
247 247
         }
248 248
         $found = false;
249 249
         //search a predefined set of locations for the vardef files
250
-        foreach($vardef_paths as $path){
251
-            if(file_exists($path)){
250
+        foreach ($vardef_paths as $path) {
251
+            if (file_exists($path)) {
252 252
                 require($path);
253 253
                 $found = true;
254 254
             }
255 255
         }
256 256
         //Some modules have multiple beans, we need to see if this object has a module_dir that is different from its module_name
257
-        if(!$found){
257
+        if (!$found) {
258 258
             $temp = BeanFactory::newBean($module);
259 259
             if ($temp)
260 260
             {
@@ -273,15 +273,15 @@  discard block
 block discarded – undo
273 273
         }
274 274
 
275 275
         //load custom fields into the vardef cache
276
-        if($cacheCustom){
276
+        if ($cacheCustom) {
277 277
             require_once("modules/DynamicFields/DynamicField.php");
278
-            $df = new DynamicField ($module) ;
278
+            $df = new DynamicField($module);
279 279
             $df->buildCache($module, false);
280 280
         }
281 281
 
282 282
         //great! now that we have loaded all of our vardefs.
283 283
         //let's go save them to the cache file.
284
-        if(!empty($dictionary[$object])) {
284
+        if (!empty($dictionary[$object])) {
285 285
             VardefManager::saveCache($module, $object);
286 286
         }
287 287
     }
@@ -318,10 +318,10 @@  discard block
 block discarded – undo
318 318
 
319 319
         $vardef = $dictionary[$object];
320 320
         $links = array();
321
-        foreach($vardef['fields'] as $name => $def)
321
+        foreach ($vardef['fields'] as $name => $def)
322 322
         {
323 323
             //Look through all link fields for related modules that have calculated fields that use that relationship
324
-            if(!empty($def['type']) && $def['type'] == 'link' && !empty($def['relationship']))
324
+            if (!empty($def['type']) && $def['type'] == 'link' && !empty($def['relationship']))
325 325
             {
326 326
                 $links[$name] = $def;
327 327
             }
@@ -337,14 +337,14 @@  discard block
 block discarded – undo
337 337
     {
338 338
         $cacheKey = "LFR{$module}{$object}{$relName}";
339 339
         $cacheValue = sugar_cache_retrieve($cacheKey);
340
-        if(!empty($cacheValue))
340
+        if (!empty($cacheValue))
341 341
             return $cacheValue;
342 342
 
343 343
         $relLinkFields = self::getLinkFieldsForModule($module, $object);
344 344
         $matches = array();
345 345
         if (!empty($relLinkFields))
346 346
         {
347
-            foreach($relLinkFields as $rfName => $rfDef)
347
+            foreach ($relLinkFields as $rfName => $rfDef)
348 348
             {
349 349
                 if ($rfDef['relationship'] == $relName)
350 350
                 {
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
             $results = $matches;
362 362
 
363 363
         sugar_cache_put($cacheKey, $results);
364
-        return $results ;
364
+        return $results;
365 365
     }
366 366
 
367 367
 
@@ -400,22 +400,22 @@  discard block
 block discarded – undo
400 400
      * @param string $object the given object we wish to load the vardefs for
401 401
      * @param bool   $refresh whether or not we wish to refresh the cache file.
402 402
      */
403
-    static function loadVardef($module, $object, $refresh=false, $params = array()){
403
+    static function loadVardef($module, $object, $refresh = false, $params = array()) {
404 404
         //here check if the cache file exists, if it does then load it, if it doesn't
405 405
         //then call refreshVardef
406 406
         //if either our session or the system is set to developerMode then refresh is set to true
407
-        if(inDeveloperMode() || !empty($_SESSION['developerMode'])){
407
+        if (inDeveloperMode() || !empty($_SESSION['developerMode'])) {
408 408
             $refresh = true;
409 409
         }
410 410
         // Retrieve the vardefs from cache.
411 411
         $key = "VardefManager.$module.$object";
412 412
 
413
-        if(!$refresh)
413
+        if (!$refresh)
414 414
         {
415 415
             $return_result = sugar_cache_retrieve($key);
416 416
             $return_result = self::applyGlobalAccountRequirements($return_result);
417 417
 
418
-            if(!empty($return_result))
418
+            if (!empty($return_result))
419 419
             {
420 420
                 $GLOBALS['dictionary'][$object] = $return_result;
421 421
                 return;
@@ -424,28 +424,28 @@  discard block
 block discarded – undo
424 424
 
425 425
         // Some of the vardefs do not correctly define dictionary as global.  Declare it first.
426 426
         global $dictionary;
427
-        if(empty($GLOBALS['dictionary'][$object]) || $refresh){
427
+        if (empty($GLOBALS['dictionary'][$object]) || $refresh) {
428 428
             //if the consumer has demanded a refresh or the cache/modules... file
429 429
             //does not exist, then we should do out and try to reload things
430 430
 
431
-			$cachedfile = sugar_cached('modules/'). $module . '/' . $object . 'vardefs.php';
432
-			if($refresh || !file_exists($cachedfile)){
431
+			$cachedfile = sugar_cached('modules/').$module.'/'.$object.'vardefs.php';
432
+			if ($refresh || !file_exists($cachedfile)) {
433 433
 				VardefManager::refreshVardefs($module, $object, null, true, $params);
434 434
 			}
435 435
 
436 436
             //at this point we should have the cache/modules/... file
437 437
             //which was created from the refreshVardefs so let's try to load it.
438
-            if(file_exists($cachedfile))
438
+            if (file_exists($cachedfile))
439 439
             {
440 440
                 if (is_readable($cachedfile))
441 441
                 {
442 442
                     include($cachedfile);
443 443
                 }
444 444
                 // now that we hae loaded the data from disk, put it in the cache.
445
-                if(!empty($GLOBALS['dictionary'][$object]))
445
+                if (!empty($GLOBALS['dictionary'][$object]))
446 446
                 {
447 447
                     $GLOBALS['dictionary'][$object] = self::applyGlobalAccountRequirements($GLOBALS['dictionary'][$object]);
448
-                    sugar_cache_put($key,$GLOBALS['dictionary'][$object]);
448
+                    sugar_cache_put($key, $GLOBALS['dictionary'][$object]);
449 449
                 }
450 450
             }
451 451
         }
Please login to merge, or discard this patch.
Braces   +44 added lines, -24 removed lines patch added patch discarded remove patch
@@ -96,14 +96,18 @@  discard block
 block discarded – undo
96 96
     }
97 97
 
98 98
     static function addTemplate($module, $object, $template, $object_name=false){
99
-        if($template == 'default')$template = 'basic';
99
+        if($template == 'default') {
100
+            $template = 'basic';
101
+        }
100 102
         $templates = array();
101 103
         $fields = array();
102
-        if(empty($object_name))$object_name = $object;
104
+        if(empty($object_name)) {
105
+            $object_name = $object;
106
+        }
103 107
         $_object_name = strtolower($object_name);
104 108
         if(!empty($GLOBALS['dictionary'][$object]['table'])){
105 109
             $table_name = $GLOBALS['dictionary'][$object]['table'];
106
-        }else{
110
+        } else{
107 111
             $table_name = strtolower($module);
108 112
         }
109 113
 
@@ -112,7 +116,7 @@  discard block
 block discarded – undo
112 116
             if(file_exists($path)){
113 117
                 require($path);
114 118
                 $templates[$template] = $vardefs;
115
-            }else{
119
+            } else{
116 120
                 $path = 'include/SugarObjects/implements/' . $template . '/vardefs.php';
117 121
                 if(file_exists($path)){
118 122
                     require($path);
@@ -122,12 +126,22 @@  discard block
 block discarded – undo
122 126
         }
123 127
        
124 128
         if(!empty($templates[$template])){
125
-            if(empty($GLOBALS['dictionary'][$object]['fields']))$GLOBALS['dictionary'][$object]['fields'] = array();
126
-            if(empty($GLOBALS['dictionary'][$object]['relationships']))$GLOBALS['dictionary'][$object]['relationships'] = array();
127
-            if(empty($GLOBALS['dictionary'][$object]['indices']))$GLOBALS['dictionary'][$object]['indices'] = array();
129
+            if(empty($GLOBALS['dictionary'][$object]['fields'])) {
130
+                $GLOBALS['dictionary'][$object]['fields'] = array();
131
+            }
132
+            if(empty($GLOBALS['dictionary'][$object]['relationships'])) {
133
+                $GLOBALS['dictionary'][$object]['relationships'] = array();
134
+            }
135
+            if(empty($GLOBALS['dictionary'][$object]['indices'])) {
136
+                $GLOBALS['dictionary'][$object]['indices'] = array();
137
+            }
128 138
             $GLOBALS['dictionary'][$object]['fields'] = array_merge($templates[$template]['fields'], $GLOBALS['dictionary'][$object]['fields']);
129
-            if(!empty($templates[$template]['relationships']))$GLOBALS['dictionary'][$object]['relationships'] = array_merge($templates[$template]['relationships'], $GLOBALS['dictionary'][$object]['relationships']);
130
-            if(!empty($templates[$template]['indices']))$GLOBALS['dictionary'][$object]['indices'] = array_merge($templates[$template]['indices'], $GLOBALS['dictionary'][$object]['indices']);
139
+            if(!empty($templates[$template]['relationships'])) {
140
+                $GLOBALS['dictionary'][$object]['relationships'] = array_merge($templates[$template]['relationships'], $GLOBALS['dictionary'][$object]['relationships']);
141
+            }
142
+            if(!empty($templates[$template]['indices'])) {
143
+                $GLOBALS['dictionary'][$object]['indices'] = array_merge($templates[$template]['indices'], $GLOBALS['dictionary'][$object]['indices']);
144
+            }
131 145
             // maintain a record of this objects inheritance from the SugarObject templates...
132 146
             $GLOBALS['dictionary'][$object]['templates'][ $template ] = $template ;
133 147
         }
@@ -160,8 +174,9 @@  discard block
 block discarded – undo
160 174
      */
161 175
     static function saveCache($module,$object, $additonal_objects= array()){
162 176
 
163
-        if (empty($GLOBALS['dictionary'][$object]))
164
-            $object = BeanFactory::getObjectName($module);
177
+        if (empty($GLOBALS['dictionary'][$object])) {
178
+                    $object = BeanFactory::getObjectName($module);
179
+        }
165 180
 
166 181
         //Sometimes bad definitions can get in from left over extensions or file system lag(caching). We need to clean those.
167 182
         $data = self::cleanVardefs($GLOBALS['dictionary'][$object]);
@@ -191,7 +206,7 @@  discard block
 block discarded – undo
191 206
         //otherwise go through each module and remove the vardefs.php
192 207
         if(!empty($module_dir) && !empty($object_name)){
193 208
             VardefManager::_clearCache($module_dir, $object_name);
194
-        }else{
209
+        } else{
195 210
             global $beanList;
196 211
             foreach($beanList as $module_dir => $object_name){
197 212
                 VardefManager::_clearCache($module_dir, $object_name);
@@ -310,11 +325,13 @@  discard block
 block discarded – undo
310 325
         }
311 326
 
312 327
         //Cache link fields for this call in a static variable
313
-        if (!isset(self::$linkFields))
314
-            self::$linkFields = array();
328
+        if (!isset(self::$linkFields)) {
329
+                    self::$linkFields = array();
330
+        }
315 331
 
316
-        if (isset(self::$linkFields[$object]))
317
-            return self::$linkFields[$object];
332
+        if (isset(self::$linkFields[$object])) {
333
+                    return self::$linkFields[$object];
334
+        }
318 335
 
319 336
         $vardef = $dictionary[$object];
320 337
         $links = array();
@@ -337,8 +354,9 @@  discard block
 block discarded – undo
337 354
     {
338 355
         $cacheKey = "LFR{$module}{$object}{$relName}";
339 356
         $cacheValue = sugar_cache_retrieve($cacheKey);
340
-        if(!empty($cacheValue))
341
-            return $cacheValue;
357
+        if(!empty($cacheValue)) {
358
+                    return $cacheValue;
359
+        }
342 360
 
343 361
         $relLinkFields = self::getLinkFieldsForModule($module, $object);
344 362
         $matches = array();
@@ -352,13 +370,15 @@  discard block
 block discarded – undo
352 370
                 }
353 371
             }
354 372
         }
355
-        if (empty($matches))
356
-            return false;
357
-        if (sizeof($matches) == 1)
358
-            $results = $matches[0];
359
-        else
360
-            //For relationships where both sides are the same module, more than one link will be returned
373
+        if (empty($matches)) {
374
+                    return false;
375
+        }
376
+        if (sizeof($matches) == 1) {
377
+                    $results = $matches[0];
378
+        } else {
379
+                    //For relationships where both sides are the same module, more than one link will be returned
361 380
             $results = $matches;
381
+        }
362 382
 
363 383
         sugar_cache_put($cacheKey, $results);
364 384
         return $results ;
Please login to merge, or discard this patch.
include/database/SqlsrvManager.php 3 patches
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -143,10 +143,10 @@  discard block
 block discarded – undo
143 143
             'url'      => 'nvarchar',
144 144
             'encrypt'  => 'nvarchar',
145 145
             'file'     => 'nvarchar',
146
-	        'decimal_tpl' => 'decimal(%d, %d)',
146
+            'decimal_tpl' => 'decimal(%d, %d)',
147 147
     );
148 148
 
149
-	/**
149
+    /**
150 150
      * @see DBManager::connect()
151 151
      */
152 152
     public function connect(array $configOptions = null, $dieOnError = false)
@@ -203,10 +203,10 @@  discard block
 block discarded – undo
203 203
         return true;
204 204
     }
205 205
 
206
-	/**
206
+    /**
207 207
      * @see DBManager::query()
208
-	 */
209
-	public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
208
+     */
209
+    public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
210 210
     {
211 211
         if(is_array($sql)) {
212 212
             return $this->queryArray($sql, $dieOnError, $msg, $suppress);
@@ -232,15 +232,15 @@  discard block
 block discarded – undo
232 232
         return $result;
233 233
     }
234 234
 
235
-	/**
235
+    /**
236 236
      * @see DBManager::getFieldsArray()
237 237
      */
238
-	public function getFieldsArray($result, $make_lower_case = false)
239
-	{
238
+    public function getFieldsArray($result, $make_lower_case = false)
239
+    {
240 240
         $field_array = array();
241 241
 
242 242
         if ( !$result ) {
243
-        	return false;
243
+            return false;
244 244
         }
245 245
 
246 246
         foreach ( sqlsrv_field_metadata($result) as $fieldMetadata ) {
@@ -252,16 +252,16 @@  discard block
 block discarded – undo
252 252
         }
253 253
 
254 254
         return $field_array;
255
-	}
255
+    }
256 256
 
257
-	/**
258
-	 * @see DBManager::fetchRow()
259
-	 */
260
-	public function fetchRow($result)
261
-	{
262
-		if (empty($result))	return false;
257
+    /**
258
+     * @see DBManager::fetchRow()
259
+     */
260
+    public function fetchRow($result)
261
+    {
262
+        if (empty($result))	return false;
263 263
 
264
-	    $row = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC);
264
+        $row = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC);
265 265
         if (empty($row)) {
266 266
             return false;
267 267
         }
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
         }
278 278
 
279 279
         return $row;
280
-	}
280
+    }
281 281
 
282 282
     /**
283 283
      * @see DBManager::convert()
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
             return parent::convert($string, $type, $additional_parameters);
292 292
     }
293 293
 
294
-	/**
294
+    /**
295 295
      * Compares two vardefs. Overriding 39098  due to bug: 39098 . IN 6.0 we changed the id columns to dbType = 'id'
296 296
      * for example emails_beans.  In 554 the field email_id was nvarchar but in 6.0 since it id dbType = 'id' we would want to alter
297 297
      * it to varchar. This code will prevent it.
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
      */
318 318
     public function disconnect()
319 319
     {
320
-    	$GLOBALS['log']->debug('Calling Mssql::disconnect()');
320
+        $GLOBALS['log']->debug('Calling Mssql::disconnect()');
321 321
         if(!empty($this->database)){
322 322
             $this->freeResult();
323 323
             sqlsrv_close($this->database);
@@ -335,10 +335,10 @@  discard block
 block discarded – undo
335 335
     }
336 336
 
337 337
 
338
-	/**
339
-	 * Detect if no clustered index has been created for a table; if none created then just pick the first index and make it that
340
-	 *
341
-	 * @see MssqlHelper::indexSQL()
338
+    /**
339
+     * Detect if no clustered index has been created for a table; if none created then just pick the first index and make it that
340
+     *
341
+     * @see MssqlHelper::indexSQL()
342 342
      */
343 343
     public function getConstraintSql($indices, $table)
344 344
     {
@@ -378,12 +378,12 @@  discard block
 block discarded – undo
378 378
                 $columns[$column_name]['len']=strtolower($row['PRECISION']);
379 379
                 $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
380 380
             }
381
-			elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) ) {
382
-				$columns[$column_name]['len']=strtolower($row['PRECISION']);
383
-				if ( $row['TYPE_NAME'] == 'nvarchar' && $row['PRECISION'] == '0' ) {
384
-				    $columns[$column_name]['len']='max';
385
-				}
386
-			}
381
+            elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) ) {
382
+                $columns[$column_name]['len']=strtolower($row['PRECISION']);
383
+                if ( $row['TYPE_NAME'] == 'nvarchar' && $row['PRECISION'] == '0' ) {
384
+                    $columns[$column_name]['len']='max';
385
+                }
386
+            }
387 387
             elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) ) {
388 388
                 $columns[$column_name]['len']=strtolower($row['LENGTH']);
389 389
             }
@@ -488,21 +488,21 @@  discard block
 block discarded – undo
488 488
         return "TRUNCATE TABLE $name";
489 489
     }
490 490
 
491
-	/**
492
-	 * (non-PHPdoc)
493
-	 * @see DBManager::lastDbError()
494
-	 */
491
+    /**
492
+     * (non-PHPdoc)
493
+     * @see DBManager::lastDbError()
494
+     */
495 495
     public function lastDbError()
496 496
     {
497 497
         $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
498 498
         if(empty($errors)) return false;
499 499
         global $app_strings;
500 500
         if (empty($app_strings)
501
-		    or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
502
-			or !isset($app_strings['ERR_MSSQL_WARNING']) ) {
501
+            or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
502
+            or !isset($app_strings['ERR_MSSQL_WARNING']) ) {
503 503
         //ignore the message from sql-server if $app_strings array is empty. This will happen
504 504
         //only if connection if made before languge is set.
505
-		    return false;
505
+            return false;
506 506
         }
507 507
         $messages = array();
508 508
         foreach($errors as $error) {
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
             }
516 516
             $sqlpos = strpos($sqlmsg, $app_strings['ERR_MSSQL_DB_CONTEXT']);
517 517
             $sqlpos2 = strpos($sqlmsg, $app_strings['ERR_MSSQL_WARNING']);
518
-    		if ( $sqlpos !== false || $sqlpos2 !== false) {
518
+            if ( $sqlpos !== false || $sqlpos2 !== false) {
519 519
                     continue;
520 520
             }
521 521
             $messages[] = $sqlmsg;
Please login to merge, or discard this patch.
Spacing   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 3
 /*********************************************************************************
4 4
  * SugarCRM Community Edition is a customer relationship management program developed by
5 5
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
@@ -175,14 +175,14 @@  discard block
 block discarded – undo
175 175
                     "ReturnDatesAsStrings" => true,
176 176
                     "MultipleActiveResultSets" => true,
177 177
                     );
178
-        if(!empty($configOptions['db_name'])) {
178
+        if (!empty($configOptions['db_name'])) {
179 179
             $options["Database"] = $configOptions['db_name'];
180 180
         }
181 181
         $this->database = sqlsrv_connect($connect_param, $options);
182
-        if(empty($this->database)) {
182
+        if (empty($this->database)) {
183 183
             $GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name']." as ".$configOptions['db_user_name'].".");
184
-            if($dieOnError) {
185
-                    if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
184
+            if ($dieOnError) {
185
+                    if (isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
186 186
                         sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
187 187
                     } else {
188 188
                         sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
             }
193 193
         }
194 194
 
195
-        if($this->checkError('Could Not Connect:', $dieOnError))
195
+        if ($this->checkError('Could Not Connect:', $dieOnError))
196 196
             $GLOBALS['log']->info("connected to db");
197 197
 
198 198
         sqlsrv_query($this->database, 'SET DATEFORMAT mdy');
@@ -208,26 +208,26 @@  discard block
 block discarded – undo
208 208
 	 */
209 209
 	public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
210 210
     {
211
-        if(is_array($sql)) {
211
+        if (is_array($sql)) {
212 212
             return $this->queryArray($sql, $dieOnError, $msg, $suppress);
213 213
         }
214 214
         $sql = $this->_appendN($sql);
215 215
 
216 216
         $this->countQuery($sql);
217
-        $GLOBALS['log']->info('Query:' . $sql);
217
+        $GLOBALS['log']->info('Query:'.$sql);
218 218
         $this->checkConnection();
219 219
         $this->query_time = microtime(true);
220 220
 
221
-        $result = $suppress?@sqlsrv_query($this->database, $sql):sqlsrv_query($this->database, $sql);
221
+        $result = $suppress ? @sqlsrv_query($this->database, $sql) : sqlsrv_query($this->database, $sql);
222 222
 
223 223
         $this->query_time = microtime(true) - $this->query_time;
224 224
         $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
225 225
 
226 226
 
227
-        $this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
227
+        $this->checkError($msg.' Query Failed:'.$sql.'::', $dieOnError);
228 228
 
229 229
         //suppress non error messages
230
-        sqlsrv_configure('WarningsReturnAsErrors',false);
230
+        sqlsrv_configure('WarningsReturnAsErrors', false);
231 231
 
232 232
         return $result;
233 233
     }
@@ -239,13 +239,13 @@  discard block
 block discarded – undo
239 239
 	{
240 240
         $field_array = array();
241 241
 
242
-        if ( !$result ) {
242
+        if (!$result) {
243 243
         	return false;
244 244
         }
245 245
 
246
-        foreach ( sqlsrv_field_metadata($result) as $fieldMetadata ) {
246
+        foreach (sqlsrv_field_metadata($result) as $fieldMetadata) {
247 247
             $key = $fieldMetadata['Name'];
248
-            if($make_lower_case==true)
248
+            if ($make_lower_case == true)
249 249
                 $key = strtolower($key);
250 250
 
251 251
             $field_array[] = $key;
@@ -261,12 +261,12 @@  discard block
 block discarded – undo
261 261
 	{
262 262
 		if (empty($result))	return false;
263 263
 
264
-	    $row = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC);
264
+	    $row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC);
265 265
         if (empty($row)) {
266 266
             return false;
267 267
         }
268 268
 
269
-        foreach($row as $key => $column) {
269
+        foreach ($row as $key => $column) {
270 270
             // MSSQL returns a space " " when a varchar column is empty ("") and not null.
271 271
             // We need to strip empty spaces
272 272
             // notice we only strip if one space is returned.  we do not want to strip
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
      */
285 285
     public function convert($string, $type, array $additional_parameters = array())
286 286
     {
287
-        if ( $type == 'datetime')
287
+        if ($type == 'datetime')
288 288
         // see http://msdn.microsoft.com/en-us/library/ms187928.aspx for details
289 289
             return "CONVERT(datetime,$string,120)";
290 290
         else
@@ -300,10 +300,10 @@  discard block
 block discarded – undo
300 300
      * @param  array  $fielddef2
301 301
      * @return bool   true if they match, false if they don't
302 302
      */
303
-    public function compareVarDefs($fielddef1,$fielddef2, $ignoreName = false)
303
+    public function compareVarDefs($fielddef1, $fielddef2, $ignoreName = false)
304 304
     {
305
-        if((isset($fielddef2['dbType']) && $fielddef2['dbType'] == 'id') || preg_match('/(_id$|^id$)/', $fielddef2['name'])){
306
-            if(isset($fielddef1['type']) && isset($fielddef2['type'])){
305
+        if ((isset($fielddef2['dbType']) && $fielddef2['dbType'] == 'id') || preg_match('/(_id$|^id$)/', $fielddef2['name'])) {
306
+            if (isset($fielddef1['type']) && isset($fielddef2['type'])) {
307 307
                 $fielddef2['type'] = $fielddef1['type'];
308 308
             }
309 309
         }
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
     public function disconnect()
319 319
     {
320 320
     	$GLOBALS['log']->debug('Calling Mssql::disconnect()');
321
-        if(!empty($this->database)){
321
+        if (!empty($this->database)) {
322 322
             $this->freeResult();
323 323
             sqlsrv_close($this->database);
324 324
             $this->database = null;
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
      */
331 331
     protected function freeDbResult($dbResult)
332 332
     {
333
-        if(!empty($dbResult))
333
+        if (!empty($dbResult))
334 334
             sqlsrv_free_stmt($dbResult);
335 335
     }
336 336
 
@@ -342,19 +342,19 @@  discard block
 block discarded – undo
342 342
      */
343 343
     public function getConstraintSql($indices, $table)
344 344
     {
345
-        if ( $this->doesTableHaveAClusteredIndexDefined($table) ) {
345
+        if ($this->doesTableHaveAClusteredIndexDefined($table)) {
346 346
             return parent::getConstraintSql($indices, $table);
347 347
         }
348 348
 
349 349
         // check to see if one of the passed in indices is a primary one; if so we can bail as well
350
-        foreach ( $indices as $index ) {
351
-            if ( $index['type'] == 'primary' ) {
350
+        foreach ($indices as $index) {
351
+            if ($index['type'] == 'primary') {
352 352
                 return parent::getConstraintSql($indices, $table);
353 353
             }
354 354
         }
355 355
 
356 356
         // Change the first index listed to be a clustered one instead ( so we have at least one for the table )
357
-        if ( isset($indices[0]) ) {
357
+        if (isset($indices[0])) {
358 358
             $indices[0]['type'] = 'clustered';
359 359
         }
360 360
 
@@ -370,41 +370,41 @@  discard block
 block discarded – undo
370 370
         $result = $this->query("sp_columns_90 $tablename");
371 371
 
372 372
         $columns = array();
373
-        while (($row=$this->fetchByAssoc($result)) !=null) {
373
+        while (($row = $this->fetchByAssoc($result)) != null) {
374 374
             $column_name = strtolower($row['COLUMN_NAME']);
375
-            $columns[$column_name]['name']=$column_name;
376
-            $columns[$column_name]['type']=strtolower($row['TYPE_NAME']);
377
-            if ( $row['TYPE_NAME'] == 'decimal' ) {
378
-                $columns[$column_name]['len']=strtolower($row['PRECISION']);
379
-                $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
375
+            $columns[$column_name]['name'] = $column_name;
376
+            $columns[$column_name]['type'] = strtolower($row['TYPE_NAME']);
377
+            if ($row['TYPE_NAME'] == 'decimal') {
378
+                $columns[$column_name]['len'] = strtolower($row['PRECISION']);
379
+                $columns[$column_name]['len'] .= ','.strtolower($row['SCALE']);
380 380
             }
381
-			elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) ) {
382
-				$columns[$column_name]['len']=strtolower($row['PRECISION']);
383
-				if ( $row['TYPE_NAME'] == 'nvarchar' && $row['PRECISION'] == '0' ) {
384
-				    $columns[$column_name]['len']='max';
381
+			elseif (in_array($row['TYPE_NAME'], array('nchar', 'nvarchar'))) {
382
+				$columns[$column_name]['len'] = strtolower($row['PRECISION']);
383
+				if ($row['TYPE_NAME'] == 'nvarchar' && $row['PRECISION'] == '0') {
384
+				    $columns[$column_name]['len'] = 'max';
385 385
 				}
386 386
 			}
387
-            elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) ) {
388
-                $columns[$column_name]['len']=strtolower($row['LENGTH']);
387
+            elseif (!in_array($row['TYPE_NAME'], array('datetime', 'text'))) {
388
+                $columns[$column_name]['len'] = strtolower($row['LENGTH']);
389 389
             }
390
-            if ( stristr($row['TYPE_NAME'],'identity') ) {
390
+            if (stristr($row['TYPE_NAME'], 'identity')) {
391 391
                 $columns[$column_name]['auto_increment'] = '1';
392
-                $columns[$column_name]['type']=str_replace(' identity','',strtolower($row['TYPE_NAME']));
392
+                $columns[$column_name]['type'] = str_replace(' identity', '', strtolower($row['TYPE_NAME']));
393 393
             }
394 394
 
395
-            if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI')))
395
+            if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'], 'PRI')))
396 396
                 $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
397 397
 
398 398
             $column_def = 1;
399
-            if ( strtolower($tablename) == 'relationships' ) {
399
+            if (strtolower($tablename) == 'relationships') {
400 400
                 $column_def = $this->getOne("select cdefault from syscolumns where id = object_id('relationships') and name = '$column_name'");
401 401
             }
402
-            if ( $column_def != 0 && ($row['COLUMN_DEF'] != null)) {	// NOTE Not using !empty as an empty string may be a viable default value.
402
+            if ($column_def != 0 && ($row['COLUMN_DEF'] != null)) {	// NOTE Not using !empty as an empty string may be a viable default value.
403 403
                 $matches = array();
404
-                $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'],ENT_QUOTES);
405
-                if ( preg_match('/\([\(|\'](.*)[\)|\']\)/i',$row['COLUMN_DEF'],$matches) )
404
+                $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'], ENT_QUOTES);
405
+                if (preg_match('/\([\(|\'](.*)[\)|\']\)/i', $row['COLUMN_DEF'], $matches))
406 406
                     $columns[$column_name]['default'] = $matches[1];
407
-                elseif ( preg_match('/\(N\'(.*)\'\)/i',$row['COLUMN_DEF'],$matches) )
407
+                elseif (preg_match('/\(N\'(.*)\'\)/i', $row['COLUMN_DEF'], $matches))
408 408
                     $columns[$column_name]['default'] = $matches[1];
409 409
                 else
410 410
                     $columns[$column_name]['default'] = $row['COLUMN_DEF'];
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 EOSQL;
431 431
 
432 432
         $result = $this->getOne($query);
433
-        if ( !$result ) {
433
+        if (!$result) {
434 434
             return false;
435 435
         }
436 436
 
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
 EOSQL;
454 454
 
455 455
         $result = $this->getOne($query);
456
-        if ( !$result ) {
456
+        if (!$result) {
457 457
             return false;
458 458
         }
459 459
 
@@ -466,10 +466,10 @@  discard block
 block discarded – undo
466 466
      * @see DBManager::changeColumnSQL()
467 467
      * @see MssqlHelper::changeColumnSQL()
468 468
      */
469
-    protected function changeColumnSQL($tablename,$fieldDefs, $action, $ignoreRequired = false)
469
+    protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
470 470
     {
471 471
         $sql = '';
472
-        if ( $action == 'drop' && $this->doesTableHaveAFulltextIndexDefined($tablename) ) {
472
+        if ($action == 'drop' && $this->doesTableHaveAFulltextIndexDefined($tablename)) {
473 473
             $sql .= "DROP FULLTEXT INDEX ON {$tablename}";
474 474
         }
475 475
 
@@ -495,33 +495,33 @@  discard block
 block discarded – undo
495 495
     public function lastDbError()
496 496
     {
497 497
         $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
498
-        if(empty($errors)) return false;
498
+        if (empty($errors)) return false;
499 499
         global $app_strings;
500 500
         if (empty($app_strings)
501 501
 		    or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
502
-			or !isset($app_strings['ERR_MSSQL_WARNING']) ) {
502
+			or !isset($app_strings['ERR_MSSQL_WARNING'])) {
503 503
         //ignore the message from sql-server if $app_strings array is empty. This will happen
504 504
         //only if connection if made before languge is set.
505 505
 		    return false;
506 506
         }
507 507
         $messages = array();
508
-        foreach($errors as $error) {
508
+        foreach ($errors as $error) {
509 509
             $sqlmsg = $error['message'];
510 510
             $sqlpos = strpos($sqlmsg, 'Changed database context to');
511 511
             $sqlpos2 = strpos($sqlmsg, 'Warning:');
512 512
             $sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
513
-            if ( $sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false ) {
513
+            if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false) {
514 514
                 continue;
515 515
             }
516 516
             $sqlpos = strpos($sqlmsg, $app_strings['ERR_MSSQL_DB_CONTEXT']);
517 517
             $sqlpos2 = strpos($sqlmsg, $app_strings['ERR_MSSQL_WARNING']);
518
-    		if ( $sqlpos !== false || $sqlpos2 !== false) {
518
+    		if ($sqlpos !== false || $sqlpos2 !== false) {
519 519
                     continue;
520 520
             }
521 521
             $messages[] = $sqlmsg;
522 522
         }
523 523
 
524
-        if(!empty($messages)) {
524
+        if (!empty($messages)) {
525 525
             return join("\n", $messages);
526 526
         }
527 527
         return false;
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
     protected function verifyGenericQueryRollback($type, $table, $query)
549 549
     {
550 550
         $this->log->debug("verifying $type statement");
551
-        if(!sqlsrv_begin_transaction($this->database)) {
551
+        if (!sqlsrv_begin_transaction($this->database)) {
552 552
             return "Failed to create transaction";
553 553
         }
554 554
         $this->query($query, false);
Please login to merge, or discard this patch.
Braces   +43 added lines, -31 removed lines patch added patch discarded remove patch
@@ -1,5 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if(!defined('sugarEntry') || !sugarEntry) {
3
+    die('Not A Valid Entry Point');
4
+}
3 5
 /*********************************************************************************
4 6
  * SugarCRM Community Edition is a customer relationship management program developed by
5 7
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
@@ -153,16 +155,18 @@  discard block
 block discarded – undo
153 155
     {
154 156
         global $sugar_config;
155 157
 
156
-        if (is_null($configOptions))
157
-            $configOptions = $sugar_config['dbconfig'];
158
+        if (is_null($configOptions)) {
159
+                    $configOptions = $sugar_config['dbconfig'];
160
+        }
158 161
 
159 162
         //set the connections parameters
160 163
         $connect_param = '';
161 164
         $configOptions['db_host_instance'] = trim($configOptions['db_host_instance']);
162
-        if (empty($configOptions['db_host_instance']))
163
-            $connect_param = $configOptions['db_host_name'];
164
-        else
165
-            $connect_param = $configOptions['db_host_name']."\\".$configOptions['db_host_instance'];
165
+        if (empty($configOptions['db_host_instance'])) {
166
+                    $connect_param = $configOptions['db_host_name'];
167
+        } else {
168
+                    $connect_param = $configOptions['db_host_name']."\\".$configOptions['db_host_instance'];
169
+        }
166 170
 
167 171
         /*
168 172
          * Don't try to specifically use a persistent connection
@@ -192,8 +196,9 @@  discard block
 block discarded – undo
192 196
             }
193 197
         }
194 198
 
195
-        if($this->checkError('Could Not Connect:', $dieOnError))
196
-            $GLOBALS['log']->info("connected to db");
199
+        if($this->checkError('Could Not Connect:', $dieOnError)) {
200
+                    $GLOBALS['log']->info("connected to db");
201
+        }
197 202
 
198 203
         sqlsrv_query($this->database, 'SET DATEFORMAT mdy');
199 204
 
@@ -245,8 +250,9 @@  discard block
 block discarded – undo
245 250
 
246 251
         foreach ( sqlsrv_field_metadata($result) as $fieldMetadata ) {
247 252
             $key = $fieldMetadata['Name'];
248
-            if($make_lower_case==true)
249
-                $key = strtolower($key);
253
+            if($make_lower_case==true) {
254
+                            $key = strtolower($key);
255
+            }
250 256
 
251 257
             $field_array[] = $key;
252 258
         }
@@ -259,7 +265,9 @@  discard block
 block discarded – undo
259 265
 	 */
260 266
 	public function fetchRow($result)
261 267
 	{
262
-		if (empty($result))	return false;
268
+		if (empty($result)) {
269
+		    return false;
270
+		}
263 271
 
264 272
 	    $row = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC);
265 273
         if (empty($row)) {
@@ -284,11 +292,12 @@  discard block
 block discarded – undo
284 292
      */
285 293
     public function convert($string, $type, array $additional_parameters = array())
286 294
     {
287
-        if ( $type == 'datetime')
288
-        // see http://msdn.microsoft.com/en-us/library/ms187928.aspx for details
295
+        if ( $type == 'datetime') {
296
+                // see http://msdn.microsoft.com/en-us/library/ms187928.aspx for details
289 297
             return "CONVERT(datetime,$string,120)";
290
-        else
291
-            return parent::convert($string, $type, $additional_parameters);
298
+        } else {
299
+                    return parent::convert($string, $type, $additional_parameters);
300
+        }
292 301
     }
293 302
 
294 303
 	/**
@@ -330,8 +339,9 @@  discard block
 block discarded – undo
330 339
      */
331 340
     protected function freeDbResult($dbResult)
332 341
     {
333
-        if(!empty($dbResult))
334
-            sqlsrv_free_stmt($dbResult);
342
+        if(!empty($dbResult)) {
343
+                    sqlsrv_free_stmt($dbResult);
344
+        }
335 345
     }
336 346
 
337 347
 
@@ -377,14 +387,12 @@  discard block
 block discarded – undo
377 387
             if ( $row['TYPE_NAME'] == 'decimal' ) {
378 388
                 $columns[$column_name]['len']=strtolower($row['PRECISION']);
379 389
                 $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
380
-            }
381
-			elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) ) {
390
+            } elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) ) {
382 391
 				$columns[$column_name]['len']=strtolower($row['PRECISION']);
383 392
 				if ( $row['TYPE_NAME'] == 'nvarchar' && $row['PRECISION'] == '0' ) {
384 393
 				    $columns[$column_name]['len']='max';
385 394
 				}
386
-			}
387
-            elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) ) {
395
+			} elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) ) {
388 396
                 $columns[$column_name]['len']=strtolower($row['LENGTH']);
389 397
             }
390 398
             if ( stristr($row['TYPE_NAME'],'identity') ) {
@@ -392,8 +400,9 @@  discard block
 block discarded – undo
392 400
                 $columns[$column_name]['type']=str_replace(' identity','',strtolower($row['TYPE_NAME']));
393 401
             }
394 402
 
395
-            if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI')))
396
-                $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
403
+            if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI'))) {
404
+                            $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
405
+            }
397 406
 
398 407
             $column_def = 1;
399 408
             if ( strtolower($tablename) == 'relationships' ) {
@@ -402,12 +411,13 @@  discard block
 block discarded – undo
402 411
             if ( $column_def != 0 && ($row['COLUMN_DEF'] != null)) {	// NOTE Not using !empty as an empty string may be a viable default value.
403 412
                 $matches = array();
404 413
                 $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'],ENT_QUOTES);
405
-                if ( preg_match('/\([\(|\'](.*)[\)|\']\)/i',$row['COLUMN_DEF'],$matches) )
406
-                    $columns[$column_name]['default'] = $matches[1];
407
-                elseif ( preg_match('/\(N\'(.*)\'\)/i',$row['COLUMN_DEF'],$matches) )
408
-                    $columns[$column_name]['default'] = $matches[1];
409
-                else
410
-                    $columns[$column_name]['default'] = $row['COLUMN_DEF'];
414
+                if ( preg_match('/\([\(|\'](.*)[\)|\']\)/i',$row['COLUMN_DEF'],$matches) ) {
415
+                                    $columns[$column_name]['default'] = $matches[1];
416
+                } elseif ( preg_match('/\(N\'(.*)\'\)/i',$row['COLUMN_DEF'],$matches) ) {
417
+                                    $columns[$column_name]['default'] = $matches[1];
418
+                } else {
419
+                                    $columns[$column_name]['default'] = $row['COLUMN_DEF'];
420
+                }
411 421
             }
412 422
         }
413 423
         return $columns;
@@ -495,7 +505,9 @@  discard block
 block discarded – undo
495 505
     public function lastDbError()
496 506
     {
497 507
         $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
498
-        if(empty($errors)) return false;
508
+        if(empty($errors)) {
509
+            return false;
510
+        }
499 511
         global $app_strings;
500 512
         if (empty($app_strings)
501 513
 		    or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
Please login to merge, or discard this patch.
include/database/MysqlManager.php 4 patches
Switch Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -825,33 +825,33 @@  discard block
 block discarded – undo
825 825
 			$fields = $index['fields'];
826 826
 
827 827
 		switch ($type) {
828
-		case 'unique':
829
-			$columns[] = " UNIQUE $name ($fields)";
830
-			break;
831
-		case 'primary':
832
-			$columns[] = " PRIMARY KEY ($fields)";
833
-			break;
834
-		case 'index':
835
-		case 'foreign':
836
-		case 'clustered':
837
-		case 'alternate_key':
838
-			/**
828
+		    case 'unique':
829
+			    $columns[] = " UNIQUE $name ($fields)";
830
+			    break;
831
+		    case 'primary':
832
+			    $columns[] = " PRIMARY KEY ($fields)";
833
+			    break;
834
+		    case 'index':
835
+		    case 'foreign':
836
+		    case 'clustered':
837
+		    case 'alternate_key':
838
+			    /**
839 839
 				* @todo here it is assumed that the primary key of the foreign
840 840
 				* table will always be named 'id'. It must be noted though
841 841
 				* that this can easily be fixed by referring to db dictionary
842 842
 				* to find the correct primary field name
843 843
 				*/
844
-			if ( $alter_table )
845
-				$columns[] = " INDEX $name ($fields)";
846
-			else
847
-				$columns[] = " KEY $name ($fields)";
848
-			break;
849
-		case 'fulltext':
850
-			if ($this->full_text_indexing_installed())
851
-				$columns[] = " FULLTEXT ($fields)";
852
-			else
853
-				$GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
854
-			break;
844
+			    if ( $alter_table )
845
+				    $columns[] = " INDEX $name ($fields)";
846
+			    else
847
+				    $columns[] = " KEY $name ($fields)";
848
+			    break;
849
+		    case 'fulltext':
850
+			    if ($this->full_text_indexing_installed())
851
+				    $columns[] = " FULLTEXT ($fields)";
852
+			    else
853
+				    $GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
854
+			    break;
855 855
 		}
856 856
 	}
857 857
 	$columns = implode(", $alter_action ", $columns);
@@ -935,33 +935,33 @@  discard block
 block discarded – undo
935 935
 
936 936
 		switch ($type){
937 937
 		// generic indices
938
-		case 'index':
939
-		case 'alternate_key':
940
-		case 'clustered':
941
-			if ($drop)
942
-				$sql = "ALTER TABLE {$table} DROP INDEX {$name} ";
943
-			else
944
-				$sql = "ALTER TABLE {$table} ADD INDEX {$name} ({$fields})";
945
-			break;
946
-		// constraints as indices
947
-		case 'unique':
948
-			if ($drop)
949
-				$sql = "ALTER TABLE {$table} DROP INDEX $name";
950
-			else
951
-				$sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
952
-			break;
953
-		case 'primary':
954
-			if ($drop)
955
-				$sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
956
-			else
957
-				$sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
958
-			break;
959
-		case 'foreign':
960
-			if ($drop)
961
-				$sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
962
-			else
963
-				$sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignField']})";
964
-			break;
938
+		    case 'index':
939
+		    case 'alternate_key':
940
+		    case 'clustered':
941
+			    if ($drop)
942
+				    $sql = "ALTER TABLE {$table} DROP INDEX {$name} ";
943
+			    else
944
+				    $sql = "ALTER TABLE {$table} ADD INDEX {$name} ({$fields})";
945
+			    break;
946
+		    // constraints as indices
947
+		    case 'unique':
948
+			    if ($drop)
949
+				    $sql = "ALTER TABLE {$table} DROP INDEX $name";
950
+			    else
951
+				    $sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
952
+			    break;
953
+		    case 'primary':
954
+			    if ($drop)
955
+				    $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
956
+			    else
957
+				    $sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
958
+			    break;
959
+		    case 'foreign':
960
+			    if ($drop)
961
+				    $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
962
+			    else
963
+				    $sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignField']})";
964
+			    break;
965 965
 		}
966 966
 		return $sql;
967 967
 	}
Please login to merge, or discard this patch.
Indentation   +1344 added lines, -1344 removed lines patch added patch discarded remove patch
@@ -100,368 +100,368 @@  discard block
 block discarded – undo
100 100
  */
101 101
 class MysqlManager extends DBManager
102 102
 {
103
-	/**
104
-	 * @see DBManager::$dbType
105
-	 */
106
-	public $dbType = 'mysql';
107
-	public $variant = 'mysql';
108
-	public $dbName = 'MySQL';
109
-	public $label = 'LBL_MYSQL';
110
-
111
-	protected $maxNameLengths = array(
112
-		'table' => 64,
113
-		'column' => 64,
114
-		'index' => 64,
115
-		'alias' => 256
116
-	);
117
-
118
-	protected $type_map = array(
119
-			'int'      => 'int',
120
-			'double'   => 'double',
121
-			'float'    => 'float',
122
-			'uint'     => 'int unsigned',
123
-			'ulong'    => 'bigint unsigned',
124
-			'long'     => 'bigint',
125
-			'short'    => 'smallint',
126
-			'varchar'  => 'varchar',
127
-			'text'     => 'text',
128
-			'longtext' => 'longtext',
129
-			'date'     => 'date',
130
-			'enum'     => 'varchar',
131
-			'relate'   => 'varchar',
132
-			'multienum'=> 'text',
133
-			'html'     => 'text',
134
-			'longhtml' => 'longtext',
135
-			'datetime' => 'datetime',
136
-			'datetimecombo' => 'datetime',
137
-			'time'     => 'time',
138
-			'bool'     => 'bool',
139
-			'tinyint'  => 'tinyint',
140
-			'char'     => 'char',
141
-			'blob'     => 'blob',
142
-			'longblob' => 'longblob',
143
-			'currency' => 'decimal(26,6)',
144
-			'decimal'  => 'decimal',
145
-			'decimal2' => 'decimal',
146
-			'id'       => 'char(36)',
147
-			'url'      => 'varchar',
148
-			'encrypt'  => 'varchar',
149
-			'file'     => 'varchar',
150
-			'decimal_tpl' => 'decimal(%d, %d)',
151
-
152
-	);
153
-
154
-	protected $capabilities = array(
155
-		"affected_rows" => true,
156
-		"select_rows" => true,
157
-		"inline_keys" => true,
158
-		"create_user" => true,
159
-		"fulltext" => true,
160
-	    "collation" => true,
161
-	    "create_db" => true,
162
-	    "disable_keys" => true,
163
-	);
164
-
165
-	/**
166
-	 * Parses and runs queries
167
-	 *
168
-	 * @param  string   $sql        SQL Statement to execute
169
-	 * @param  bool     $dieOnError True if we want to call die if the query returns errors
170
-	 * @param  string   $msg        Message to log if error occurs
171
-	 * @param  bool     $suppress   Flag to suppress all error output unless in debug logging mode.
172
-	 * @param  bool     $keepResult True if we want to push this result into the $lastResult array.
173
-	 * @return resource result set
174
-	 */
175
-	public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
176
-	{
177
-		if(is_array($sql)) {
178
-			return $this->queryArray($sql, $dieOnError, $msg, $suppress);
179
-		}
180
-
181
-		parent::countQuery($sql);
182
-		$GLOBALS['log']->info('Query:' . $sql);
183
-		$this->checkConnection();
184
-		$this->query_time = microtime(true);
185
-		$this->lastsql = $sql;
186
-		$result = $suppress?@mysql_query($sql, $this->database):mysql_query($sql, $this->database);
187
-
188
-		$this->query_time = microtime(true) - $this->query_time;
189
-		$GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
190
-
191
-
192
-		if($keepResult)
193
-			$this->lastResult = $result;
194
-
195
-		$this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
196
-		return $result;
197
-	}
103
+    /**
104
+     * @see DBManager::$dbType
105
+     */
106
+    public $dbType = 'mysql';
107
+    public $variant = 'mysql';
108
+    public $dbName = 'MySQL';
109
+    public $label = 'LBL_MYSQL';
110
+
111
+    protected $maxNameLengths = array(
112
+        'table' => 64,
113
+        'column' => 64,
114
+        'index' => 64,
115
+        'alias' => 256
116
+    );
117
+
118
+    protected $type_map = array(
119
+            'int'      => 'int',
120
+            'double'   => 'double',
121
+            'float'    => 'float',
122
+            'uint'     => 'int unsigned',
123
+            'ulong'    => 'bigint unsigned',
124
+            'long'     => 'bigint',
125
+            'short'    => 'smallint',
126
+            'varchar'  => 'varchar',
127
+            'text'     => 'text',
128
+            'longtext' => 'longtext',
129
+            'date'     => 'date',
130
+            'enum'     => 'varchar',
131
+            'relate'   => 'varchar',
132
+            'multienum'=> 'text',
133
+            'html'     => 'text',
134
+            'longhtml' => 'longtext',
135
+            'datetime' => 'datetime',
136
+            'datetimecombo' => 'datetime',
137
+            'time'     => 'time',
138
+            'bool'     => 'bool',
139
+            'tinyint'  => 'tinyint',
140
+            'char'     => 'char',
141
+            'blob'     => 'blob',
142
+            'longblob' => 'longblob',
143
+            'currency' => 'decimal(26,6)',
144
+            'decimal'  => 'decimal',
145
+            'decimal2' => 'decimal',
146
+            'id'       => 'char(36)',
147
+            'url'      => 'varchar',
148
+            'encrypt'  => 'varchar',
149
+            'file'     => 'varchar',
150
+            'decimal_tpl' => 'decimal(%d, %d)',
151
+
152
+    );
153
+
154
+    protected $capabilities = array(
155
+        "affected_rows" => true,
156
+        "select_rows" => true,
157
+        "inline_keys" => true,
158
+        "create_user" => true,
159
+        "fulltext" => true,
160
+        "collation" => true,
161
+        "create_db" => true,
162
+        "disable_keys" => true,
163
+    );
164
+
165
+    /**
166
+     * Parses and runs queries
167
+     *
168
+     * @param  string   $sql        SQL Statement to execute
169
+     * @param  bool     $dieOnError True if we want to call die if the query returns errors
170
+     * @param  string   $msg        Message to log if error occurs
171
+     * @param  bool     $suppress   Flag to suppress all error output unless in debug logging mode.
172
+     * @param  bool     $keepResult True if we want to push this result into the $lastResult array.
173
+     * @return resource result set
174
+     */
175
+    public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
176
+    {
177
+        if(is_array($sql)) {
178
+            return $this->queryArray($sql, $dieOnError, $msg, $suppress);
179
+        }
180
+
181
+        parent::countQuery($sql);
182
+        $GLOBALS['log']->info('Query:' . $sql);
183
+        $this->checkConnection();
184
+        $this->query_time = microtime(true);
185
+        $this->lastsql = $sql;
186
+        $result = $suppress?@mysql_query($sql, $this->database):mysql_query($sql, $this->database);
187
+
188
+        $this->query_time = microtime(true) - $this->query_time;
189
+        $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
190
+
191
+
192
+        if($keepResult)
193
+            $this->lastResult = $result;
194
+
195
+        $this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
196
+        return $result;
197
+    }
198 198
 
199 199
     /**
200 200
      * Returns the number of rows affected by the last query
201 201
      * @param $result
202 202
      * @return int
203 203
      */
204
-	public function getAffectedRowCount($result)
205
-	{
206
-		return mysql_affected_rows($this->getDatabase());
207
-	}
208
-
209
-	/**
210
-	 * Returns the number of rows returned by the result
211
-	 *
212
-	 * This function can't be reliably implemented on most DB, do not use it.
213
-	 * @abstract
214
-	 * @deprecated
215
-	 * @param  resource $result
216
-	 * @return int
217
-	 */
218
-	public function getRowCount($result)
219
-	{
220
-	    return mysql_num_rows($result);
221
-	}
222
-
223
-	/**
224
-	 * Disconnects from the database
225
-	 *
226
-	 * Also handles any cleanup needed
227
-	 */
228
-	public function disconnect()
229
-	{
230
-		$GLOBALS['log']->debug('Calling MySQL::disconnect()');
231
-		if(!empty($this->database)){
232
-			$this->freeResult();
233
-			mysql_close($this->database);
234
-			$this->database = null;
235
-		}
236
-	}
237
-
238
-	/**
239
-	 * @see DBManager::freeDbResult()
240
-	 */
241
-	protected function freeDbResult($dbResult)
242
-	{
243
-		if(!empty($dbResult))
244
-			mysql_free_result($dbResult);
245
-	}
246
-
247
-
248
-	/**
249
-	 * @abstract
250
-	 * Check if query has LIMIT clause
251
-	 * Relevant for now only for Mysql
252
-	 * @param string $sql
253
-	 * @return bool
254
-	 */
255
-	protected function hasLimit($sql)
256
-	{
257
-	    return stripos($sql, " limit ") !== false;
258
-	}
259
-
260
-	/**
261
-	 * @see DBManager::limitQuery()
262
-	 */
263
-	public function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true)
264
-	{
204
+    public function getAffectedRowCount($result)
205
+    {
206
+        return mysql_affected_rows($this->getDatabase());
207
+    }
208
+
209
+    /**
210
+     * Returns the number of rows returned by the result
211
+     *
212
+     * This function can't be reliably implemented on most DB, do not use it.
213
+     * @abstract
214
+     * @deprecated
215
+     * @param  resource $result
216
+     * @return int
217
+     */
218
+    public function getRowCount($result)
219
+    {
220
+        return mysql_num_rows($result);
221
+    }
222
+
223
+    /**
224
+     * Disconnects from the database
225
+     *
226
+     * Also handles any cleanup needed
227
+     */
228
+    public function disconnect()
229
+    {
230
+        $GLOBALS['log']->debug('Calling MySQL::disconnect()');
231
+        if(!empty($this->database)){
232
+            $this->freeResult();
233
+            mysql_close($this->database);
234
+            $this->database = null;
235
+        }
236
+    }
237
+
238
+    /**
239
+     * @see DBManager::freeDbResult()
240
+     */
241
+    protected function freeDbResult($dbResult)
242
+    {
243
+        if(!empty($dbResult))
244
+            mysql_free_result($dbResult);
245
+    }
246
+
247
+
248
+    /**
249
+     * @abstract
250
+     * Check if query has LIMIT clause
251
+     * Relevant for now only for Mysql
252
+     * @param string $sql
253
+     * @return bool
254
+     */
255
+    protected function hasLimit($sql)
256
+    {
257
+        return stripos($sql, " limit ") !== false;
258
+    }
259
+
260
+    /**
261
+     * @see DBManager::limitQuery()
262
+     */
263
+    public function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true)
264
+    {
265 265
         $start = (int)$start;
266 266
         $count = (int)$count;
267
-	    if ($start < 0)
268
-			$start = 0;
269
-		$GLOBALS['log']->debug('Limit Query:' . $sql. ' Start: ' .$start . ' count: ' . $count);
270
-
271
-	    $sql = "$sql LIMIT $start,$count";
272
-		$this->lastsql = $sql;
273
-
274
-		if(!empty($GLOBALS['sugar_config']['check_query'])){
275
-			$this->checkQuery($sql);
276
-		}
277
-		if(!$execute) {
278
-			return $sql;
279
-		}
280
-
281
-		return $this->query($sql, $dieOnError, $msg);
282
-	}
283
-
284
-
285
-	/**
286
-	 * @see DBManager::checkQuery()
287
-	 */
288
-	protected function checkQuery($sql, $object_name = false)
289
-	{
290
-		$result   = $this->query('EXPLAIN ' . $sql);
291
-		$badQuery = array();
292
-		while ($row = $this->fetchByAssoc($result)) {
293
-			if (empty($row['table']))
294
-				continue;
295
-			$badQuery[$row['table']] = '';
296
-			if (strtoupper($row['type']) == 'ALL')
297
-				$badQuery[$row['table']]  .=  ' Full Table Scan;';
298
-			if (empty($row['key']))
299
-				$badQuery[$row['table']] .= ' No Index Key Used;';
300
-			if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using filesort') > 0)
301
-				$badQuery[$row['table']] .= ' Using FileSort;';
302
-			if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using temporary') > 0)
303
-				$badQuery[$row['table']] .= ' Using Temporary Table;';
304
-		}
305
-
306
-		if ( empty($badQuery) )
307
-			return true;
308
-
309
-		foreach($badQuery as $table=>$data ){
310
-			if(!empty($data)){
311
-				$warning = ' Table:' . $table . ' Data:' . $data;
312
-				if(!empty($GLOBALS['sugar_config']['check_query_log'])){
313
-					$GLOBALS['log']->fatal($sql);
314
-					$GLOBALS['log']->fatal('CHECK QUERY:' .$warning);
315
-				}
316
-				else{
317
-					$GLOBALS['log']->warn('CHECK QUERY:' .$warning);
318
-				}
319
-			}
320
-		}
321
-
322
-		return false;
323
-	}
324
-
325
-	/**
326
-	 * @see DBManager::get_columns()
327
-	 */
328
-	public function get_columns($tablename)
329
-	{
330
-		//find all unique indexes and primary keys.
331
-		$result = $this->query("DESCRIBE $tablename");
332
-
333
-		$columns = array();
334
-		while (($row=$this->fetchByAssoc($result)) !=null) {
335
-			$name = strtolower($row['Field']);
336
-			$columns[$name]['name']=$name;
337
-			$matches = array();
338
-			preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*)\)|)( unsigned)?/i', $row['Type'], $matches);
339
-			$columns[$name]['type']=strtolower($matches[1][0]);
340
-			if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) )
341
-				$columns[$name]['len']=strtolower($matches[2][0]);
342
-			if ( stristr($row['Extra'],'auto_increment') )
343
-				$columns[$name]['auto_increment'] = '1';
344
-			if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI'))
345
-				$columns[$name]['required'] = 'true';
346
-			if (!empty($row['Default']) )
347
-				$columns[$name]['default'] = $row['Default'];
348
-		}
349
-		return $columns;
350
-	}
351
-
352
-	/**
353
-	 * @see DBManager::getFieldsArray()
354
-	 */
355
-	public function getFieldsArray($result, $make_lower_case=false)
356
-	{
357
-		$field_array = array();
358
-
359
-		if(empty($result))
360
-			return 0;
361
-
362
-		$fields = mysql_num_fields($result);
363
-		for ($i=0; $i < $fields; $i++) {
364
-			$meta = mysql_fetch_field($result, $i);
365
-			if (!$meta)
366
-				return array();
367
-
368
-			if($make_lower_case == true)
369
-				$meta->name = strtolower($meta->name);
370
-
371
-			$field_array[] = $meta->name;
372
-		}
373
-
374
-		return $field_array;
375
-	}
376
-
377
-	/**
378
-	 * @see DBManager::fetchRow()
379
-	 */
380
-	public function fetchRow($result)
381
-	{
382
-		if (empty($result))	return false;
383
-
384
-		return mysql_fetch_assoc($result);
385
-	}
386
-
387
-	/**
388
-	 * @see DBManager::getTablesArray()
389
-	 */
390
-	public function getTablesArray()
391
-	{
392
-		$this->log->debug('Fetching table list');
393
-
394
-		if ($this->getDatabase()) {
395
-			$tables = array();
396
-			$r = $this->query('SHOW TABLES');
397
-			if (!empty($r)) {
398
-				while ($a = $this->fetchByAssoc($r)) {
399
-					$row = array_values($a);
400
-					$tables[]=$row[0];
401
-				}
402
-				return $tables;
403
-			}
404
-		}
405
-
406
-		return false; // no database available
407
-	}
408
-
409
-	/**
410
-	 * @see DBManager::version()
411
-	 */
412
-	public function version()
413
-	{
414
-		return $this->getOne("SELECT version() version");
415
-	}
416
-
417
-	/**
418
-	 * @see DBManager::tableExists()
419
-	 */
420
-	public function tableExists($tableName)
421
-	{
422
-		$this->log->info("tableExists: $tableName");
423
-
424
-		if ($this->getDatabase()) {
425
-			$result = $this->query("SHOW TABLES LIKE ".$this->quoted($tableName));
426
-			if(empty($result)) return false;
427
-			$row = $this->fetchByAssoc($result);
428
-			return !empty($row);
429
-		}
430
-
431
-		return false;
432
-	}
433
-
434
-	/**
435
-	 * Get tables like expression
436
-	 * @param $like string
437
-	 * @return array
438
-	 */
439
-	public function tablesLike($like)
440
-	{
441
-		if ($this->getDatabase()) {
442
-			$tables = array();
443
-			$r = $this->query('SHOW TABLES LIKE '.$this->quoted($like));
444
-			if (!empty($r)) {
445
-				while ($a = $this->fetchByAssoc($r)) {
446
-					$row = array_values($a);
447
-					$tables[]=$row[0];
448
-				}
449
-				return $tables;
450
-			}
451
-		}
452
-		return false;
453
-	}
454
-
455
-	/**
456
-	 * @see DBManager::quote()
457
-	 */
458
-	public function quote($string)
459
-	{
460
-		if(is_array($string)) {
461
-			return $this->arrayQuote($string);
462
-		}
463
-		return mysqli_real_escape_string($this->quoteInternal($string), $this->getDatabase());
464
-	}
267
+        if ($start < 0)
268
+            $start = 0;
269
+        $GLOBALS['log']->debug('Limit Query:' . $sql. ' Start: ' .$start . ' count: ' . $count);
270
+
271
+        $sql = "$sql LIMIT $start,$count";
272
+        $this->lastsql = $sql;
273
+
274
+        if(!empty($GLOBALS['sugar_config']['check_query'])){
275
+            $this->checkQuery($sql);
276
+        }
277
+        if(!$execute) {
278
+            return $sql;
279
+        }
280
+
281
+        return $this->query($sql, $dieOnError, $msg);
282
+    }
283
+
284
+
285
+    /**
286
+     * @see DBManager::checkQuery()
287
+     */
288
+    protected function checkQuery($sql, $object_name = false)
289
+    {
290
+        $result   = $this->query('EXPLAIN ' . $sql);
291
+        $badQuery = array();
292
+        while ($row = $this->fetchByAssoc($result)) {
293
+            if (empty($row['table']))
294
+                continue;
295
+            $badQuery[$row['table']] = '';
296
+            if (strtoupper($row['type']) == 'ALL')
297
+                $badQuery[$row['table']]  .=  ' Full Table Scan;';
298
+            if (empty($row['key']))
299
+                $badQuery[$row['table']] .= ' No Index Key Used;';
300
+            if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using filesort') > 0)
301
+                $badQuery[$row['table']] .= ' Using FileSort;';
302
+            if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using temporary') > 0)
303
+                $badQuery[$row['table']] .= ' Using Temporary Table;';
304
+        }
305
+
306
+        if ( empty($badQuery) )
307
+            return true;
308
+
309
+        foreach($badQuery as $table=>$data ){
310
+            if(!empty($data)){
311
+                $warning = ' Table:' . $table . ' Data:' . $data;
312
+                if(!empty($GLOBALS['sugar_config']['check_query_log'])){
313
+                    $GLOBALS['log']->fatal($sql);
314
+                    $GLOBALS['log']->fatal('CHECK QUERY:' .$warning);
315
+                }
316
+                else{
317
+                    $GLOBALS['log']->warn('CHECK QUERY:' .$warning);
318
+                }
319
+            }
320
+        }
321
+
322
+        return false;
323
+    }
324
+
325
+    /**
326
+     * @see DBManager::get_columns()
327
+     */
328
+    public function get_columns($tablename)
329
+    {
330
+        //find all unique indexes and primary keys.
331
+        $result = $this->query("DESCRIBE $tablename");
332
+
333
+        $columns = array();
334
+        while (($row=$this->fetchByAssoc($result)) !=null) {
335
+            $name = strtolower($row['Field']);
336
+            $columns[$name]['name']=$name;
337
+            $matches = array();
338
+            preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*)\)|)( unsigned)?/i', $row['Type'], $matches);
339
+            $columns[$name]['type']=strtolower($matches[1][0]);
340
+            if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) )
341
+                $columns[$name]['len']=strtolower($matches[2][0]);
342
+            if ( stristr($row['Extra'],'auto_increment') )
343
+                $columns[$name]['auto_increment'] = '1';
344
+            if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI'))
345
+                $columns[$name]['required'] = 'true';
346
+            if (!empty($row['Default']) )
347
+                $columns[$name]['default'] = $row['Default'];
348
+        }
349
+        return $columns;
350
+    }
351
+
352
+    /**
353
+     * @see DBManager::getFieldsArray()
354
+     */
355
+    public function getFieldsArray($result, $make_lower_case=false)
356
+    {
357
+        $field_array = array();
358
+
359
+        if(empty($result))
360
+            return 0;
361
+
362
+        $fields = mysql_num_fields($result);
363
+        for ($i=0; $i < $fields; $i++) {
364
+            $meta = mysql_fetch_field($result, $i);
365
+            if (!$meta)
366
+                return array();
367
+
368
+            if($make_lower_case == true)
369
+                $meta->name = strtolower($meta->name);
370
+
371
+            $field_array[] = $meta->name;
372
+        }
373
+
374
+        return $field_array;
375
+    }
376
+
377
+    /**
378
+     * @see DBManager::fetchRow()
379
+     */
380
+    public function fetchRow($result)
381
+    {
382
+        if (empty($result))	return false;
383
+
384
+        return mysql_fetch_assoc($result);
385
+    }
386
+
387
+    /**
388
+     * @see DBManager::getTablesArray()
389
+     */
390
+    public function getTablesArray()
391
+    {
392
+        $this->log->debug('Fetching table list');
393
+
394
+        if ($this->getDatabase()) {
395
+            $tables = array();
396
+            $r = $this->query('SHOW TABLES');
397
+            if (!empty($r)) {
398
+                while ($a = $this->fetchByAssoc($r)) {
399
+                    $row = array_values($a);
400
+                    $tables[]=$row[0];
401
+                }
402
+                return $tables;
403
+            }
404
+        }
405
+
406
+        return false; // no database available
407
+    }
408
+
409
+    /**
410
+     * @see DBManager::version()
411
+     */
412
+    public function version()
413
+    {
414
+        return $this->getOne("SELECT version() version");
415
+    }
416
+
417
+    /**
418
+     * @see DBManager::tableExists()
419
+     */
420
+    public function tableExists($tableName)
421
+    {
422
+        $this->log->info("tableExists: $tableName");
423
+
424
+        if ($this->getDatabase()) {
425
+            $result = $this->query("SHOW TABLES LIKE ".$this->quoted($tableName));
426
+            if(empty($result)) return false;
427
+            $row = $this->fetchByAssoc($result);
428
+            return !empty($row);
429
+        }
430
+
431
+        return false;
432
+    }
433
+
434
+    /**
435
+     * Get tables like expression
436
+     * @param $like string
437
+     * @return array
438
+     */
439
+    public function tablesLike($like)
440
+    {
441
+        if ($this->getDatabase()) {
442
+            $tables = array();
443
+            $r = $this->query('SHOW TABLES LIKE '.$this->quoted($like));
444
+            if (!empty($r)) {
445
+                while ($a = $this->fetchByAssoc($r)) {
446
+                    $row = array_values($a);
447
+                    $tables[]=$row[0];
448
+                }
449
+                return $tables;
450
+            }
451
+        }
452
+        return false;
453
+    }
454
+
455
+    /**
456
+     * @see DBManager::quote()
457
+     */
458
+    public function quote($string)
459
+    {
460
+        if(is_array($string)) {
461
+            return $this->arrayQuote($string);
462
+        }
463
+        return mysqli_real_escape_string($this->quoteInternal($string), $this->getDatabase());
464
+    }
465 465
 
466 466
     /**
467 467
      * @see DBManager::quoteIdentifier()
@@ -471,272 +471,272 @@  discard block
 block discarded – undo
471 471
         return '`'.$string.'`';
472 472
     }
473 473
 
474
-	/**
475
-	 * @see DBManager::connect()
476
-	 */
477
-	public function connect(array $configOptions = null, $dieOnError = false)
478
-	{
479
-		global $sugar_config;
480
-
481
-		if(is_null($configOptions))
482
-			$configOptions = $sugar_config['dbconfig'];
483
-
484
-		if ($this->getOption('persistent')) {
485
-			$this->database = @mysql_pconnect(
486
-				$configOptions['db_host_name'],
487
-				$configOptions['db_user_name'],
488
-				$configOptions['db_password']
489
-				);
490
-		}
491
-
492
-		if (!$this->database) {
493
-			$this->database = mysql_connect(
494
-					$configOptions['db_host_name'],
495
-					$configOptions['db_user_name'],
496
-					$configOptions['db_password']
497
-					);
498
-			if(empty($this->database)) {
499
-				$GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name']." as ".$configOptions['db_user_name'].":".mysql_error());
500
-				if($dieOnError) {
501
-					if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
502
-						sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
503
-					} else {
504
-						sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
505
-					}
506
-				} else {
507
-					return false;
508
-				}
509
-			}
510
-			// Do not pass connection information because we have not connected yet
511
-			if($this->database  && $this->getOption('persistent')){
512
-				$_SESSION['administrator_error'] = "<b>Severe Performance Degradation: Persistent Database Connections "
513
-					. "not working.  Please set \$sugar_config['dbconfigoption']['persistent'] to false "
514
-					. "in your config.php file</b>";
515
-			}
516
-		}
517
-		if(!empty($configOptions['db_name']) && !@mysql_select_db($configOptions['db_name'])) {
518
-			$GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}: " . mysql_error($this->database));
519
-			if($dieOnError) {
520
-				sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
521
-			} else {
522
-				return false;
523
-			}
524
-		}
525
-
526
-		// cn: using direct calls to prevent this from spamming the Logs
527
-	    mysql_query("SET CHARACTER SET utf8", $this->database);
528
-	    $names = "SET NAMES 'utf8'";
529
-	    $collation = $this->getOption('collation');
530
-	    if(!empty($collation)) {
531
-	        $names .= " COLLATE '$collation'";
532
-		}
533
-	    mysql_query($names, $this->database);
534
-
535
-		if(!$this->checkError('Could Not Connect:', $dieOnError))
536
-			$GLOBALS['log']->info("connected to db");
537
-		$this->connectOptions = $configOptions;
538
-
539
-		$GLOBALS['log']->info("Connect:".$this->database);
540
-		return true;
541
-	}
542
-
543
-	/**
544
-	 * @see DBManager::repairTableParams()
545
-	 *
546
-	 * For MySQL, we can write the ALTER TABLE statement all in one line, which speeds things
547
-	 * up quite a bit. So here, we'll parse the returned SQL into a single ALTER TABLE command.
548
-	 */
549
-	public function repairTableParams($tablename, $fielddefs, $indices, $execute = true, $engine = null)
550
-	{
551
-		$sql = parent::repairTableParams($tablename,$fielddefs,$indices,false,$engine);
552
-
553
-		if ( $sql == '' )
554
-			return '';
555
-
556
-		if ( stristr($sql,'create table') )
557
-		{
558
-			if ($execute) {
559
-				$msg = "Error creating table: ".$tablename. ":";
560
-				$this->query($sql,true,$msg);
561
-			}
562
-			return $sql;
563
-		}
564
-
565
-		// first, parse out all the comments
566
-		$match = array();
567
-		preg_match_all('!/\*.*?\*/!is', $sql, $match);
568
-		$commentBlocks = $match[0];
569
-		$sql = preg_replace('!/\*.*?\*/!is','', $sql);
570
-
571
-		// now, we should only have alter table statements
572
-		// let's replace the 'alter table name' part with a comma
573
-		$sql = preg_replace("!alter table $tablename!is",', ', $sql);
574
-
575
-		// re-add it at the beginning
576
-		$sql = substr_replace($sql,'',strpos($sql,','),1);
577
-		$sql = str_replace(";","",$sql);
578
-		$sql = str_replace("\n","",$sql);
579
-		$sql = "ALTER TABLE $tablename $sql";
580
-
581
-		if ( $execute )
582
-			$this->query($sql,'Error with MySQL repair table');
583
-
584
-		// and re-add the comments at the beginning
585
-		$sql = implode("\n",$commentBlocks) . "\n". $sql . "\n";
586
-
587
-		return $sql;
588
-	}
589
-
590
-	/**
591
-	 * @see DBManager::convert()
592
-	 */
593
-	public function convert($string, $type, array $additional_parameters = array())
594
-	{
595
-		$all_parameters = $additional_parameters;
596
-		if(is_array($string)) {
597
-			$all_parameters = array_merge($string, $all_parameters);
598
-		} elseif (!is_null($string)) {
599
-			array_unshift($all_parameters, $string);
600
-		}
601
-		$all_strings = implode(',', $all_parameters);
602
-
603
-		switch (strtolower($type)) {
604
-			case 'today':
605
-				return "CURDATE()";
606
-			case 'left':
607
-				return "LEFT($all_strings)";
608
-			case 'date_format':
609
-				if(empty($additional_parameters)) {
610
-					return "DATE_FORMAT($string,'%Y-%m-%d')";
611
-				} else {
612
-					$format = $additional_parameters[0];
613
-					if($format[0] != "'") {
614
-						$format = $this->quoted($format);
615
-					}
616
-					return "DATE_FORMAT($string,$format)";
617
-				}
618
-			case 'ifnull':
619
-				if(empty($additional_parameters) && !strstr($all_strings, ",")) {
620
-					$all_strings .= ",''";
621
-				}
622
-				return "IFNULL($all_strings)";
623
-			case 'concat':
624
-				return "CONCAT($all_strings)";
625
-			case 'quarter':
626
-					return "QUARTER($string)";
627
-			case "length":
628
-					return "LENGTH($string)";
629
-			case 'month':
630
-					return "MONTH($string)";
631
-			case 'add_date':
632
-					return "DATE_ADD($string, INTERVAL {$additional_parameters[0]} {$additional_parameters[1]})";
633
-			case 'add_time':
634
-					return "DATE_ADD($string, INTERVAL + CONCAT({$additional_parameters[0]}, ':', {$additional_parameters[1]}) HOUR_MINUTE)";
474
+    /**
475
+     * @see DBManager::connect()
476
+     */
477
+    public function connect(array $configOptions = null, $dieOnError = false)
478
+    {
479
+        global $sugar_config;
480
+
481
+        if(is_null($configOptions))
482
+            $configOptions = $sugar_config['dbconfig'];
483
+
484
+        if ($this->getOption('persistent')) {
485
+            $this->database = @mysql_pconnect(
486
+                $configOptions['db_host_name'],
487
+                $configOptions['db_user_name'],
488
+                $configOptions['db_password']
489
+                );
490
+        }
491
+
492
+        if (!$this->database) {
493
+            $this->database = mysql_connect(
494
+                    $configOptions['db_host_name'],
495
+                    $configOptions['db_user_name'],
496
+                    $configOptions['db_password']
497
+                    );
498
+            if(empty($this->database)) {
499
+                $GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name']." as ".$configOptions['db_user_name'].":".mysql_error());
500
+                if($dieOnError) {
501
+                    if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
502
+                        sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
503
+                    } else {
504
+                        sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
505
+                    }
506
+                } else {
507
+                    return false;
508
+                }
509
+            }
510
+            // Do not pass connection information because we have not connected yet
511
+            if($this->database  && $this->getOption('persistent')){
512
+                $_SESSION['administrator_error'] = "<b>Severe Performance Degradation: Persistent Database Connections "
513
+                    . "not working.  Please set \$sugar_config['dbconfigoption']['persistent'] to false "
514
+                    . "in your config.php file</b>";
515
+            }
516
+        }
517
+        if(!empty($configOptions['db_name']) && !@mysql_select_db($configOptions['db_name'])) {
518
+            $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}: " . mysql_error($this->database));
519
+            if($dieOnError) {
520
+                sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
521
+            } else {
522
+                return false;
523
+            }
524
+        }
525
+
526
+        // cn: using direct calls to prevent this from spamming the Logs
527
+        mysql_query("SET CHARACTER SET utf8", $this->database);
528
+        $names = "SET NAMES 'utf8'";
529
+        $collation = $this->getOption('collation');
530
+        if(!empty($collation)) {
531
+            $names .= " COLLATE '$collation'";
532
+        }
533
+        mysql_query($names, $this->database);
534
+
535
+        if(!$this->checkError('Could Not Connect:', $dieOnError))
536
+            $GLOBALS['log']->info("connected to db");
537
+        $this->connectOptions = $configOptions;
538
+
539
+        $GLOBALS['log']->info("Connect:".$this->database);
540
+        return true;
541
+    }
542
+
543
+    /**
544
+     * @see DBManager::repairTableParams()
545
+     *
546
+     * For MySQL, we can write the ALTER TABLE statement all in one line, which speeds things
547
+     * up quite a bit. So here, we'll parse the returned SQL into a single ALTER TABLE command.
548
+     */
549
+    public function repairTableParams($tablename, $fielddefs, $indices, $execute = true, $engine = null)
550
+    {
551
+        $sql = parent::repairTableParams($tablename,$fielddefs,$indices,false,$engine);
552
+
553
+        if ( $sql == '' )
554
+            return '';
555
+
556
+        if ( stristr($sql,'create table') )
557
+        {
558
+            if ($execute) {
559
+                $msg = "Error creating table: ".$tablename. ":";
560
+                $this->query($sql,true,$msg);
561
+            }
562
+            return $sql;
563
+        }
564
+
565
+        // first, parse out all the comments
566
+        $match = array();
567
+        preg_match_all('!/\*.*?\*/!is', $sql, $match);
568
+        $commentBlocks = $match[0];
569
+        $sql = preg_replace('!/\*.*?\*/!is','', $sql);
570
+
571
+        // now, we should only have alter table statements
572
+        // let's replace the 'alter table name' part with a comma
573
+        $sql = preg_replace("!alter table $tablename!is",', ', $sql);
574
+
575
+        // re-add it at the beginning
576
+        $sql = substr_replace($sql,'',strpos($sql,','),1);
577
+        $sql = str_replace(";","",$sql);
578
+        $sql = str_replace("\n","",$sql);
579
+        $sql = "ALTER TABLE $tablename $sql";
580
+
581
+        if ( $execute )
582
+            $this->query($sql,'Error with MySQL repair table');
583
+
584
+        // and re-add the comments at the beginning
585
+        $sql = implode("\n",$commentBlocks) . "\n". $sql . "\n";
586
+
587
+        return $sql;
588
+    }
589
+
590
+    /**
591
+     * @see DBManager::convert()
592
+     */
593
+    public function convert($string, $type, array $additional_parameters = array())
594
+    {
595
+        $all_parameters = $additional_parameters;
596
+        if(is_array($string)) {
597
+            $all_parameters = array_merge($string, $all_parameters);
598
+        } elseif (!is_null($string)) {
599
+            array_unshift($all_parameters, $string);
600
+        }
601
+        $all_strings = implode(',', $all_parameters);
602
+
603
+        switch (strtolower($type)) {
604
+            case 'today':
605
+                return "CURDATE()";
606
+            case 'left':
607
+                return "LEFT($all_strings)";
608
+            case 'date_format':
609
+                if(empty($additional_parameters)) {
610
+                    return "DATE_FORMAT($string,'%Y-%m-%d')";
611
+                } else {
612
+                    $format = $additional_parameters[0];
613
+                    if($format[0] != "'") {
614
+                        $format = $this->quoted($format);
615
+                    }
616
+                    return "DATE_FORMAT($string,$format)";
617
+                }
618
+            case 'ifnull':
619
+                if(empty($additional_parameters) && !strstr($all_strings, ",")) {
620
+                    $all_strings .= ",''";
621
+                }
622
+                return "IFNULL($all_strings)";
623
+            case 'concat':
624
+                return "CONCAT($all_strings)";
625
+            case 'quarter':
626
+                    return "QUARTER($string)";
627
+            case "length":
628
+                    return "LENGTH($string)";
629
+            case 'month':
630
+                    return "MONTH($string)";
631
+            case 'add_date':
632
+                    return "DATE_ADD($string, INTERVAL {$additional_parameters[0]} {$additional_parameters[1]})";
633
+            case 'add_time':
634
+                    return "DATE_ADD($string, INTERVAL + CONCAT({$additional_parameters[0]}, ':', {$additional_parameters[1]}) HOUR_MINUTE)";
635 635
             case 'add_tz_offset' :
636 636
                 $getUserUTCOffset = $GLOBALS['timedate']->getUserUTCOffset();
637 637
                 $operation = $getUserUTCOffset < 0 ? '-' : '+';
638 638
                 return $string . ' ' . $operation . ' INTERVAL ' . abs($getUserUTCOffset) . ' MINUTE';
639 639
             case 'avg':
640 640
                 return "avg($string)";
641
-		}
642
-
643
-		return $string;
644
-	}
645
-
646
-	/**
647
-	 * (non-PHPdoc)
648
-	 * @see DBManager::fromConvert()
649
-	 */
650
-	public function fromConvert($string, $type)
651
-	{
652
-		return $string;
653
-	}
654
-
655
-	/**
656
-	 * Returns the name of the engine to use or null if we are to use the default
657
-	 *
658
-	 * @param  object $bean SugarBean instance
659
-	 * @return string
660
-	 */
661
-	protected function getEngine($bean)
662
-	{
663
-		global $dictionary;
664
-		$engine = null;
665
-		if (isset($dictionary[$bean->getObjectName()]['engine'])) {
666
-			$engine = $dictionary[$bean->getObjectName()]['engine'];
667
-		}
668
-		return $engine;
669
-	}
670
-
671
-	/**
672
-	 * Returns true if the engine given is enabled in the backend
673
-	 *
674
-	 * @param  string $engine
675
-	 * @return bool
676
-	 */
677
-	protected function isEngineEnabled($engine)
678
-	{
679
-		if(!is_string($engine)) return false;
680
-
681
-		$engine = strtoupper($engine);
682
-
683
-		$r = $this->query("SHOW ENGINES");
684
-
685
-		while ( $row = $this->fetchByAssoc($r) )
686
-			if ( strtoupper($row['Engine']) == $engine )
687
-				return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
688
-
689
-		return false;
690
-	}
691
-
692
-	/**
693
-	 * @see DBManager::createTableSQL()
694
-	 */
695
-	public function createTableSQL(SugarBean $bean)
696
-	{
697
-		$tablename = $bean->getTableName();
698
-		$fieldDefs = $bean->getFieldDefinitions();
699
-		$indices   = $bean->getIndices();
700
-		$engine    = $this->getEngine($bean);
701
-		return $this->createTableSQLParams($tablename, $fieldDefs, $indices, $engine);
702
-	}
703
-
704
-	/**
705
-	 * Generates sql for create table statement for a bean.
706
-	 *
707
-	 * @param  string $tablename
708
-	 * @param  array  $fieldDefs
709
-	 * @param  array  $indices
710
-	 * @param  string $engine optional, MySQL engine to use
711
-	 * @return string SQL Create Table statement
712
-	*/
713
-	public function createTableSQLParams($tablename, $fieldDefs, $indices, $engine = null)
714
-	{
715
-		if ( empty($engine) && isset($fieldDefs['engine']))
716
-			$engine = $fieldDefs['engine'];
717
-		if ( !$this->isEngineEnabled($engine) )
718
-			$engine = '';
719
-
720
-		$columns = $this->columnSQLRep($fieldDefs, false, $tablename);
721
-		if (empty($columns))
722
-			return false;
723
-
724
-		$keys = $this->keysSQL($indices);
725
-		if (!empty($keys))
726
-			$keys = ",$keys";
727
-
728
-		// cn: bug 9873 - module tables do not get created in utf8 with assoc collation
729
-		$collation = $this->getOption('collation');
730
-		if(empty($collation)) {
731
-		    $collation = 'utf8_general_ci';
732
-		}
733
-		$sql = "CREATE TABLE $tablename ($columns $keys) CHARACTER SET utf8 COLLATE $collation";
734
-
735
-		if (!empty($engine))
736
-			$sql.= " ENGINE=$engine";
737
-
738
-		return $sql;
739
-	}
641
+        }
642
+
643
+        return $string;
644
+    }
645
+
646
+    /**
647
+     * (non-PHPdoc)
648
+     * @see DBManager::fromConvert()
649
+     */
650
+    public function fromConvert($string, $type)
651
+    {
652
+        return $string;
653
+    }
654
+
655
+    /**
656
+     * Returns the name of the engine to use or null if we are to use the default
657
+     *
658
+     * @param  object $bean SugarBean instance
659
+     * @return string
660
+     */
661
+    protected function getEngine($bean)
662
+    {
663
+        global $dictionary;
664
+        $engine = null;
665
+        if (isset($dictionary[$bean->getObjectName()]['engine'])) {
666
+            $engine = $dictionary[$bean->getObjectName()]['engine'];
667
+        }
668
+        return $engine;
669
+    }
670
+
671
+    /**
672
+     * Returns true if the engine given is enabled in the backend
673
+     *
674
+     * @param  string $engine
675
+     * @return bool
676
+     */
677
+    protected function isEngineEnabled($engine)
678
+    {
679
+        if(!is_string($engine)) return false;
680
+
681
+        $engine = strtoupper($engine);
682
+
683
+        $r = $this->query("SHOW ENGINES");
684
+
685
+        while ( $row = $this->fetchByAssoc($r) )
686
+            if ( strtoupper($row['Engine']) == $engine )
687
+                return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
688
+
689
+        return false;
690
+    }
691
+
692
+    /**
693
+     * @see DBManager::createTableSQL()
694
+     */
695
+    public function createTableSQL(SugarBean $bean)
696
+    {
697
+        $tablename = $bean->getTableName();
698
+        $fieldDefs = $bean->getFieldDefinitions();
699
+        $indices   = $bean->getIndices();
700
+        $engine    = $this->getEngine($bean);
701
+        return $this->createTableSQLParams($tablename, $fieldDefs, $indices, $engine);
702
+    }
703
+
704
+    /**
705
+     * Generates sql for create table statement for a bean.
706
+     *
707
+     * @param  string $tablename
708
+     * @param  array  $fieldDefs
709
+     * @param  array  $indices
710
+     * @param  string $engine optional, MySQL engine to use
711
+     * @return string SQL Create Table statement
712
+     */
713
+    public function createTableSQLParams($tablename, $fieldDefs, $indices, $engine = null)
714
+    {
715
+        if ( empty($engine) && isset($fieldDefs['engine']))
716
+            $engine = $fieldDefs['engine'];
717
+        if ( !$this->isEngineEnabled($engine) )
718
+            $engine = '';
719
+
720
+        $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
721
+        if (empty($columns))
722
+            return false;
723
+
724
+        $keys = $this->keysSQL($indices);
725
+        if (!empty($keys))
726
+            $keys = ",$keys";
727
+
728
+        // cn: bug 9873 - module tables do not get created in utf8 with assoc collation
729
+        $collation = $this->getOption('collation');
730
+        if(empty($collation)) {
731
+            $collation = 'utf8_general_ci';
732
+        }
733
+        $sql = "CREATE TABLE $tablename ($columns $keys) CHARACTER SET utf8 COLLATE $collation";
734
+
735
+        if (!empty($engine))
736
+            $sql.= " ENGINE=$engine";
737
+
738
+        return $sql;
739
+    }
740 740
 
741 741
     /**
742 742
      * Does this type represent text (i.e., non-varchar) value?
@@ -748,745 +748,745 @@  discard block
 block discarded – undo
748 748
         return in_array($type, array('blob','text','longblob', 'longtext'));
749 749
     }
750 750
 
751
-	/**
752
-	 * @see DBManager::oneColumnSQLRep()
753
-	 */
754
-	protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
755
-	{
756
-		// always return as array for post-processing
757
-		$ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
751
+    /**
752
+     * @see DBManager::oneColumnSQLRep()
753
+     */
754
+    protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
755
+    {
756
+        // always return as array for post-processing
757
+        $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
758 758
 
759
-		if ( $ref['colType'] == 'int' && !empty($fieldDef['len']) ) {
760
-			$ref['colType'] .= "(".$fieldDef['len'].")";
761
-		}
759
+        if ( $ref['colType'] == 'int' && !empty($fieldDef['len']) ) {
760
+            $ref['colType'] .= "(".$fieldDef['len'].")";
761
+        }
762 762
 
763
-		// bug 22338 - don't set a default value on text or blob fields
764
-		if ( isset($ref['default']) &&
763
+        // bug 22338 - don't set a default value on text or blob fields
764
+        if ( isset($ref['default']) &&
765 765
             in_array($ref['colBaseType'], array('text', 'blob', 'longtext', 'longblob')))
766
-			    $ref['default'] = '';
767
-
768
-		if ( $return_as_array )
769
-			return $ref;
770
-		else
771
-			return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
772
-	}
773
-
774
-	/**
775
-	 * @see DBManager::changeColumnSQL()
776
-	 */
777
-	protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
778
-	{
779
-		$columns = array();
780
-		if ($this->isFieldArray($fieldDefs)){
781
-			foreach ($fieldDefs as $def){
782
-				if ($action == 'drop')
783
-					$columns[] = $def['name'];
784
-				else
785
-					$columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
786
-			}
787
-		} else {
788
-			if ($action == 'drop')
789
-				$columns[] = $fieldDefs['name'];
790
-		else
791
-			$columns[] = $this->oneColumnSQLRep($fieldDefs);
792
-		}
793
-
794
-		return "ALTER TABLE $tablename $action COLUMN ".implode(",$action column ", $columns);
795
-	}
796
-
797
-	/**
798
-	 * Generates SQL for key specification inside CREATE TABLE statement
799
-	 *
800
-	 * The passes array is an array of field definitions or a field definition
801
-	 * itself. The keys generated will be either primary, foreign, unique, index
802
-	 * or none at all depending on the setting of the "key" parameter of a field definition
803
-	 *
804
-	 * @param  array  $indices
805
-	 * @param  bool   $alter_table
806
-	 * @param  string $alter_action
807
-	 * @return string SQL Statement
808
-	 */
809
-	protected function keysSQL($indices, $alter_table = false, $alter_action = '')
810
-	{
811
-	// check if the passed value is an array of fields.
812
-	// if not, convert it into an array
813
-	if (!$this->isFieldArray($indices))
814
-		$indices[] = $indices;
815
-
816
-	$columns = array();
817
-	foreach ($indices as $index) {
818
-		if(!empty($index['db']) && $index['db'] != $this->dbType)
819
-			continue;
820
-		if (isset($index['source']) && $index['source'] != 'db')
821
-			continue;
822
-
823
-		$type = $index['type'];
824
-		$name = $index['name'];
825
-
826
-		if (is_array($index['fields']))
827
-			$fields = implode(", ", $index['fields']);
828
-		else
829
-			$fields = $index['fields'];
830
-
831
-		switch ($type) {
832
-		case 'unique':
833
-			$columns[] = " UNIQUE $name ($fields)";
834
-			break;
835
-		case 'primary':
836
-			$columns[] = " PRIMARY KEY ($fields)";
837
-			break;
838
-		case 'index':
839
-		case 'foreign':
840
-		case 'clustered':
841
-		case 'alternate_key':
842
-			/**
843
-				* @todo here it is assumed that the primary key of the foreign
844
-				* table will always be named 'id'. It must be noted though
845
-				* that this can easily be fixed by referring to db dictionary
846
-				* to find the correct primary field name
847
-				*/
848
-			if ( $alter_table )
849
-				$columns[] = " INDEX $name ($fields)";
850
-			else
851
-				$columns[] = " KEY $name ($fields)";
852
-			break;
853
-		case 'fulltext':
854
-			if ($this->full_text_indexing_installed())
855
-				$columns[] = " FULLTEXT ($fields)";
856
-			else
857
-				$GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
858
-			break;
859
-		}
860
-	}
861
-	$columns = implode(", $alter_action ", $columns);
862
-	if(!empty($alter_action)){
863
-		$columns = $alter_action . ' '. $columns;
864
-	}
865
-	return $columns;
866
-	}
867
-
868
-	/**
869
-	 * @see DBManager::setAutoIncrement()
870
-	 */
871
-	protected function setAutoIncrement($table, $field_name)
872
-	{
873
-		return "auto_increment";
874
-	}
875
-
876
-	/**
877
-	 * Sets the next auto-increment value of a column to a specific value.
878
-	 *
879
-	 * @param  string $table tablename
880
-	 * @param  string $field_name
881
-	 */
882
-	public function setAutoIncrementStart($table, $field_name, $start_value)
883
-	{
884
-		$start_value = (int)$start_value;
885
-		return $this->query( "ALTER TABLE $table AUTO_INCREMENT = $start_value;");
886
-	}
887
-
888
-	/**
889
-	 * Returns the next value for an auto increment
890
-	 *
891
-	 * @param  string $table tablename
892
-	 * @param  string $field_name
893
-	 * @return string
894
-	 */
895
-	public function getAutoIncrement($table, $field_name)
896
-	{
897
-		$result = $this->query("SHOW TABLE STATUS LIKE '$table'");
898
-		$row = $this->fetchByAssoc($result);
899
-		if (!empty($row['Auto_increment']))
900
-			return $row['Auto_increment'];
901
-
902
-		return "";
903
-	}
904
-
905
-	/**
906
-	 * @see DBManager::get_indices()
907
-	 */
908
-	public function get_indices($tablename)
909
-	{
910
-		//find all unique indexes and primary keys.
911
-		$result = $this->query("SHOW INDEX FROM $tablename");
912
-
913
-		$indices = array();
914
-		while (($row=$this->fetchByAssoc($result)) !=null) {
915
-			$index_type='index';
916
-			if ($row['Key_name'] =='PRIMARY') {
917
-				$index_type='primary';
918
-			}
919
-			elseif ( $row['Non_unique'] == '0' ) {
920
-				$index_type='unique';
921
-			}
922
-			$name = strtolower($row['Key_name']);
923
-			$indices[$name]['name']=$name;
924
-			$indices[$name]['type']=$index_type;
925
-			$indices[$name]['fields'][]=strtolower($row['Column_name']);
926
-		}
927
-		return $indices;
928
-	}
929
-
930
-	/**
931
-	 * @see DBManager::add_drop_constraint()
932
-	 */
933
-	public function add_drop_constraint($table, $definition, $drop = false)
934
-	{
935
-		$type         = $definition['type'];
936
-		$fields       = implode(',',$definition['fields']);
937
-		$name         = $definition['name'];
938
-		$sql          = '';
939
-
940
-		switch ($type){
941
-		// generic indices
942
-		case 'index':
943
-		case 'alternate_key':
944
-		case 'clustered':
945
-			if ($drop)
946
-				$sql = "ALTER TABLE {$table} DROP INDEX {$name} ";
947
-			else
948
-				$sql = "ALTER TABLE {$table} ADD INDEX {$name} ({$fields})";
949
-			break;
950
-		// constraints as indices
951
-		case 'unique':
952
-			if ($drop)
953
-				$sql = "ALTER TABLE {$table} DROP INDEX $name";
954
-			else
955
-				$sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
956
-			break;
957
-		case 'primary':
958
-			if ($drop)
959
-				$sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
960
-			else
961
-				$sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
962
-			break;
963
-		case 'foreign':
964
-			if ($drop)
965
-				$sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
966
-			else
967
-				$sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignField']})";
968
-			break;
969
-		}
970
-		return $sql;
971
-	}
972
-
973
-	/**
974
-	 * Runs a query and returns a single row
975
-	 *
976
-	 * @param  string   $sql        SQL Statement to execute
977
-	 * @param  bool     $dieOnError True if we want to call die if the query returns errors
978
-	 * @param  string   $msg        Message to log if error occurs
979
-	 * @param  bool     $suppress   Message to log if error occurs
980
-	 * @return array    single row from the query
981
-	 */
982
-	public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false)
983
-	{
984
-		if(stripos($sql, ' LIMIT ') === false) {
985
-			// little optimization to just fetch one row
986
-			$sql .= " LIMIT 0,1";
987
-		}
988
-		return parent::fetchOne($sql, $dieOnError, $msg, $suppress);
989
-	}
990
-
991
-	/**
992
-	 * @see DBManager::full_text_indexing_installed()
993
-	 */
994
-	public function full_text_indexing_installed($dbname = null)
995
-	{
996
-		return $this->isEngineEnabled('MyISAM');
997
-	}
998
-
999
-	/**
1000
-	 * @see DBManager::massageFieldDef()
1001
-	 */
1002
-	public function massageFieldDef(&$fieldDef, $tablename)
1003
-	{
1004
-		parent::massageFieldDef($fieldDef,$tablename);
1005
-
1006
-		if ( isset($fieldDef['default']) &&
1007
-			($fieldDef['dbType'] == 'text'
1008
-				|| $fieldDef['dbType'] == 'blob'
1009
-				|| $fieldDef['dbType'] == 'longtext'
1010
-				|| $fieldDef['dbType'] == 'longblob' ))
1011
-			unset($fieldDef['default']);
1012
-		if ($fieldDef['dbType'] == 'uint')
1013
-			$fieldDef['len'] = '10';
1014
-		if ($fieldDef['dbType'] == 'ulong')
1015
-			$fieldDef['len'] = '20';
1016
-		if ($fieldDef['dbType'] == 'bool')
1017
-			$fieldDef['type'] = 'tinyint';
1018
-		if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) )
1019
-			$fieldDef['default'] = '0';
1020
-		if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) )
1021
-			$fieldDef['len'] = '255';
1022
-		if ($fieldDef['dbType'] == 'uint')
1023
-			$fieldDef['len'] = '10';
1024
-		if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) )
1025
-			$fieldDef['len'] = '11';
1026
-
1027
-		if($fieldDef['dbType'] == 'decimal') {
1028
-			if(isset($fieldDef['len'])) {
1029
-				if(strstr($fieldDef['len'], ",") === false) {
1030
-					$fieldDef['len'] .= ",0";
1031
-				}
1032
-			} else {
1033
-				$fieldDef['len']  = '10,0';
1034
-			}
1035
-		}
1036
-	}
1037
-
1038
-	/**
1039
-	 * Generates SQL for dropping a table.
1040
-	 *
1041
-	 * @param  string $name table name
1042
-	 * @return string SQL statement
1043
-	 */
1044
-	public function dropTableNameSQL($name)
1045
-	{
1046
-		return "DROP TABLE IF EXISTS ".$name;
1047
-	}
1048
-
1049
-	public function dropIndexes($tablename, $indexes, $execute = true)
1050
-	{
1051
-		$sql = array();
1052
-		foreach ($indexes as $index) {
1053
-			$name =$index['name'];
1054
-			if($execute) {
1055
-			unset(self::$index_descriptions[$tablename][$name]);
1056
-			}
1057
-			if ($index['type'] == 'primary') {
1058
-				$sql[] = 'DROP PRIMARY KEY';
1059
-			} else {
1060
-				$sql[] = "DROP INDEX $name";
1061
-			}
1062
-		}
1063
-		if (!empty($sql)) {
766
+                $ref['default'] = '';
767
+
768
+        if ( $return_as_array )
769
+            return $ref;
770
+        else
771
+            return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
772
+    }
773
+
774
+    /**
775
+     * @see DBManager::changeColumnSQL()
776
+     */
777
+    protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
778
+    {
779
+        $columns = array();
780
+        if ($this->isFieldArray($fieldDefs)){
781
+            foreach ($fieldDefs as $def){
782
+                if ($action == 'drop')
783
+                    $columns[] = $def['name'];
784
+                else
785
+                    $columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
786
+            }
787
+        } else {
788
+            if ($action == 'drop')
789
+                $columns[] = $fieldDefs['name'];
790
+        else
791
+            $columns[] = $this->oneColumnSQLRep($fieldDefs);
792
+        }
793
+
794
+        return "ALTER TABLE $tablename $action COLUMN ".implode(",$action column ", $columns);
795
+    }
796
+
797
+    /**
798
+     * Generates SQL for key specification inside CREATE TABLE statement
799
+     *
800
+     * The passes array is an array of field definitions or a field definition
801
+     * itself. The keys generated will be either primary, foreign, unique, index
802
+     * or none at all depending on the setting of the "key" parameter of a field definition
803
+     *
804
+     * @param  array  $indices
805
+     * @param  bool   $alter_table
806
+     * @param  string $alter_action
807
+     * @return string SQL Statement
808
+     */
809
+    protected function keysSQL($indices, $alter_table = false, $alter_action = '')
810
+    {
811
+    // check if the passed value is an array of fields.
812
+    // if not, convert it into an array
813
+    if (!$this->isFieldArray($indices))
814
+        $indices[] = $indices;
815
+
816
+    $columns = array();
817
+    foreach ($indices as $index) {
818
+        if(!empty($index['db']) && $index['db'] != $this->dbType)
819
+            continue;
820
+        if (isset($index['source']) && $index['source'] != 'db')
821
+            continue;
822
+
823
+        $type = $index['type'];
824
+        $name = $index['name'];
825
+
826
+        if (is_array($index['fields']))
827
+            $fields = implode(", ", $index['fields']);
828
+        else
829
+            $fields = $index['fields'];
830
+
831
+        switch ($type) {
832
+        case 'unique':
833
+            $columns[] = " UNIQUE $name ($fields)";
834
+            break;
835
+        case 'primary':
836
+            $columns[] = " PRIMARY KEY ($fields)";
837
+            break;
838
+        case 'index':
839
+        case 'foreign':
840
+        case 'clustered':
841
+        case 'alternate_key':
842
+            /**
843
+             * @todo here it is assumed that the primary key of the foreign
844
+             * table will always be named 'id'. It must be noted though
845
+             * that this can easily be fixed by referring to db dictionary
846
+             * to find the correct primary field name
847
+             */
848
+            if ( $alter_table )
849
+                $columns[] = " INDEX $name ($fields)";
850
+            else
851
+                $columns[] = " KEY $name ($fields)";
852
+            break;
853
+        case 'fulltext':
854
+            if ($this->full_text_indexing_installed())
855
+                $columns[] = " FULLTEXT ($fields)";
856
+            else
857
+                $GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
858
+            break;
859
+        }
860
+    }
861
+    $columns = implode(", $alter_action ", $columns);
862
+    if(!empty($alter_action)){
863
+        $columns = $alter_action . ' '. $columns;
864
+    }
865
+    return $columns;
866
+    }
867
+
868
+    /**
869
+     * @see DBManager::setAutoIncrement()
870
+     */
871
+    protected function setAutoIncrement($table, $field_name)
872
+    {
873
+        return "auto_increment";
874
+    }
875
+
876
+    /**
877
+     * Sets the next auto-increment value of a column to a specific value.
878
+     *
879
+     * @param  string $table tablename
880
+     * @param  string $field_name
881
+     */
882
+    public function setAutoIncrementStart($table, $field_name, $start_value)
883
+    {
884
+        $start_value = (int)$start_value;
885
+        return $this->query( "ALTER TABLE $table AUTO_INCREMENT = $start_value;");
886
+    }
887
+
888
+    /**
889
+     * Returns the next value for an auto increment
890
+     *
891
+     * @param  string $table tablename
892
+     * @param  string $field_name
893
+     * @return string
894
+     */
895
+    public function getAutoIncrement($table, $field_name)
896
+    {
897
+        $result = $this->query("SHOW TABLE STATUS LIKE '$table'");
898
+        $row = $this->fetchByAssoc($result);
899
+        if (!empty($row['Auto_increment']))
900
+            return $row['Auto_increment'];
901
+
902
+        return "";
903
+    }
904
+
905
+    /**
906
+     * @see DBManager::get_indices()
907
+     */
908
+    public function get_indices($tablename)
909
+    {
910
+        //find all unique indexes and primary keys.
911
+        $result = $this->query("SHOW INDEX FROM $tablename");
912
+
913
+        $indices = array();
914
+        while (($row=$this->fetchByAssoc($result)) !=null) {
915
+            $index_type='index';
916
+            if ($row['Key_name'] =='PRIMARY') {
917
+                $index_type='primary';
918
+            }
919
+            elseif ( $row['Non_unique'] == '0' ) {
920
+                $index_type='unique';
921
+            }
922
+            $name = strtolower($row['Key_name']);
923
+            $indices[$name]['name']=$name;
924
+            $indices[$name]['type']=$index_type;
925
+            $indices[$name]['fields'][]=strtolower($row['Column_name']);
926
+        }
927
+        return $indices;
928
+    }
929
+
930
+    /**
931
+     * @see DBManager::add_drop_constraint()
932
+     */
933
+    public function add_drop_constraint($table, $definition, $drop = false)
934
+    {
935
+        $type         = $definition['type'];
936
+        $fields       = implode(',',$definition['fields']);
937
+        $name         = $definition['name'];
938
+        $sql          = '';
939
+
940
+        switch ($type){
941
+        // generic indices
942
+        case 'index':
943
+        case 'alternate_key':
944
+        case 'clustered':
945
+            if ($drop)
946
+                $sql = "ALTER TABLE {$table} DROP INDEX {$name} ";
947
+            else
948
+                $sql = "ALTER TABLE {$table} ADD INDEX {$name} ({$fields})";
949
+            break;
950
+        // constraints as indices
951
+        case 'unique':
952
+            if ($drop)
953
+                $sql = "ALTER TABLE {$table} DROP INDEX $name";
954
+            else
955
+                $sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
956
+            break;
957
+        case 'primary':
958
+            if ($drop)
959
+                $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
960
+            else
961
+                $sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
962
+            break;
963
+        case 'foreign':
964
+            if ($drop)
965
+                $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
966
+            else
967
+                $sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignField']})";
968
+            break;
969
+        }
970
+        return $sql;
971
+    }
972
+
973
+    /**
974
+     * Runs a query and returns a single row
975
+     *
976
+     * @param  string   $sql        SQL Statement to execute
977
+     * @param  bool     $dieOnError True if we want to call die if the query returns errors
978
+     * @param  string   $msg        Message to log if error occurs
979
+     * @param  bool     $suppress   Message to log if error occurs
980
+     * @return array    single row from the query
981
+     */
982
+    public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false)
983
+    {
984
+        if(stripos($sql, ' LIMIT ') === false) {
985
+            // little optimization to just fetch one row
986
+            $sql .= " LIMIT 0,1";
987
+        }
988
+        return parent::fetchOne($sql, $dieOnError, $msg, $suppress);
989
+    }
990
+
991
+    /**
992
+     * @see DBManager::full_text_indexing_installed()
993
+     */
994
+    public function full_text_indexing_installed($dbname = null)
995
+    {
996
+        return $this->isEngineEnabled('MyISAM');
997
+    }
998
+
999
+    /**
1000
+     * @see DBManager::massageFieldDef()
1001
+     */
1002
+    public function massageFieldDef(&$fieldDef, $tablename)
1003
+    {
1004
+        parent::massageFieldDef($fieldDef,$tablename);
1005
+
1006
+        if ( isset($fieldDef['default']) &&
1007
+            ($fieldDef['dbType'] == 'text'
1008
+                || $fieldDef['dbType'] == 'blob'
1009
+                || $fieldDef['dbType'] == 'longtext'
1010
+                || $fieldDef['dbType'] == 'longblob' ))
1011
+            unset($fieldDef['default']);
1012
+        if ($fieldDef['dbType'] == 'uint')
1013
+            $fieldDef['len'] = '10';
1014
+        if ($fieldDef['dbType'] == 'ulong')
1015
+            $fieldDef['len'] = '20';
1016
+        if ($fieldDef['dbType'] == 'bool')
1017
+            $fieldDef['type'] = 'tinyint';
1018
+        if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) )
1019
+            $fieldDef['default'] = '0';
1020
+        if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) )
1021
+            $fieldDef['len'] = '255';
1022
+        if ($fieldDef['dbType'] == 'uint')
1023
+            $fieldDef['len'] = '10';
1024
+        if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) )
1025
+            $fieldDef['len'] = '11';
1026
+
1027
+        if($fieldDef['dbType'] == 'decimal') {
1028
+            if(isset($fieldDef['len'])) {
1029
+                if(strstr($fieldDef['len'], ",") === false) {
1030
+                    $fieldDef['len'] .= ",0";
1031
+                }
1032
+            } else {
1033
+                $fieldDef['len']  = '10,0';
1034
+            }
1035
+        }
1036
+    }
1037
+
1038
+    /**
1039
+     * Generates SQL for dropping a table.
1040
+     *
1041
+     * @param  string $name table name
1042
+     * @return string SQL statement
1043
+     */
1044
+    public function dropTableNameSQL($name)
1045
+    {
1046
+        return "DROP TABLE IF EXISTS ".$name;
1047
+    }
1048
+
1049
+    public function dropIndexes($tablename, $indexes, $execute = true)
1050
+    {
1051
+        $sql = array();
1052
+        foreach ($indexes as $index) {
1053
+            $name =$index['name'];
1054
+            if($execute) {
1055
+            unset(self::$index_descriptions[$tablename][$name]);
1056
+            }
1057
+            if ($index['type'] == 'primary') {
1058
+                $sql[] = 'DROP PRIMARY KEY';
1059
+            } else {
1060
+                $sql[] = "DROP INDEX $name";
1061
+            }
1062
+        }
1063
+        if (!empty($sql)) {
1064 1064
             $sql = "ALTER TABLE $tablename " . join(",", $sql) . ";";
1065
-			if($execute)
1066
-				$this->query($sql);
1067
-		} else {
1068
-			$sql = '';
1069
-		}
1070
-		return $sql;
1071
-	}
1072
-
1073
-	/**
1074
-	 * List of available collation settings
1075
-	 * @return string
1076
-	 */
1077
-	public function getDefaultCollation()
1078
-	{
1079
-		return "utf8_general_ci";
1080
-	}
1081
-
1082
-	/**
1083
-	 * List of available collation settings
1084
-	 * @return array
1085
-	 */
1086
-	public function getCollationList()
1087
-	{
1088
-		$q = "SHOW COLLATION LIKE 'utf8%'";
1089
-		$r = $this->query($q);
1090
-		$res = array();
1091
-		while($a = $this->fetchByAssoc($r)) {
1092
-			$res[] = $a['Collation'];
1093
-		}
1094
-		return $res;
1095
-	}
1096
-
1097
-	/**
1098
-	 * (non-PHPdoc)
1099
-	 * @see DBManager::renameColumnSQL()
1100
-	 */
1101
-	public function renameColumnSQL($tablename, $column, $newname)
1102
-	{
1103
-		$field = $this->describeField($column, $tablename);
1104
-		$field['name'] = $newname;
1105
-		return "ALTER TABLE $tablename CHANGE COLUMN $column ".$this->oneColumnSQLRep($field);
1106
-	}
1107
-
1108
-	public function emptyValue($type)
1109
-	{
1110
-		$ctype = $this->getColumnType($type);
1111
-		if($ctype == "datetime") {
1112
-			return 'NULL';
1113
-		}
1114
-		if($ctype == "date") {
1115
-			return 'NULL';
1116
-		}
1117
-		if($ctype == "time") {
1118
-			return 'NULL';
1119
-		}
1120
-		return parent::emptyValue($type);
1121
-	}
1122
-
1123
-	/**
1124
-	 * (non-PHPdoc)
1125
-	 * @see DBManager::lastDbError()
1126
-	 */
1127
-	public function lastDbError()
1128
-	{
1129
-		if($this->database) {
1130
-		    if(mysql_errno($this->database)) {
1131
-			    return "MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database);
1132
-		    }
1133
-		} else {
1134
-			$err =  mysql_error();
1135
-			if($err) {
1136
-			    return $err;
1137
-			}
1138
-		}
1065
+            if($execute)
1066
+                $this->query($sql);
1067
+        } else {
1068
+            $sql = '';
1069
+        }
1070
+        return $sql;
1071
+    }
1072
+
1073
+    /**
1074
+     * List of available collation settings
1075
+     * @return string
1076
+     */
1077
+    public function getDefaultCollation()
1078
+    {
1079
+        return "utf8_general_ci";
1080
+    }
1081
+
1082
+    /**
1083
+     * List of available collation settings
1084
+     * @return array
1085
+     */
1086
+    public function getCollationList()
1087
+    {
1088
+        $q = "SHOW COLLATION LIKE 'utf8%'";
1089
+        $r = $this->query($q);
1090
+        $res = array();
1091
+        while($a = $this->fetchByAssoc($r)) {
1092
+            $res[] = $a['Collation'];
1093
+        }
1094
+        return $res;
1095
+    }
1096
+
1097
+    /**
1098
+     * (non-PHPdoc)
1099
+     * @see DBManager::renameColumnSQL()
1100
+     */
1101
+    public function renameColumnSQL($tablename, $column, $newname)
1102
+    {
1103
+        $field = $this->describeField($column, $tablename);
1104
+        $field['name'] = $newname;
1105
+        return "ALTER TABLE $tablename CHANGE COLUMN $column ".$this->oneColumnSQLRep($field);
1106
+    }
1107
+
1108
+    public function emptyValue($type)
1109
+    {
1110
+        $ctype = $this->getColumnType($type);
1111
+        if($ctype == "datetime") {
1112
+            return 'NULL';
1113
+        }
1114
+        if($ctype == "date") {
1115
+            return 'NULL';
1116
+        }
1117
+        if($ctype == "time") {
1118
+            return 'NULL';
1119
+        }
1120
+        return parent::emptyValue($type);
1121
+    }
1122
+
1123
+    /**
1124
+     * (non-PHPdoc)
1125
+     * @see DBManager::lastDbError()
1126
+     */
1127
+    public function lastDbError()
1128
+    {
1129
+        if($this->database) {
1130
+            if(mysql_errno($this->database)) {
1131
+                return "MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database);
1132
+            }
1133
+        } else {
1134
+            $err =  mysql_error();
1135
+            if($err) {
1136
+                return $err;
1137
+            }
1138
+        }
1139 1139
         return false;
1140 1140
     }
1141 1141
 
1142
-	/**
1143
-	 * Quote MySQL search term
1144
-	 * @param unknown_type $term
1145
-	 */
1146
-	protected function quoteTerm($term)
1147
-	{
1148
-		if(strpos($term, ' ') !== false) {
1149
-			return '"'.$term.'"';
1150
-		}
1151
-		return $term;
1152
-	}
1153
-
1154
-	/**
1155
-	 * Generate fulltext query from set of terms
1156
-	 * @param string $fields Field to search against
1157
-	 * @param array $terms Search terms that may be or not be in the result
1158
-	 * @param array $must_terms Search terms that have to be in the result
1159
-	 * @param array $exclude_terms Search terms that have to be not in the result
1160
-	 */
1161
-	public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1162
-	{
1163
-		$condition = array();
1164
-		foreach($terms as $term) {
1165
-			$condition[] = $this->quoteTerm($term);
1166
-		}
1167
-		foreach($must_terms as $term) {
1168
-			$condition[] = "+".$this->quoteTerm($term);
1169
-		}
1170
-		foreach($exclude_terms as $term) {
1171
-			$condition[] = "-".$this->quoteTerm($term);
1172
-		}
1173
-		$condition = $this->quoted(join(" ",$condition));
1174
-		return "MATCH($field) AGAINST($condition IN BOOLEAN MODE)";
1175
-	}
1176
-
1177
-	/**
1178
-	 * Get list of all defined charsets
1179
-	 * @return array
1180
-	 */
1181
-	protected function getCharsetInfo()
1182
-	{
1183
-		$charsets = array();
1184
-		$res = $this->query("show variables like 'character\\_set\\_%'");
1185
-		while($row = $this->fetchByAssoc($res)) {
1186
-			$charsets[$row['Variable_name']] = $row['Value'];
1187
-		}
1188
-		return $charsets;
1189
-	}
1190
-
1191
-	public function getDbInfo()
1192
-	{
1193
-		$charsets = $this->getCharsetInfo();
1194
-		$charset_str = array();
1195
-		foreach($charsets as $name => $value) {
1196
-			$charset_str[] = "$name = $value";
1197
-		}
1198
-		return array(
1199
-			"MySQL Version" => @mysql_get_client_info(),
1200
-			"MySQL Host Info" => @mysql_get_host_info($this->database),
1201
-			"MySQL Server Info" => @mysql_get_server_info($this->database),
1202
-			"MySQL Client Encoding" =>  @mysql_client_encoding($this->database),
1203
-			"MySQL Character Set Settings" => join(", ", $charset_str),
1204
-		);
1205
-	}
1206
-
1207
-	public function validateQuery($query)
1208
-	{
1209
-		$res = $this->query("EXPLAIN $query");
1210
-		return !empty($res);
1211
-	}
1212
-
1213
-	protected function makeTempTableCopy($table)
1214
-	{
1215
-		$this->log->debug("creating temp table for [$table]...");
1216
-		$result = $this->query("SHOW CREATE TABLE {$table}");
1217
-		if(empty($result)) {
1218
-			return false;
1219
-		}
1220
-		$row = $this->fetchByAssoc($result);
1221
-		if(empty($row) || empty($row['Create Table'])) {
1222
-		    return false;
1223
-		}
1224
-		$create = $row['Create Table'];
1225
-		// rewrite DDL with _temp name
1226
-		$tempTableQuery = str_replace("CREATE TABLE `{$table}`", "CREATE TABLE `{$table}__uw_temp`", $create);
1227
-		$r2 = $this->query($tempTableQuery);
1228
-		if(empty($r2)) {
1229
-			return false;
1230
-		}
1231
-
1232
-		// get sample data into the temp table to test for data/constraint conflicts
1233
-		$this->log->debug('inserting temp dataset...');
1234
-		$q3 = "INSERT INTO `{$table}__uw_temp` SELECT * FROM `{$table}` LIMIT 10";
1235
-		$this->query($q3, false, "Preflight Failed for: {$q3}");
1236
-		return true;
1237
-	}
1238
-
1239
-	/**
1240
-	 * Tests an ALTER TABLE query
1241
-	 * @param string table The table name to get DDL
1242
-	 * @param string query The query to test.
1243
-	 * @return string Non-empty if error found
1244
-	 */
1245
-	protected function verifyAlterTable($table, $query)
1246
-	{
1247
-		$this->log->debug("verifying ALTER TABLE");
1248
-		// Skipping ALTER TABLE [table] DROP PRIMARY KEY because primary keys are not being copied
1249
-		// over to the temp tables
1250
-		if(strpos(strtoupper($query), 'DROP PRIMARY KEY') !== false) {
1251
-			$this->log->debug("Skipping DROP PRIMARY KEY");
1252
-			return '';
1253
-		}
1254
-		if(!$this->makeTempTableCopy($table)) {
1255
-			return 'Could not create temp table copy';
1256
-		}
1257
-
1258
-		// test the query on the test table
1259
-		$this->log->debug('testing query: ['.$query.']');
1260
-		$tempTableTestQuery = str_replace("ALTER TABLE `{$table}`", "ALTER TABLE `{$table}__uw_temp`", $query);
1261
-		if (strpos($tempTableTestQuery, 'idx') === false) {
1262
-			if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1263
-				return 'Could not use a temp table to test query!';
1264
-			}
1265
-
1266
-			$this->log->debug('testing query on temp table: ['.$tempTableTestQuery.']');
1267
-			$this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1268
-		} else {
1269
-			// test insertion of an index on a table
1270
-			$tempTableTestQuery_idx = str_replace("ADD INDEX `idx_", "ADD INDEX `temp_idx_", $tempTableTestQuery);
1271
-			$this->log->debug('testing query on temp table: ['.$tempTableTestQuery_idx.']');
1272
-			$this->query($tempTableTestQuery_idx, false, "Preflight Failed for: {$query}");
1273
-		}
1274
-		$mysqlError = $this->getL();
1275
-		if(!empty($mysqlError)) {
1276
-			return $mysqlError;
1277
-		}
1278
-		$this->dropTableName("{$table}__uw_temp");
1279
-
1280
-		return '';
1281
-	}
1282
-
1283
-	protected function verifyGenericReplaceQuery($querytype, $table, $query)
1284
-	{
1285
-		$this->log->debug("verifying $querytype statement");
1286
-
1287
-		if(!$this->makeTempTableCopy($table)) {
1288
-			return 'Could not create temp table copy';
1289
-		}
1290
-		// test the query on the test table
1291
-		$this->log->debug('testing query: ['.$query.']');
1292
-		$tempTableTestQuery = str_replace("$querytype `{$table}`", "$querytype `{$table}__uw_temp`", $query);
1293
-		if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1294
-			return 'Could not use a temp table to test query!';
1295
-		}
1296
-
1297
-		$this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1298
-		$error = $this->lastError(); // empty on no-errors
1299
-		$this->dropTableName("{$table}__uw_temp"); // just in case
1300
-		return $error;
1301
-	}
1302
-
1303
-	/**
1304
-	 * Tests a DROP TABLE query
1305
-	 * @param string table The table name to get DDL
1306
-	 * @param string query The query to test.
1307
-	 * @return string Non-empty if error found
1308
-	 */
1309
-	public function verifyDropTable($table, $query)
1310
-	{
1311
-		return $this->verifyGenericReplaceQuery("DROP TABLE", $table, $query);
1312
-	}
1313
-
1314
-	/**
1315
-	 * Tests an INSERT INTO query
1316
-	 * @param string table The table name to get DDL
1317
-	 * @param string query The query to test.
1318
-	 * @return string Non-empty if error found
1319
-	 */
1320
-	public function verifyInsertInto($table, $query)
1321
-	{
1322
-		return $this->verifyGenericReplaceQuery("INSERT INTO", $table, $query);
1323
-	}
1324
-
1325
-	/**
1326
-	 * Tests an UPDATE query
1327
-	 * @param string table The table name to get DDL
1328
-	 * @param string query The query to test.
1329
-	 * @return string Non-empty if error found
1330
-	 */
1331
-	public function verifyUpdate($table, $query)
1332
-	{
1333
-		return $this->verifyGenericReplaceQuery("UPDATE", $table, $query);
1334
-	}
1335
-
1336
-	/**
1337
-	 * Tests an DELETE FROM query
1338
-	 * @param string table The table name to get DDL
1339
-	 * @param string query The query to test.
1340
-	 * @return string Non-empty if error found
1341
-	 */
1342
-	public function verifyDeleteFrom($table, $query)
1343
-	{
1344
-		return $this->verifyGenericReplaceQuery("DELETE FROM", $table, $query);
1345
-	}
1346
-
1347
-	/**
1348
-	 * Check if certain database exists
1349
-	 * @param string $dbname
1350
-	 */
1351
-	public function dbExists($dbname)
1352
-	{
1353
-		$db = $this->getOne("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ".$this->quoted($dbname));
1354
-		return !empty($db);
1355
-	}
1356
-
1357
-	/**
1358
-	 * Select database
1359
-	 * @param string $dbname
1360
-	 */
1361
-	protected function selectDb($dbname)
1362
-	{
1363
-		return mysql_select_db($dbname);
1364
-	}
1365
-
1366
-	/**
1367
-	 * Check if certain DB user exists
1368
-	 * @param string $username
1369
-	 */
1370
-	public function userExists($username)
1371
-	{
1372
-		$db = $this->getOne("SELECT DATABASE()");
1373
-		if(!$this->selectDb("mysql")) {
1374
-			return false;
1375
-		}
1376
-		$user = $this->getOne("select count(*) from user where user = ".$this->quoted($username));
1377
-		if(!$this->selectDb($db)) {
1378
-			$this->checkError("Cannot select database $db", true);
1379
-		}
1380
-		return !empty($user);
1381
-	}
1382
-
1383
-	/**
1384
-	 * Create DB user
1385
-	 * @param string $database_name
1386
-	 * @param string $host_name
1387
-	 * @param string $user
1388
-	 * @param string $password
1389
-	 */
1390
-	public function createDbUser($database_name, $host_name, $user, $password)
1391
-	{
1392
-		$qpassword = $this->quote($password);
1393
-		$this->query("GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
1142
+    /**
1143
+     * Quote MySQL search term
1144
+     * @param unknown_type $term
1145
+     */
1146
+    protected function quoteTerm($term)
1147
+    {
1148
+        if(strpos($term, ' ') !== false) {
1149
+            return '"'.$term.'"';
1150
+        }
1151
+        return $term;
1152
+    }
1153
+
1154
+    /**
1155
+     * Generate fulltext query from set of terms
1156
+     * @param string $fields Field to search against
1157
+     * @param array $terms Search terms that may be or not be in the result
1158
+     * @param array $must_terms Search terms that have to be in the result
1159
+     * @param array $exclude_terms Search terms that have to be not in the result
1160
+     */
1161
+    public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1162
+    {
1163
+        $condition = array();
1164
+        foreach($terms as $term) {
1165
+            $condition[] = $this->quoteTerm($term);
1166
+        }
1167
+        foreach($must_terms as $term) {
1168
+            $condition[] = "+".$this->quoteTerm($term);
1169
+        }
1170
+        foreach($exclude_terms as $term) {
1171
+            $condition[] = "-".$this->quoteTerm($term);
1172
+        }
1173
+        $condition = $this->quoted(join(" ",$condition));
1174
+        return "MATCH($field) AGAINST($condition IN BOOLEAN MODE)";
1175
+    }
1176
+
1177
+    /**
1178
+     * Get list of all defined charsets
1179
+     * @return array
1180
+     */
1181
+    protected function getCharsetInfo()
1182
+    {
1183
+        $charsets = array();
1184
+        $res = $this->query("show variables like 'character\\_set\\_%'");
1185
+        while($row = $this->fetchByAssoc($res)) {
1186
+            $charsets[$row['Variable_name']] = $row['Value'];
1187
+        }
1188
+        return $charsets;
1189
+    }
1190
+
1191
+    public function getDbInfo()
1192
+    {
1193
+        $charsets = $this->getCharsetInfo();
1194
+        $charset_str = array();
1195
+        foreach($charsets as $name => $value) {
1196
+            $charset_str[] = "$name = $value";
1197
+        }
1198
+        return array(
1199
+            "MySQL Version" => @mysql_get_client_info(),
1200
+            "MySQL Host Info" => @mysql_get_host_info($this->database),
1201
+            "MySQL Server Info" => @mysql_get_server_info($this->database),
1202
+            "MySQL Client Encoding" =>  @mysql_client_encoding($this->database),
1203
+            "MySQL Character Set Settings" => join(", ", $charset_str),
1204
+        );
1205
+    }
1206
+
1207
+    public function validateQuery($query)
1208
+    {
1209
+        $res = $this->query("EXPLAIN $query");
1210
+        return !empty($res);
1211
+    }
1212
+
1213
+    protected function makeTempTableCopy($table)
1214
+    {
1215
+        $this->log->debug("creating temp table for [$table]...");
1216
+        $result = $this->query("SHOW CREATE TABLE {$table}");
1217
+        if(empty($result)) {
1218
+            return false;
1219
+        }
1220
+        $row = $this->fetchByAssoc($result);
1221
+        if(empty($row) || empty($row['Create Table'])) {
1222
+            return false;
1223
+        }
1224
+        $create = $row['Create Table'];
1225
+        // rewrite DDL with _temp name
1226
+        $tempTableQuery = str_replace("CREATE TABLE `{$table}`", "CREATE TABLE `{$table}__uw_temp`", $create);
1227
+        $r2 = $this->query($tempTableQuery);
1228
+        if(empty($r2)) {
1229
+            return false;
1230
+        }
1231
+
1232
+        // get sample data into the temp table to test for data/constraint conflicts
1233
+        $this->log->debug('inserting temp dataset...');
1234
+        $q3 = "INSERT INTO `{$table}__uw_temp` SELECT * FROM `{$table}` LIMIT 10";
1235
+        $this->query($q3, false, "Preflight Failed for: {$q3}");
1236
+        return true;
1237
+    }
1238
+
1239
+    /**
1240
+     * Tests an ALTER TABLE query
1241
+     * @param string table The table name to get DDL
1242
+     * @param string query The query to test.
1243
+     * @return string Non-empty if error found
1244
+     */
1245
+    protected function verifyAlterTable($table, $query)
1246
+    {
1247
+        $this->log->debug("verifying ALTER TABLE");
1248
+        // Skipping ALTER TABLE [table] DROP PRIMARY KEY because primary keys are not being copied
1249
+        // over to the temp tables
1250
+        if(strpos(strtoupper($query), 'DROP PRIMARY KEY') !== false) {
1251
+            $this->log->debug("Skipping DROP PRIMARY KEY");
1252
+            return '';
1253
+        }
1254
+        if(!$this->makeTempTableCopy($table)) {
1255
+            return 'Could not create temp table copy';
1256
+        }
1257
+
1258
+        // test the query on the test table
1259
+        $this->log->debug('testing query: ['.$query.']');
1260
+        $tempTableTestQuery = str_replace("ALTER TABLE `{$table}`", "ALTER TABLE `{$table}__uw_temp`", $query);
1261
+        if (strpos($tempTableTestQuery, 'idx') === false) {
1262
+            if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1263
+                return 'Could not use a temp table to test query!';
1264
+            }
1265
+
1266
+            $this->log->debug('testing query on temp table: ['.$tempTableTestQuery.']');
1267
+            $this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1268
+        } else {
1269
+            // test insertion of an index on a table
1270
+            $tempTableTestQuery_idx = str_replace("ADD INDEX `idx_", "ADD INDEX `temp_idx_", $tempTableTestQuery);
1271
+            $this->log->debug('testing query on temp table: ['.$tempTableTestQuery_idx.']');
1272
+            $this->query($tempTableTestQuery_idx, false, "Preflight Failed for: {$query}");
1273
+        }
1274
+        $mysqlError = $this->getL();
1275
+        if(!empty($mysqlError)) {
1276
+            return $mysqlError;
1277
+        }
1278
+        $this->dropTableName("{$table}__uw_temp");
1279
+
1280
+        return '';
1281
+    }
1282
+
1283
+    protected function verifyGenericReplaceQuery($querytype, $table, $query)
1284
+    {
1285
+        $this->log->debug("verifying $querytype statement");
1286
+
1287
+        if(!$this->makeTempTableCopy($table)) {
1288
+            return 'Could not create temp table copy';
1289
+        }
1290
+        // test the query on the test table
1291
+        $this->log->debug('testing query: ['.$query.']');
1292
+        $tempTableTestQuery = str_replace("$querytype `{$table}`", "$querytype `{$table}__uw_temp`", $query);
1293
+        if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1294
+            return 'Could not use a temp table to test query!';
1295
+        }
1296
+
1297
+        $this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1298
+        $error = $this->lastError(); // empty on no-errors
1299
+        $this->dropTableName("{$table}__uw_temp"); // just in case
1300
+        return $error;
1301
+    }
1302
+
1303
+    /**
1304
+     * Tests a DROP TABLE query
1305
+     * @param string table The table name to get DDL
1306
+     * @param string query The query to test.
1307
+     * @return string Non-empty if error found
1308
+     */
1309
+    public function verifyDropTable($table, $query)
1310
+    {
1311
+        return $this->verifyGenericReplaceQuery("DROP TABLE", $table, $query);
1312
+    }
1313
+
1314
+    /**
1315
+     * Tests an INSERT INTO query
1316
+     * @param string table The table name to get DDL
1317
+     * @param string query The query to test.
1318
+     * @return string Non-empty if error found
1319
+     */
1320
+    public function verifyInsertInto($table, $query)
1321
+    {
1322
+        return $this->verifyGenericReplaceQuery("INSERT INTO", $table, $query);
1323
+    }
1324
+
1325
+    /**
1326
+     * Tests an UPDATE query
1327
+     * @param string table The table name to get DDL
1328
+     * @param string query The query to test.
1329
+     * @return string Non-empty if error found
1330
+     */
1331
+    public function verifyUpdate($table, $query)
1332
+    {
1333
+        return $this->verifyGenericReplaceQuery("UPDATE", $table, $query);
1334
+    }
1335
+
1336
+    /**
1337
+     * Tests an DELETE FROM query
1338
+     * @param string table The table name to get DDL
1339
+     * @param string query The query to test.
1340
+     * @return string Non-empty if error found
1341
+     */
1342
+    public function verifyDeleteFrom($table, $query)
1343
+    {
1344
+        return $this->verifyGenericReplaceQuery("DELETE FROM", $table, $query);
1345
+    }
1346
+
1347
+    /**
1348
+     * Check if certain database exists
1349
+     * @param string $dbname
1350
+     */
1351
+    public function dbExists($dbname)
1352
+    {
1353
+        $db = $this->getOne("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ".$this->quoted($dbname));
1354
+        return !empty($db);
1355
+    }
1356
+
1357
+    /**
1358
+     * Select database
1359
+     * @param string $dbname
1360
+     */
1361
+    protected function selectDb($dbname)
1362
+    {
1363
+        return mysql_select_db($dbname);
1364
+    }
1365
+
1366
+    /**
1367
+     * Check if certain DB user exists
1368
+     * @param string $username
1369
+     */
1370
+    public function userExists($username)
1371
+    {
1372
+        $db = $this->getOne("SELECT DATABASE()");
1373
+        if(!$this->selectDb("mysql")) {
1374
+            return false;
1375
+        }
1376
+        $user = $this->getOne("select count(*) from user where user = ".$this->quoted($username));
1377
+        if(!$this->selectDb($db)) {
1378
+            $this->checkError("Cannot select database $db", true);
1379
+        }
1380
+        return !empty($user);
1381
+    }
1382
+
1383
+    /**
1384
+     * Create DB user
1385
+     * @param string $database_name
1386
+     * @param string $host_name
1387
+     * @param string $user
1388
+     * @param string $password
1389
+     */
1390
+    public function createDbUser($database_name, $host_name, $user, $password)
1391
+    {
1392
+        $qpassword = $this->quote($password);
1393
+        $this->query("GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
1394 1394
 							ON `$database_name`.*
1395 1395
 							TO \"$user\"@\"$host_name\"
1396 1396
 							IDENTIFIED BY '{$qpassword}';", true);
1397 1397
 
1398
-		$this->query("SET PASSWORD FOR \"{$user}\"@\"{$host_name}\" = password('{$qpassword}');", true);
1399
-		if($host_name != 'localhost') {
1400
-			$this->createDbUser($database_name, "localhost", $user, $password);
1401
-		}
1402
-	}
1403
-
1404
-	/**
1405
-	 * Create a database
1406
-	 * @param string $dbname
1407
-	 */
1408
-	public function createDatabase($dbname)
1409
-	{
1410
-		$this->query("CREATE DATABASE `$dbname` CHARACTER SET utf8 COLLATE utf8_general_ci", true);
1411
-	}
1412
-
1413
-	public function preInstall()
1414
-	{
1415
-		$db->query("ALTER DATABASE `{$setup_db_database_name}` DEFAULT CHARACTER SET utf8", true);
1416
-		$db->query("ALTER DATABASE `{$setup_db_database_name}` DEFAULT COLLATE utf8_general_ci", true);
1417
-
1418
-	}
1419
-
1420
-	/**
1421
-	 * Drop a database
1422
-	 * @param string $dbname
1423
-	 */
1424
-	public function dropDatabase($dbname)
1425
-	{
1426
-		return $this->query("DROP DATABASE IF EXISTS `$dbname`", true);
1427
-	}
1428
-
1429
-	/**
1430
-	 * Check if this driver can be used
1431
-	 * @return bool
1432
-	 */
1433
-	public function valid()
1434
-	{
1435
-		return function_exists("mysql_connect");
1436
-	}
1437
-
1438
-	/**
1439
-	 * Check DB version
1440
-	 * @see DBManager::canInstall()
1441
-	 */
1442
-	public function canInstall()
1443
-	{
1444
-		$db_version = $this->version();
1445
-		if(empty($db_version)) {
1446
-			return array('ERR_DB_VERSION_FAILURE');
1447
-		}
1448
-		if(version_compare($db_version, '4.1.2') < 0) {
1449
-			return array('ERR_DB_MYSQL_VERSION', $db_version);
1450
-		}
1451
-		return true;
1452
-	}
1453
-
1454
-	public function installConfig()
1455
-	{
1456
-		return array(
1457
-			'LBL_DBCONFIG_MSG3' =>  array(
1458
-				"setup_db_database_name" => array("label" => 'LBL_DBCONF_DB_NAME', "required" => true),
1459
-			),
1460
-			'LBL_DBCONFIG_MSG2' =>  array(
1461
-				"setup_db_host_name" => array("label" => 'LBL_DBCONF_HOST_NAME', "required" => true),
1462
-			),
1463
-			'LBL_DBCONF_TITLE_USER_INFO' => array(),
1464
-			'LBL_DBCONFIG_B_MSG1' => array(
1465
-				"setup_db_admin_user_name" => array("label" => 'LBL_DBCONF_DB_ADMIN_USER', "required" => true),
1466
-				"setup_db_admin_password" => array("label" => 'LBL_DBCONF_DB_ADMIN_PASSWORD', "type" => "password"),
1467
-			)
1468
-		);
1469
-	}
1470
-
1471
-	/**
1472
-	 * Disable keys on the table
1473
-	 * @abstract
1474
-	 * @param string $tableName
1475
-	 */
1476
-	public function disableKeys($tableName)
1477
-	{
1478
-	    return $this->query('ALTER TABLE '.$tableName.' DISABLE KEYS');
1479
-	}
1480
-
1481
-	/**
1482
-	 * Re-enable keys on the table
1483
-	 * @abstract
1484
-	 * @param string $tableName
1485
-	 */
1486
-	public function enableKeys($tableName)
1487
-	{
1488
-	    return $this->query('ALTER TABLE '.$tableName.' ENABLE KEYS');
1489
-	}
1398
+        $this->query("SET PASSWORD FOR \"{$user}\"@\"{$host_name}\" = password('{$qpassword}');", true);
1399
+        if($host_name != 'localhost') {
1400
+            $this->createDbUser($database_name, "localhost", $user, $password);
1401
+        }
1402
+    }
1403
+
1404
+    /**
1405
+     * Create a database
1406
+     * @param string $dbname
1407
+     */
1408
+    public function createDatabase($dbname)
1409
+    {
1410
+        $this->query("CREATE DATABASE `$dbname` CHARACTER SET utf8 COLLATE utf8_general_ci", true);
1411
+    }
1412
+
1413
+    public function preInstall()
1414
+    {
1415
+        $db->query("ALTER DATABASE `{$setup_db_database_name}` DEFAULT CHARACTER SET utf8", true);
1416
+        $db->query("ALTER DATABASE `{$setup_db_database_name}` DEFAULT COLLATE utf8_general_ci", true);
1417
+
1418
+    }
1419
+
1420
+    /**
1421
+     * Drop a database
1422
+     * @param string $dbname
1423
+     */
1424
+    public function dropDatabase($dbname)
1425
+    {
1426
+        return $this->query("DROP DATABASE IF EXISTS `$dbname`", true);
1427
+    }
1428
+
1429
+    /**
1430
+     * Check if this driver can be used
1431
+     * @return bool
1432
+     */
1433
+    public function valid()
1434
+    {
1435
+        return function_exists("mysql_connect");
1436
+    }
1437
+
1438
+    /**
1439
+     * Check DB version
1440
+     * @see DBManager::canInstall()
1441
+     */
1442
+    public function canInstall()
1443
+    {
1444
+        $db_version = $this->version();
1445
+        if(empty($db_version)) {
1446
+            return array('ERR_DB_VERSION_FAILURE');
1447
+        }
1448
+        if(version_compare($db_version, '4.1.2') < 0) {
1449
+            return array('ERR_DB_MYSQL_VERSION', $db_version);
1450
+        }
1451
+        return true;
1452
+    }
1453
+
1454
+    public function installConfig()
1455
+    {
1456
+        return array(
1457
+            'LBL_DBCONFIG_MSG3' =>  array(
1458
+                "setup_db_database_name" => array("label" => 'LBL_DBCONF_DB_NAME', "required" => true),
1459
+            ),
1460
+            'LBL_DBCONFIG_MSG2' =>  array(
1461
+                "setup_db_host_name" => array("label" => 'LBL_DBCONF_HOST_NAME', "required" => true),
1462
+            ),
1463
+            'LBL_DBCONF_TITLE_USER_INFO' => array(),
1464
+            'LBL_DBCONFIG_B_MSG1' => array(
1465
+                "setup_db_admin_user_name" => array("label" => 'LBL_DBCONF_DB_ADMIN_USER', "required" => true),
1466
+                "setup_db_admin_password" => array("label" => 'LBL_DBCONF_DB_ADMIN_PASSWORD', "type" => "password"),
1467
+            )
1468
+        );
1469
+    }
1470
+
1471
+    /**
1472
+     * Disable keys on the table
1473
+     * @abstract
1474
+     * @param string $tableName
1475
+     */
1476
+    public function disableKeys($tableName)
1477
+    {
1478
+        return $this->query('ALTER TABLE '.$tableName.' DISABLE KEYS');
1479
+    }
1480
+
1481
+    /**
1482
+     * Re-enable keys on the table
1483
+     * @abstract
1484
+     * @param string $tableName
1485
+     */
1486
+    public function enableKeys($tableName)
1487
+    {
1488
+        return $this->query('ALTER TABLE '.$tableName.' ENABLE KEYS');
1489
+    }
1490 1490
 
1491 1491
     /**
1492 1492
      * Returns a DB specific FROM clause which can be used to select against functions.
@@ -1505,8 +1505,8 @@  discard block
 block discarded – undo
1505 1505
      * @return string
1506 1506
      */
1507 1507
 
1508
-	public function getGuidSQL()
1508
+    public function getGuidSQL()
1509 1509
     {
1510
-      	return 'UUID()';
1510
+            return 'UUID()';
1511 1511
     }
1512 1512
 }
Please login to merge, or discard this patch.
Spacing   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -174,25 +174,25 @@  discard block
 block discarded – undo
174 174
 	 */
175 175
 	public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
176 176
 	{
177
-		if(is_array($sql)) {
177
+		if (is_array($sql)) {
178 178
 			return $this->queryArray($sql, $dieOnError, $msg, $suppress);
179 179
 		}
180 180
 
181 181
 		parent::countQuery($sql);
182
-		$GLOBALS['log']->info('Query:' . $sql);
182
+		$GLOBALS['log']->info('Query:'.$sql);
183 183
 		$this->checkConnection();
184 184
 		$this->query_time = microtime(true);
185 185
 		$this->lastsql = $sql;
186
-		$result = $suppress?@mysql_query($sql, $this->database):mysql_query($sql, $this->database);
186
+		$result = $suppress ? @mysql_query($sql, $this->database) : mysql_query($sql, $this->database);
187 187
 
188 188
 		$this->query_time = microtime(true) - $this->query_time;
189 189
 		$GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
190 190
 
191 191
 
192
-		if($keepResult)
192
+		if ($keepResult)
193 193
 			$this->lastResult = $result;
194 194
 
195
-		$this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
195
+		$this->checkError($msg.' Query Failed:'.$sql.'::', $dieOnError);
196 196
 		return $result;
197 197
 	}
198 198
 
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 	public function disconnect()
229 229
 	{
230 230
 		$GLOBALS['log']->debug('Calling MySQL::disconnect()');
231
-		if(!empty($this->database)){
231
+		if (!empty($this->database)) {
232 232
 			$this->freeResult();
233 233
 			mysql_close($this->database);
234 234
 			$this->database = null;
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
 	 */
241 241
 	protected function freeDbResult($dbResult)
242 242
 	{
243
-		if(!empty($dbResult))
243
+		if (!empty($dbResult))
244 244
 			mysql_free_result($dbResult);
245 245
 	}
246 246
 
@@ -266,15 +266,15 @@  discard block
 block discarded – undo
266 266
         $count = (int)$count;
267 267
 	    if ($start < 0)
268 268
 			$start = 0;
269
-		$GLOBALS['log']->debug('Limit Query:' . $sql. ' Start: ' .$start . ' count: ' . $count);
269
+		$GLOBALS['log']->debug('Limit Query:'.$sql.' Start: '.$start.' count: '.$count);
270 270
 
271 271
 	    $sql = "$sql LIMIT $start,$count";
272 272
 		$this->lastsql = $sql;
273 273
 
274
-		if(!empty($GLOBALS['sugar_config']['check_query'])){
274
+		if (!empty($GLOBALS['sugar_config']['check_query'])) {
275 275
 			$this->checkQuery($sql);
276 276
 		}
277
-		if(!$execute) {
277
+		if (!$execute) {
278 278
 			return $sql;
279 279
 		}
280 280
 
@@ -287,14 +287,14 @@  discard block
 block discarded – undo
287 287
 	 */
288 288
 	protected function checkQuery($sql, $object_name = false)
289 289
 	{
290
-		$result   = $this->query('EXPLAIN ' . $sql);
290
+		$result   = $this->query('EXPLAIN '.$sql);
291 291
 		$badQuery = array();
292 292
 		while ($row = $this->fetchByAssoc($result)) {
293 293
 			if (empty($row['table']))
294 294
 				continue;
295 295
 			$badQuery[$row['table']] = '';
296 296
 			if (strtoupper($row['type']) == 'ALL')
297
-				$badQuery[$row['table']]  .=  ' Full Table Scan;';
297
+				$badQuery[$row['table']] .= ' Full Table Scan;';
298 298
 			if (empty($row['key']))
299 299
 				$badQuery[$row['table']] .= ' No Index Key Used;';
300 300
 			if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using filesort') > 0)
@@ -303,18 +303,18 @@  discard block
 block discarded – undo
303 303
 				$badQuery[$row['table']] .= ' Using Temporary Table;';
304 304
 		}
305 305
 
306
-		if ( empty($badQuery) )
306
+		if (empty($badQuery))
307 307
 			return true;
308 308
 
309
-		foreach($badQuery as $table=>$data ){
310
-			if(!empty($data)){
311
-				$warning = ' Table:' . $table . ' Data:' . $data;
312
-				if(!empty($GLOBALS['sugar_config']['check_query_log'])){
309
+		foreach ($badQuery as $table=>$data) {
310
+			if (!empty($data)) {
311
+				$warning = ' Table:'.$table.' Data:'.$data;
312
+				if (!empty($GLOBALS['sugar_config']['check_query_log'])) {
313 313
 					$GLOBALS['log']->fatal($sql);
314
-					$GLOBALS['log']->fatal('CHECK QUERY:' .$warning);
314
+					$GLOBALS['log']->fatal('CHECK QUERY:'.$warning);
315 315
 				}
316
-				else{
317
-					$GLOBALS['log']->warn('CHECK QUERY:' .$warning);
316
+				else {
317
+					$GLOBALS['log']->warn('CHECK QUERY:'.$warning);
318 318
 				}
319 319
 			}
320 320
 		}
@@ -331,19 +331,19 @@  discard block
 block discarded – undo
331 331
 		$result = $this->query("DESCRIBE $tablename");
332 332
 
333 333
 		$columns = array();
334
-		while (($row=$this->fetchByAssoc($result)) !=null) {
334
+		while (($row = $this->fetchByAssoc($result)) != null) {
335 335
 			$name = strtolower($row['Field']);
336
-			$columns[$name]['name']=$name;
336
+			$columns[$name]['name'] = $name;
337 337
 			$matches = array();
338 338
 			preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*)\)|)( unsigned)?/i', $row['Type'], $matches);
339
-			$columns[$name]['type']=strtolower($matches[1][0]);
340
-			if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) )
341
-				$columns[$name]['len']=strtolower($matches[2][0]);
342
-			if ( stristr($row['Extra'],'auto_increment') )
339
+			$columns[$name]['type'] = strtolower($matches[1][0]);
340
+			if (isset($matches[2][0]) && in_array(strtolower($matches[1][0]), array('varchar', 'char', 'varchar2', 'int', 'decimal', 'float')))
341
+				$columns[$name]['len'] = strtolower($matches[2][0]);
342
+			if (stristr($row['Extra'], 'auto_increment'))
343 343
 				$columns[$name]['auto_increment'] = '1';
344
-			if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI'))
344
+			if ($row['Null'] == 'NO' && !stristr($row['Key'], 'PRI'))
345 345
 				$columns[$name]['required'] = 'true';
346
-			if (!empty($row['Default']) )
346
+			if (!empty($row['Default']))
347 347
 				$columns[$name]['default'] = $row['Default'];
348 348
 		}
349 349
 		return $columns;
@@ -352,20 +352,20 @@  discard block
 block discarded – undo
352 352
 	/**
353 353
 	 * @see DBManager::getFieldsArray()
354 354
 	 */
355
-	public function getFieldsArray($result, $make_lower_case=false)
355
+	public function getFieldsArray($result, $make_lower_case = false)
356 356
 	{
357 357
 		$field_array = array();
358 358
 
359
-		if(empty($result))
359
+		if (empty($result))
360 360
 			return 0;
361 361
 
362 362
 		$fields = mysql_num_fields($result);
363
-		for ($i=0; $i < $fields; $i++) {
363
+		for ($i = 0; $i < $fields; $i++) {
364 364
 			$meta = mysql_fetch_field($result, $i);
365 365
 			if (!$meta)
366 366
 				return array();
367 367
 
368
-			if($make_lower_case == true)
368
+			if ($make_lower_case == true)
369 369
 				$meta->name = strtolower($meta->name);
370 370
 
371 371
 			$field_array[] = $meta->name;
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
 			if (!empty($r)) {
398 398
 				while ($a = $this->fetchByAssoc($r)) {
399 399
 					$row = array_values($a);
400
-					$tables[]=$row[0];
400
+					$tables[] = $row[0];
401 401
 				}
402 402
 				return $tables;
403 403
 			}
@@ -423,7 +423,7 @@  discard block
 block discarded – undo
423 423
 
424 424
 		if ($this->getDatabase()) {
425 425
 			$result = $this->query("SHOW TABLES LIKE ".$this->quoted($tableName));
426
-			if(empty($result)) return false;
426
+			if (empty($result)) return false;
427 427
 			$row = $this->fetchByAssoc($result);
428 428
 			return !empty($row);
429 429
 		}
@@ -444,7 +444,7 @@  discard block
 block discarded – undo
444 444
 			if (!empty($r)) {
445 445
 				while ($a = $this->fetchByAssoc($r)) {
446 446
 					$row = array_values($a);
447
-					$tables[]=$row[0];
447
+					$tables[] = $row[0];
448 448
 				}
449 449
 				return $tables;
450 450
 			}
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
 	 */
458 458
 	public function quote($string)
459 459
 	{
460
-		if(is_array($string)) {
460
+		if (is_array($string)) {
461 461
 			return $this->arrayQuote($string);
462 462
 		}
463 463
 		return mysqli_real_escape_string($this->quoteInternal($string), $this->getDatabase());
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
 	{
479 479
 		global $sugar_config;
480 480
 
481
-		if(is_null($configOptions))
481
+		if (is_null($configOptions))
482 482
 			$configOptions = $sugar_config['dbconfig'];
483 483
 
484 484
 		if ($this->getOption('persistent')) {
@@ -495,10 +495,10 @@  discard block
 block discarded – undo
495 495
 					$configOptions['db_user_name'],
496 496
 					$configOptions['db_password']
497 497
 					);
498
-			if(empty($this->database)) {
498
+			if (empty($this->database)) {
499 499
 				$GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name']." as ".$configOptions['db_user_name'].":".mysql_error());
500
-				if($dieOnError) {
501
-					if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
500
+				if ($dieOnError) {
501
+					if (isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
502 502
 						sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
503 503
 					} else {
504 504
 						sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
@@ -508,15 +508,15 @@  discard block
 block discarded – undo
508 508
 				}
509 509
 			}
510 510
 			// Do not pass connection information because we have not connected yet
511
-			if($this->database  && $this->getOption('persistent')){
511
+			if ($this->database && $this->getOption('persistent')) {
512 512
 				$_SESSION['administrator_error'] = "<b>Severe Performance Degradation: Persistent Database Connections "
513 513
 					. "not working.  Please set \$sugar_config['dbconfigoption']['persistent'] to false "
514 514
 					. "in your config.php file</b>";
515 515
 			}
516 516
 		}
517
-		if(!empty($configOptions['db_name']) && !@mysql_select_db($configOptions['db_name'])) {
518
-			$GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}: " . mysql_error($this->database));
519
-			if($dieOnError) {
517
+		if (!empty($configOptions['db_name']) && !@mysql_select_db($configOptions['db_name'])) {
518
+			$GLOBALS['log']->fatal("Unable to select database {$configOptions['db_name']}: ".mysql_error($this->database));
519
+			if ($dieOnError) {
520 520
 				sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
521 521
 			} else {
522 522
 				return false;
@@ -527,12 +527,12 @@  discard block
 block discarded – undo
527 527
 	    mysql_query("SET CHARACTER SET utf8", $this->database);
528 528
 	    $names = "SET NAMES 'utf8'";
529 529
 	    $collation = $this->getOption('collation');
530
-	    if(!empty($collation)) {
530
+	    if (!empty($collation)) {
531 531
 	        $names .= " COLLATE '$collation'";
532 532
 		}
533 533
 	    mysql_query($names, $this->database);
534 534
 
535
-		if(!$this->checkError('Could Not Connect:', $dieOnError))
535
+		if (!$this->checkError('Could Not Connect:', $dieOnError))
536 536
 			$GLOBALS['log']->info("connected to db");
537 537
 		$this->connectOptions = $configOptions;
538 538
 
@@ -548,16 +548,16 @@  discard block
 block discarded – undo
548 548
 	 */
549 549
 	public function repairTableParams($tablename, $fielddefs, $indices, $execute = true, $engine = null)
550 550
 	{
551
-		$sql = parent::repairTableParams($tablename,$fielddefs,$indices,false,$engine);
551
+		$sql = parent::repairTableParams($tablename, $fielddefs, $indices, false, $engine);
552 552
 
553
-		if ( $sql == '' )
553
+		if ($sql == '')
554 554
 			return '';
555 555
 
556
-		if ( stristr($sql,'create table') )
556
+		if (stristr($sql, 'create table'))
557 557
 		{
558 558
 			if ($execute) {
559
-				$msg = "Error creating table: ".$tablename. ":";
560
-				$this->query($sql,true,$msg);
559
+				$msg = "Error creating table: ".$tablename.":";
560
+				$this->query($sql, true, $msg);
561 561
 			}
562 562
 			return $sql;
563 563
 		}
@@ -566,23 +566,23 @@  discard block
 block discarded – undo
566 566
 		$match = array();
567 567
 		preg_match_all('!/\*.*?\*/!is', $sql, $match);
568 568
 		$commentBlocks = $match[0];
569
-		$sql = preg_replace('!/\*.*?\*/!is','', $sql);
569
+		$sql = preg_replace('!/\*.*?\*/!is', '', $sql);
570 570
 
571 571
 		// now, we should only have alter table statements
572 572
 		// let's replace the 'alter table name' part with a comma
573
-		$sql = preg_replace("!alter table $tablename!is",', ', $sql);
573
+		$sql = preg_replace("!alter table $tablename!is", ', ', $sql);
574 574
 
575 575
 		// re-add it at the beginning
576
-		$sql = substr_replace($sql,'',strpos($sql,','),1);
577
-		$sql = str_replace(";","",$sql);
578
-		$sql = str_replace("\n","",$sql);
576
+		$sql = substr_replace($sql, '', strpos($sql, ','), 1);
577
+		$sql = str_replace(";", "", $sql);
578
+		$sql = str_replace("\n", "", $sql);
579 579
 		$sql = "ALTER TABLE $tablename $sql";
580 580
 
581
-		if ( $execute )
582
-			$this->query($sql,'Error with MySQL repair table');
581
+		if ($execute)
582
+			$this->query($sql, 'Error with MySQL repair table');
583 583
 
584 584
 		// and re-add the comments at the beginning
585
-		$sql = implode("\n",$commentBlocks) . "\n". $sql . "\n";
585
+		$sql = implode("\n", $commentBlocks)."\n".$sql."\n";
586 586
 
587 587
 		return $sql;
588 588
 	}
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
 	public function convert($string, $type, array $additional_parameters = array())
594 594
 	{
595 595
 		$all_parameters = $additional_parameters;
596
-		if(is_array($string)) {
596
+		if (is_array($string)) {
597 597
 			$all_parameters = array_merge($string, $all_parameters);
598 598
 		} elseif (!is_null($string)) {
599 599
 			array_unshift($all_parameters, $string);
@@ -606,17 +606,17 @@  discard block
 block discarded – undo
606 606
 			case 'left':
607 607
 				return "LEFT($all_strings)";
608 608
 			case 'date_format':
609
-				if(empty($additional_parameters)) {
609
+				if (empty($additional_parameters)) {
610 610
 					return "DATE_FORMAT($string,'%Y-%m-%d')";
611 611
 				} else {
612 612
 					$format = $additional_parameters[0];
613
-					if($format[0] != "'") {
613
+					if ($format[0] != "'") {
614 614
 						$format = $this->quoted($format);
615 615
 					}
616 616
 					return "DATE_FORMAT($string,$format)";
617 617
 				}
618 618
 			case 'ifnull':
619
-				if(empty($additional_parameters) && !strstr($all_strings, ",")) {
619
+				if (empty($additional_parameters) && !strstr($all_strings, ",")) {
620 620
 					$all_strings .= ",''";
621 621
 				}
622 622
 				return "IFNULL($all_strings)";
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
             case 'add_tz_offset' :
636 636
                 $getUserUTCOffset = $GLOBALS['timedate']->getUserUTCOffset();
637 637
                 $operation = $getUserUTCOffset < 0 ? '-' : '+';
638
-                return $string . ' ' . $operation . ' INTERVAL ' . abs($getUserUTCOffset) . ' MINUTE';
638
+                return $string.' '.$operation.' INTERVAL '.abs($getUserUTCOffset).' MINUTE';
639 639
             case 'avg':
640 640
                 return "avg($string)";
641 641
 		}
@@ -676,15 +676,15 @@  discard block
 block discarded – undo
676 676
 	 */
677 677
 	protected function isEngineEnabled($engine)
678 678
 	{
679
-		if(!is_string($engine)) return false;
679
+		if (!is_string($engine)) return false;
680 680
 
681 681
 		$engine = strtoupper($engine);
682 682
 
683 683
 		$r = $this->query("SHOW ENGINES");
684 684
 
685
-		while ( $row = $this->fetchByAssoc($r) )
686
-			if ( strtoupper($row['Engine']) == $engine )
687
-				return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
685
+		while ($row = $this->fetchByAssoc($r))
686
+			if (strtoupper($row['Engine']) == $engine)
687
+				return ($row['Support'] == 'YES' || $row['Support'] == 'DEFAULT');
688 688
 
689 689
 		return false;
690 690
 	}
@@ -712,9 +712,9 @@  discard block
 block discarded – undo
712 712
 	*/
713 713
 	public function createTableSQLParams($tablename, $fieldDefs, $indices, $engine = null)
714 714
 	{
715
-		if ( empty($engine) && isset($fieldDefs['engine']))
715
+		if (empty($engine) && isset($fieldDefs['engine']))
716 716
 			$engine = $fieldDefs['engine'];
717
-		if ( !$this->isEngineEnabled($engine) )
717
+		if (!$this->isEngineEnabled($engine))
718 718
 			$engine = '';
719 719
 
720 720
 		$columns = $this->columnSQLRep($fieldDefs, false, $tablename);
@@ -727,13 +727,13 @@  discard block
 block discarded – undo
727 727
 
728 728
 		// cn: bug 9873 - module tables do not get created in utf8 with assoc collation
729 729
 		$collation = $this->getOption('collation');
730
-		if(empty($collation)) {
730
+		if (empty($collation)) {
731 731
 		    $collation = 'utf8_general_ci';
732 732
 		}
733 733
 		$sql = "CREATE TABLE $tablename ($columns $keys) CHARACTER SET utf8 COLLATE $collation";
734 734
 
735 735
 		if (!empty($engine))
736
-			$sql.= " ENGINE=$engine";
736
+			$sql .= " ENGINE=$engine";
737 737
 
738 738
 		return $sql;
739 739
 	}
@@ -745,7 +745,7 @@  discard block
 block discarded – undo
745 745
     public function isTextType($type)
746 746
     {
747 747
         $type = $this->getColumnType(strtolower($type));
748
-        return in_array($type, array('blob','text','longblob', 'longtext'));
748
+        return in_array($type, array('blob', 'text', 'longblob', 'longtext'));
749 749
     }
750 750
 
751 751
 	/**
@@ -756,16 +756,16 @@  discard block
 block discarded – undo
756 756
 		// always return as array for post-processing
757 757
 		$ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
758 758
 
759
-		if ( $ref['colType'] == 'int' && !empty($fieldDef['len']) ) {
759
+		if ($ref['colType'] == 'int' && !empty($fieldDef['len'])) {
760 760
 			$ref['colType'] .= "(".$fieldDef['len'].")";
761 761
 		}
762 762
 
763 763
 		// bug 22338 - don't set a default value on text or blob fields
764
-		if ( isset($ref['default']) &&
764
+		if (isset($ref['default']) &&
765 765
             in_array($ref['colBaseType'], array('text', 'blob', 'longtext', 'longblob')))
766 766
 			    $ref['default'] = '';
767 767
 
768
-		if ( $return_as_array )
768
+		if ($return_as_array)
769 769
 			return $ref;
770 770
 		else
771 771
 			return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
@@ -777,8 +777,8 @@  discard block
 block discarded – undo
777 777
 	protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
778 778
 	{
779 779
 		$columns = array();
780
-		if ($this->isFieldArray($fieldDefs)){
781
-			foreach ($fieldDefs as $def){
780
+		if ($this->isFieldArray($fieldDefs)) {
781
+			foreach ($fieldDefs as $def) {
782 782
 				if ($action == 'drop')
783 783
 					$columns[] = $def['name'];
784 784
 				else
@@ -815,7 +815,7 @@  discard block
 block discarded – undo
815 815
 
816 816
 	$columns = array();
817 817
 	foreach ($indices as $index) {
818
-		if(!empty($index['db']) && $index['db'] != $this->dbType)
818
+		if (!empty($index['db']) && $index['db'] != $this->dbType)
819 819
 			continue;
820 820
 		if (isset($index['source']) && $index['source'] != 'db')
821 821
 			continue;
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
 				* that this can easily be fixed by referring to db dictionary
846 846
 				* to find the correct primary field name
847 847
 				*/
848
-			if ( $alter_table )
848
+			if ($alter_table)
849 849
 				$columns[] = " INDEX $name ($fields)";
850 850
 			else
851 851
 				$columns[] = " KEY $name ($fields)";
@@ -854,13 +854,13 @@  discard block
 block discarded – undo
854 854
 			if ($this->full_text_indexing_installed())
855 855
 				$columns[] = " FULLTEXT ($fields)";
856 856
 			else
857
-				$GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
857
+				$GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:', $name);
858 858
 			break;
859 859
 		}
860 860
 	}
861 861
 	$columns = implode(", $alter_action ", $columns);
862
-	if(!empty($alter_action)){
863
-		$columns = $alter_action . ' '. $columns;
862
+	if (!empty($alter_action)) {
863
+		$columns = $alter_action.' '.$columns;
864 864
 	}
865 865
 	return $columns;
866 866
 	}
@@ -882,7 +882,7 @@  discard block
 block discarded – undo
882 882
 	public function setAutoIncrementStart($table, $field_name, $start_value)
883 883
 	{
884 884
 		$start_value = (int)$start_value;
885
-		return $this->query( "ALTER TABLE $table AUTO_INCREMENT = $start_value;");
885
+		return $this->query("ALTER TABLE $table AUTO_INCREMENT = $start_value;");
886 886
 	}
887 887
 
888 888
 	/**
@@ -911,18 +911,18 @@  discard block
 block discarded – undo
911 911
 		$result = $this->query("SHOW INDEX FROM $tablename");
912 912
 
913 913
 		$indices = array();
914
-		while (($row=$this->fetchByAssoc($result)) !=null) {
915
-			$index_type='index';
916
-			if ($row['Key_name'] =='PRIMARY') {
917
-				$index_type='primary';
914
+		while (($row = $this->fetchByAssoc($result)) != null) {
915
+			$index_type = 'index';
916
+			if ($row['Key_name'] == 'PRIMARY') {
917
+				$index_type = 'primary';
918 918
 			}
919
-			elseif ( $row['Non_unique'] == '0' ) {
920
-				$index_type='unique';
919
+			elseif ($row['Non_unique'] == '0') {
920
+				$index_type = 'unique';
921 921
 			}
922 922
 			$name = strtolower($row['Key_name']);
923
-			$indices[$name]['name']=$name;
924
-			$indices[$name]['type']=$index_type;
925
-			$indices[$name]['fields'][]=strtolower($row['Column_name']);
923
+			$indices[$name]['name'] = $name;
924
+			$indices[$name]['type'] = $index_type;
925
+			$indices[$name]['fields'][] = strtolower($row['Column_name']);
926 926
 		}
927 927
 		return $indices;
928 928
 	}
@@ -933,11 +933,11 @@  discard block
 block discarded – undo
933 933
 	public function add_drop_constraint($table, $definition, $drop = false)
934 934
 	{
935 935
 		$type         = $definition['type'];
936
-		$fields       = implode(',',$definition['fields']);
936
+		$fields       = implode(',', $definition['fields']);
937 937
 		$name         = $definition['name'];
938 938
 		$sql          = '';
939 939
 
940
-		switch ($type){
940
+		switch ($type) {
941 941
 		// generic indices
942 942
 		case 'index':
943 943
 		case 'alternate_key':
@@ -981,7 +981,7 @@  discard block
 block discarded – undo
981 981
 	 */
982 982
 	public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false)
983 983
 	{
984
-		if(stripos($sql, ' LIMIT ') === false) {
984
+		if (stripos($sql, ' LIMIT ') === false) {
985 985
 			// little optimization to just fetch one row
986 986
 			$sql .= " LIMIT 0,1";
987 987
 		}
@@ -1001,13 +1001,13 @@  discard block
 block discarded – undo
1001 1001
 	 */
1002 1002
 	public function massageFieldDef(&$fieldDef, $tablename)
1003 1003
 	{
1004
-		parent::massageFieldDef($fieldDef,$tablename);
1004
+		parent::massageFieldDef($fieldDef, $tablename);
1005 1005
 
1006
-		if ( isset($fieldDef['default']) &&
1006
+		if (isset($fieldDef['default']) &&
1007 1007
 			($fieldDef['dbType'] == 'text'
1008 1008
 				|| $fieldDef['dbType'] == 'blob'
1009 1009
 				|| $fieldDef['dbType'] == 'longtext'
1010
-				|| $fieldDef['dbType'] == 'longblob' ))
1010
+				|| $fieldDef['dbType'] == 'longblob'))
1011 1011
 			unset($fieldDef['default']);
1012 1012
 		if ($fieldDef['dbType'] == 'uint')
1013 1013
 			$fieldDef['len'] = '10';
@@ -1015,22 +1015,22 @@  discard block
 block discarded – undo
1015 1015
 			$fieldDef['len'] = '20';
1016 1016
 		if ($fieldDef['dbType'] == 'bool')
1017 1017
 			$fieldDef['type'] = 'tinyint';
1018
-		if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) )
1018
+		if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']))
1019 1019
 			$fieldDef['default'] = '0';
1020
-		if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) )
1020
+		if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']))
1021 1021
 			$fieldDef['len'] = '255';
1022 1022
 		if ($fieldDef['dbType'] == 'uint')
1023 1023
 			$fieldDef['len'] = '10';
1024
-		if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) )
1024
+		if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']))
1025 1025
 			$fieldDef['len'] = '11';
1026 1026
 
1027
-		if($fieldDef['dbType'] == 'decimal') {
1028
-			if(isset($fieldDef['len'])) {
1029
-				if(strstr($fieldDef['len'], ",") === false) {
1027
+		if ($fieldDef['dbType'] == 'decimal') {
1028
+			if (isset($fieldDef['len'])) {
1029
+				if (strstr($fieldDef['len'], ",") === false) {
1030 1030
 					$fieldDef['len'] .= ",0";
1031 1031
 				}
1032 1032
 			} else {
1033
-				$fieldDef['len']  = '10,0';
1033
+				$fieldDef['len'] = '10,0';
1034 1034
 			}
1035 1035
 		}
1036 1036
 	}
@@ -1050,8 +1050,8 @@  discard block
 block discarded – undo
1050 1050
 	{
1051 1051
 		$sql = array();
1052 1052
 		foreach ($indexes as $index) {
1053
-			$name =$index['name'];
1054
-			if($execute) {
1053
+			$name = $index['name'];
1054
+			if ($execute) {
1055 1055
 			unset(self::$index_descriptions[$tablename][$name]);
1056 1056
 			}
1057 1057
 			if ($index['type'] == 'primary') {
@@ -1061,8 +1061,8 @@  discard block
 block discarded – undo
1061 1061
 			}
1062 1062
 		}
1063 1063
 		if (!empty($sql)) {
1064
-            $sql = "ALTER TABLE $tablename " . join(",", $sql) . ";";
1065
-			if($execute)
1064
+            $sql = "ALTER TABLE $tablename ".join(",", $sql).";";
1065
+			if ($execute)
1066 1066
 				$this->query($sql);
1067 1067
 		} else {
1068 1068
 			$sql = '';
@@ -1088,7 +1088,7 @@  discard block
 block discarded – undo
1088 1088
 		$q = "SHOW COLLATION LIKE 'utf8%'";
1089 1089
 		$r = $this->query($q);
1090 1090
 		$res = array();
1091
-		while($a = $this->fetchByAssoc($r)) {
1091
+		while ($a = $this->fetchByAssoc($r)) {
1092 1092
 			$res[] = $a['Collation'];
1093 1093
 		}
1094 1094
 		return $res;
@@ -1108,13 +1108,13 @@  discard block
 block discarded – undo
1108 1108
 	public function emptyValue($type)
1109 1109
 	{
1110 1110
 		$ctype = $this->getColumnType($type);
1111
-		if($ctype == "datetime") {
1111
+		if ($ctype == "datetime") {
1112 1112
 			return 'NULL';
1113 1113
 		}
1114
-		if($ctype == "date") {
1114
+		if ($ctype == "date") {
1115 1115
 			return 'NULL';
1116 1116
 		}
1117
-		if($ctype == "time") {
1117
+		if ($ctype == "time") {
1118 1118
 			return 'NULL';
1119 1119
 		}
1120 1120
 		return parent::emptyValue($type);
@@ -1126,13 +1126,13 @@  discard block
 block discarded – undo
1126 1126
 	 */
1127 1127
 	public function lastDbError()
1128 1128
 	{
1129
-		if($this->database) {
1130
-		    if(mysql_errno($this->database)) {
1129
+		if ($this->database) {
1130
+		    if (mysql_errno($this->database)) {
1131 1131
 			    return "MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database);
1132 1132
 		    }
1133 1133
 		} else {
1134
-			$err =  mysql_error();
1135
-			if($err) {
1134
+			$err = mysql_error();
1135
+			if ($err) {
1136 1136
 			    return $err;
1137 1137
 			}
1138 1138
 		}
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
 	 */
1146 1146
 	protected function quoteTerm($term)
1147 1147
 	{
1148
-		if(strpos($term, ' ') !== false) {
1148
+		if (strpos($term, ' ') !== false) {
1149 1149
 			return '"'.$term.'"';
1150 1150
 		}
1151 1151
 		return $term;
@@ -1161,16 +1161,16 @@  discard block
 block discarded – undo
1161 1161
 	public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1162 1162
 	{
1163 1163
 		$condition = array();
1164
-		foreach($terms as $term) {
1164
+		foreach ($terms as $term) {
1165 1165
 			$condition[] = $this->quoteTerm($term);
1166 1166
 		}
1167
-		foreach($must_terms as $term) {
1167
+		foreach ($must_terms as $term) {
1168 1168
 			$condition[] = "+".$this->quoteTerm($term);
1169 1169
 		}
1170
-		foreach($exclude_terms as $term) {
1170
+		foreach ($exclude_terms as $term) {
1171 1171
 			$condition[] = "-".$this->quoteTerm($term);
1172 1172
 		}
1173
-		$condition = $this->quoted(join(" ",$condition));
1173
+		$condition = $this->quoted(join(" ", $condition));
1174 1174
 		return "MATCH($field) AGAINST($condition IN BOOLEAN MODE)";
1175 1175
 	}
1176 1176
 
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
 	{
1183 1183
 		$charsets = array();
1184 1184
 		$res = $this->query("show variables like 'character\\_set\\_%'");
1185
-		while($row = $this->fetchByAssoc($res)) {
1185
+		while ($row = $this->fetchByAssoc($res)) {
1186 1186
 			$charsets[$row['Variable_name']] = $row['Value'];
1187 1187
 		}
1188 1188
 		return $charsets;
@@ -1192,7 +1192,7 @@  discard block
 block discarded – undo
1192 1192
 	{
1193 1193
 		$charsets = $this->getCharsetInfo();
1194 1194
 		$charset_str = array();
1195
-		foreach($charsets as $name => $value) {
1195
+		foreach ($charsets as $name => $value) {
1196 1196
 			$charset_str[] = "$name = $value";
1197 1197
 		}
1198 1198
 		return array(
@@ -1214,18 +1214,18 @@  discard block
 block discarded – undo
1214 1214
 	{
1215 1215
 		$this->log->debug("creating temp table for [$table]...");
1216 1216
 		$result = $this->query("SHOW CREATE TABLE {$table}");
1217
-		if(empty($result)) {
1217
+		if (empty($result)) {
1218 1218
 			return false;
1219 1219
 		}
1220 1220
 		$row = $this->fetchByAssoc($result);
1221
-		if(empty($row) || empty($row['Create Table'])) {
1221
+		if (empty($row) || empty($row['Create Table'])) {
1222 1222
 		    return false;
1223 1223
 		}
1224 1224
 		$create = $row['Create Table'];
1225 1225
 		// rewrite DDL with _temp name
1226 1226
 		$tempTableQuery = str_replace("CREATE TABLE `{$table}`", "CREATE TABLE `{$table}__uw_temp`", $create);
1227 1227
 		$r2 = $this->query($tempTableQuery);
1228
-		if(empty($r2)) {
1228
+		if (empty($r2)) {
1229 1229
 			return false;
1230 1230
 		}
1231 1231
 
@@ -1247,11 +1247,11 @@  discard block
 block discarded – undo
1247 1247
 		$this->log->debug("verifying ALTER TABLE");
1248 1248
 		// Skipping ALTER TABLE [table] DROP PRIMARY KEY because primary keys are not being copied
1249 1249
 		// over to the temp tables
1250
-		if(strpos(strtoupper($query), 'DROP PRIMARY KEY') !== false) {
1250
+		if (strpos(strtoupper($query), 'DROP PRIMARY KEY') !== false) {
1251 1251
 			$this->log->debug("Skipping DROP PRIMARY KEY");
1252 1252
 			return '';
1253 1253
 		}
1254
-		if(!$this->makeTempTableCopy($table)) {
1254
+		if (!$this->makeTempTableCopy($table)) {
1255 1255
 			return 'Could not create temp table copy';
1256 1256
 		}
1257 1257
 
@@ -1259,7 +1259,7 @@  discard block
 block discarded – undo
1259 1259
 		$this->log->debug('testing query: ['.$query.']');
1260 1260
 		$tempTableTestQuery = str_replace("ALTER TABLE `{$table}`", "ALTER TABLE `{$table}__uw_temp`", $query);
1261 1261
 		if (strpos($tempTableTestQuery, 'idx') === false) {
1262
-			if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1262
+			if (strpos($tempTableTestQuery, '__uw_temp') === false) {
1263 1263
 				return 'Could not use a temp table to test query!';
1264 1264
 			}
1265 1265
 
@@ -1272,7 +1272,7 @@  discard block
 block discarded – undo
1272 1272
 			$this->query($tempTableTestQuery_idx, false, "Preflight Failed for: {$query}");
1273 1273
 		}
1274 1274
 		$mysqlError = $this->getL();
1275
-		if(!empty($mysqlError)) {
1275
+		if (!empty($mysqlError)) {
1276 1276
 			return $mysqlError;
1277 1277
 		}
1278 1278
 		$this->dropTableName("{$table}__uw_temp");
@@ -1284,13 +1284,13 @@  discard block
 block discarded – undo
1284 1284
 	{
1285 1285
 		$this->log->debug("verifying $querytype statement");
1286 1286
 
1287
-		if(!$this->makeTempTableCopy($table)) {
1287
+		if (!$this->makeTempTableCopy($table)) {
1288 1288
 			return 'Could not create temp table copy';
1289 1289
 		}
1290 1290
 		// test the query on the test table
1291 1291
 		$this->log->debug('testing query: ['.$query.']');
1292 1292
 		$tempTableTestQuery = str_replace("$querytype `{$table}`", "$querytype `{$table}__uw_temp`", $query);
1293
-		if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1293
+		if (strpos($tempTableTestQuery, '__uw_temp') === false) {
1294 1294
 			return 'Could not use a temp table to test query!';
1295 1295
 		}
1296 1296
 
@@ -1370,11 +1370,11 @@  discard block
 block discarded – undo
1370 1370
 	public function userExists($username)
1371 1371
 	{
1372 1372
 		$db = $this->getOne("SELECT DATABASE()");
1373
-		if(!$this->selectDb("mysql")) {
1373
+		if (!$this->selectDb("mysql")) {
1374 1374
 			return false;
1375 1375
 		}
1376 1376
 		$user = $this->getOne("select count(*) from user where user = ".$this->quoted($username));
1377
-		if(!$this->selectDb($db)) {
1377
+		if (!$this->selectDb($db)) {
1378 1378
 			$this->checkError("Cannot select database $db", true);
1379 1379
 		}
1380 1380
 		return !empty($user);
@@ -1396,7 +1396,7 @@  discard block
 block discarded – undo
1396 1396
 							IDENTIFIED BY '{$qpassword}';", true);
1397 1397
 
1398 1398
 		$this->query("SET PASSWORD FOR \"{$user}\"@\"{$host_name}\" = password('{$qpassword}');", true);
1399
-		if($host_name != 'localhost') {
1399
+		if ($host_name != 'localhost') {
1400 1400
 			$this->createDbUser($database_name, "localhost", $user, $password);
1401 1401
 		}
1402 1402
 	}
@@ -1442,10 +1442,10 @@  discard block
 block discarded – undo
1442 1442
 	public function canInstall()
1443 1443
 	{
1444 1444
 		$db_version = $this->version();
1445
-		if(empty($db_version)) {
1445
+		if (empty($db_version)) {
1446 1446
 			return array('ERR_DB_VERSION_FAILURE');
1447 1447
 		}
1448
-		if(version_compare($db_version, '4.1.2') < 0) {
1448
+		if (version_compare($db_version, '4.1.2') < 0) {
1449 1449
 			return array('ERR_DB_MYSQL_VERSION', $db_version);
1450 1450
 		}
1451 1451
 		return true;
Please login to merge, or discard this patch.
Braces   +181 added lines, -127 removed lines patch added patch discarded remove patch
@@ -189,8 +189,9 @@  discard block
 block discarded – undo
189 189
 		$GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
190 190
 
191 191
 
192
-		if($keepResult)
193
-			$this->lastResult = $result;
192
+		if($keepResult) {
193
+					$this->lastResult = $result;
194
+		}
194 195
 
195 196
 		$this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
196 197
 		return $result;
@@ -240,8 +241,9 @@  discard block
 block discarded – undo
240 241
 	 */
241 242
 	protected function freeDbResult($dbResult)
242 243
 	{
243
-		if(!empty($dbResult))
244
-			mysql_free_result($dbResult);
244
+		if(!empty($dbResult)) {
245
+					mysql_free_result($dbResult);
246
+		}
245 247
 	}
246 248
 
247 249
 
@@ -264,8 +266,9 @@  discard block
 block discarded – undo
264 266
 	{
265 267
         $start = (int)$start;
266 268
         $count = (int)$count;
267
-	    if ($start < 0)
268
-			$start = 0;
269
+	    if ($start < 0) {
270
+	    			$start = 0;
271
+	    }
269 272
 		$GLOBALS['log']->debug('Limit Query:' . $sql. ' Start: ' .$start . ' count: ' . $count);
270 273
 
271 274
 	    $sql = "$sql LIMIT $start,$count";
@@ -290,21 +293,27 @@  discard block
 block discarded – undo
290 293
 		$result   = $this->query('EXPLAIN ' . $sql);
291 294
 		$badQuery = array();
292 295
 		while ($row = $this->fetchByAssoc($result)) {
293
-			if (empty($row['table']))
294
-				continue;
296
+			if (empty($row['table'])) {
297
+							continue;
298
+			}
295 299
 			$badQuery[$row['table']] = '';
296
-			if (strtoupper($row['type']) == 'ALL')
297
-				$badQuery[$row['table']]  .=  ' Full Table Scan;';
298
-			if (empty($row['key']))
299
-				$badQuery[$row['table']] .= ' No Index Key Used;';
300
-			if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using filesort') > 0)
301
-				$badQuery[$row['table']] .= ' Using FileSort;';
302
-			if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using temporary') > 0)
303
-				$badQuery[$row['table']] .= ' Using Temporary Table;';
300
+			if (strtoupper($row['type']) == 'ALL') {
301
+							$badQuery[$row['table']]  .=  ' Full Table Scan;';
302
+			}
303
+			if (empty($row['key'])) {
304
+							$badQuery[$row['table']] .= ' No Index Key Used;';
305
+			}
306
+			if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using filesort') > 0) {
307
+							$badQuery[$row['table']] .= ' Using FileSort;';
308
+			}
309
+			if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using temporary') > 0) {
310
+							$badQuery[$row['table']] .= ' Using Temporary Table;';
311
+			}
304 312
 		}
305 313
 
306
-		if ( empty($badQuery) )
307
-			return true;
314
+		if ( empty($badQuery) ) {
315
+					return true;
316
+		}
308 317
 
309 318
 		foreach($badQuery as $table=>$data ){
310 319
 			if(!empty($data)){
@@ -312,8 +321,7 @@  discard block
 block discarded – undo
312 321
 				if(!empty($GLOBALS['sugar_config']['check_query_log'])){
313 322
 					$GLOBALS['log']->fatal($sql);
314 323
 					$GLOBALS['log']->fatal('CHECK QUERY:' .$warning);
315
-				}
316
-				else{
324
+				} else{
317 325
 					$GLOBALS['log']->warn('CHECK QUERY:' .$warning);
318 326
 				}
319 327
 			}
@@ -337,14 +345,18 @@  discard block
 block discarded – undo
337 345
 			$matches = array();
338 346
 			preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*)\)|)( unsigned)?/i', $row['Type'], $matches);
339 347
 			$columns[$name]['type']=strtolower($matches[1][0]);
340
-			if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) )
341
-				$columns[$name]['len']=strtolower($matches[2][0]);
342
-			if ( stristr($row['Extra'],'auto_increment') )
343
-				$columns[$name]['auto_increment'] = '1';
344
-			if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI'))
345
-				$columns[$name]['required'] = 'true';
346
-			if (!empty($row['Default']) )
347
-				$columns[$name]['default'] = $row['Default'];
348
+			if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) ) {
349
+							$columns[$name]['len']=strtolower($matches[2][0]);
350
+			}
351
+			if ( stristr($row['Extra'],'auto_increment') ) {
352
+							$columns[$name]['auto_increment'] = '1';
353
+			}
354
+			if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI')) {
355
+							$columns[$name]['required'] = 'true';
356
+			}
357
+			if (!empty($row['Default']) ) {
358
+							$columns[$name]['default'] = $row['Default'];
359
+			}
348 360
 		}
349 361
 		return $columns;
350 362
 	}
@@ -356,17 +368,20 @@  discard block
 block discarded – undo
356 368
 	{
357 369
 		$field_array = array();
358 370
 
359
-		if(empty($result))
360
-			return 0;
371
+		if(empty($result)) {
372
+					return 0;
373
+		}
361 374
 
362 375
 		$fields = mysql_num_fields($result);
363 376
 		for ($i=0; $i < $fields; $i++) {
364 377
 			$meta = mysql_fetch_field($result, $i);
365
-			if (!$meta)
366
-				return array();
378
+			if (!$meta) {
379
+							return array();
380
+			}
367 381
 
368
-			if($make_lower_case == true)
369
-				$meta->name = strtolower($meta->name);
382
+			if($make_lower_case == true) {
383
+							$meta->name = strtolower($meta->name);
384
+			}
370 385
 
371 386
 			$field_array[] = $meta->name;
372 387
 		}
@@ -379,7 +394,9 @@  discard block
 block discarded – undo
379 394
 	 */
380 395
 	public function fetchRow($result)
381 396
 	{
382
-		if (empty($result))	return false;
397
+		if (empty($result)) {
398
+		    return false;
399
+		}
383 400
 
384 401
 		return mysql_fetch_assoc($result);
385 402
 	}
@@ -423,7 +440,9 @@  discard block
 block discarded – undo
423 440
 
424 441
 		if ($this->getDatabase()) {
425 442
 			$result = $this->query("SHOW TABLES LIKE ".$this->quoted($tableName));
426
-			if(empty($result)) return false;
443
+			if(empty($result)) {
444
+			    return false;
445
+			}
427 446
 			$row = $this->fetchByAssoc($result);
428 447
 			return !empty($row);
429 448
 		}
@@ -478,8 +497,9 @@  discard block
 block discarded – undo
478 497
 	{
479 498
 		global $sugar_config;
480 499
 
481
-		if(is_null($configOptions))
482
-			$configOptions = $sugar_config['dbconfig'];
500
+		if(is_null($configOptions)) {
501
+					$configOptions = $sugar_config['dbconfig'];
502
+		}
483 503
 
484 504
 		if ($this->getOption('persistent')) {
485 505
 			$this->database = @mysql_pconnect(
@@ -532,8 +552,9 @@  discard block
 block discarded – undo
532 552
 		}
533 553
 	    mysql_query($names, $this->database);
534 554
 
535
-		if(!$this->checkError('Could Not Connect:', $dieOnError))
536
-			$GLOBALS['log']->info("connected to db");
555
+		if(!$this->checkError('Could Not Connect:', $dieOnError)) {
556
+					$GLOBALS['log']->info("connected to db");
557
+		}
537 558
 		$this->connectOptions = $configOptions;
538 559
 
539 560
 		$GLOBALS['log']->info("Connect:".$this->database);
@@ -550,8 +571,9 @@  discard block
 block discarded – undo
550 571
 	{
551 572
 		$sql = parent::repairTableParams($tablename,$fielddefs,$indices,false,$engine);
552 573
 
553
-		if ( $sql == '' )
554
-			return '';
574
+		if ( $sql == '' ) {
575
+					return '';
576
+		}
555 577
 
556 578
 		if ( stristr($sql,'create table') )
557 579
 		{
@@ -578,8 +600,9 @@  discard block
 block discarded – undo
578 600
 		$sql = str_replace("\n","",$sql);
579 601
 		$sql = "ALTER TABLE $tablename $sql";
580 602
 
581
-		if ( $execute )
582
-			$this->query($sql,'Error with MySQL repair table');
603
+		if ( $execute ) {
604
+					$this->query($sql,'Error with MySQL repair table');
605
+		}
583 606
 
584 607
 		// and re-add the comments at the beginning
585 608
 		$sql = implode("\n",$commentBlocks) . "\n". $sql . "\n";
@@ -676,15 +699,18 @@  discard block
 block discarded – undo
676 699
 	 */
677 700
 	protected function isEngineEnabled($engine)
678 701
 	{
679
-		if(!is_string($engine)) return false;
702
+		if(!is_string($engine)) {
703
+		    return false;
704
+		}
680 705
 
681 706
 		$engine = strtoupper($engine);
682 707
 
683 708
 		$r = $this->query("SHOW ENGINES");
684 709
 
685
-		while ( $row = $this->fetchByAssoc($r) )
686
-			if ( strtoupper($row['Engine']) == $engine )
710
+		while ( $row = $this->fetchByAssoc($r) ) {
711
+					if ( strtoupper($row['Engine']) == $engine )
687 712
 				return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
713
+		}
688 714
 
689 715
 		return false;
690 716
 	}
@@ -712,18 +738,22 @@  discard block
 block discarded – undo
712 738
 	*/
713 739
 	public function createTableSQLParams($tablename, $fieldDefs, $indices, $engine = null)
714 740
 	{
715
-		if ( empty($engine) && isset($fieldDefs['engine']))
716
-			$engine = $fieldDefs['engine'];
717
-		if ( !$this->isEngineEnabled($engine) )
718
-			$engine = '';
741
+		if ( empty($engine) && isset($fieldDefs['engine'])) {
742
+					$engine = $fieldDefs['engine'];
743
+		}
744
+		if ( !$this->isEngineEnabled($engine) ) {
745
+					$engine = '';
746
+		}
719 747
 
720 748
 		$columns = $this->columnSQLRep($fieldDefs, false, $tablename);
721
-		if (empty($columns))
722
-			return false;
749
+		if (empty($columns)) {
750
+					return false;
751
+		}
723 752
 
724 753
 		$keys = $this->keysSQL($indices);
725
-		if (!empty($keys))
726
-			$keys = ",$keys";
754
+		if (!empty($keys)) {
755
+					$keys = ",$keys";
756
+		}
727 757
 
728 758
 		// cn: bug 9873 - module tables do not get created in utf8 with assoc collation
729 759
 		$collation = $this->getOption('collation');
@@ -732,8 +762,9 @@  discard block
 block discarded – undo
732 762
 		}
733 763
 		$sql = "CREATE TABLE $tablename ($columns $keys) CHARACTER SET utf8 COLLATE $collation";
734 764
 
735
-		if (!empty($engine))
736
-			$sql.= " ENGINE=$engine";
765
+		if (!empty($engine)) {
766
+					$sql.= " ENGINE=$engine";
767
+		}
737 768
 
738 769
 		return $sql;
739 770
 	}
@@ -762,13 +793,15 @@  discard block
 block discarded – undo
762 793
 
763 794
 		// bug 22338 - don't set a default value on text or blob fields
764 795
 		if ( isset($ref['default']) &&
765
-            in_array($ref['colBaseType'], array('text', 'blob', 'longtext', 'longblob')))
766
-			    $ref['default'] = '';
796
+            in_array($ref['colBaseType'], array('text', 'blob', 'longtext', 'longblob'))) {
797
+					    $ref['default'] = '';
798
+		}
767 799
 
768
-		if ( $return_as_array )
769
-			return $ref;
770
-		else
771
-			return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
800
+		if ( $return_as_array ) {
801
+					return $ref;
802
+		} else {
803
+					return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
804
+		}
772 805
 	}
773 806
 
774 807
 	/**
@@ -779,16 +812,18 @@  discard block
 block discarded – undo
779 812
 		$columns = array();
780 813
 		if ($this->isFieldArray($fieldDefs)){
781 814
 			foreach ($fieldDefs as $def){
782
-				if ($action == 'drop')
783
-					$columns[] = $def['name'];
784
-				else
785
-					$columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
815
+				if ($action == 'drop') {
816
+									$columns[] = $def['name'];
817
+				} else {
818
+									$columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
819
+				}
786 820
 			}
787 821
 		} else {
788
-			if ($action == 'drop')
789
-				$columns[] = $fieldDefs['name'];
790
-		else
791
-			$columns[] = $this->oneColumnSQLRep($fieldDefs);
822
+			if ($action == 'drop') {
823
+							$columns[] = $fieldDefs['name'];
824
+			} else {
825
+					$columns[] = $this->oneColumnSQLRep($fieldDefs);
826
+		}
792 827
 		}
793 828
 
794 829
 		return "ALTER TABLE $tablename $action COLUMN ".implode(",$action column ", $columns);
@@ -810,23 +845,27 @@  discard block
 block discarded – undo
810 845
 	{
811 846
 	// check if the passed value is an array of fields.
812 847
 	// if not, convert it into an array
813
-	if (!$this->isFieldArray($indices))
814
-		$indices[] = $indices;
848
+	if (!$this->isFieldArray($indices)) {
849
+			$indices[] = $indices;
850
+	}
815 851
 
816 852
 	$columns = array();
817 853
 	foreach ($indices as $index) {
818
-		if(!empty($index['db']) && $index['db'] != $this->dbType)
819
-			continue;
820
-		if (isset($index['source']) && $index['source'] != 'db')
821
-			continue;
854
+		if(!empty($index['db']) && $index['db'] != $this->dbType) {
855
+					continue;
856
+		}
857
+		if (isset($index['source']) && $index['source'] != 'db') {
858
+					continue;
859
+		}
822 860
 
823 861
 		$type = $index['type'];
824 862
 		$name = $index['name'];
825 863
 
826
-		if (is_array($index['fields']))
827
-			$fields = implode(", ", $index['fields']);
828
-		else
829
-			$fields = $index['fields'];
864
+		if (is_array($index['fields'])) {
865
+					$fields = implode(", ", $index['fields']);
866
+		} else {
867
+					$fields = $index['fields'];
868
+		}
830 869
 
831 870
 		switch ($type) {
832 871
 		case 'unique':
@@ -845,16 +884,18 @@  discard block
 block discarded – undo
845 884
 				* that this can easily be fixed by referring to db dictionary
846 885
 				* to find the correct primary field name
847 886
 				*/
848
-			if ( $alter_table )
849
-				$columns[] = " INDEX $name ($fields)";
850
-			else
851
-				$columns[] = " KEY $name ($fields)";
887
+			if ( $alter_table ) {
888
+							$columns[] = " INDEX $name ($fields)";
889
+			} else {
890
+							$columns[] = " KEY $name ($fields)";
891
+			}
852 892
 			break;
853 893
 		case 'fulltext':
854
-			if ($this->full_text_indexing_installed())
855
-				$columns[] = " FULLTEXT ($fields)";
856
-			else
857
-				$GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
894
+			if ($this->full_text_indexing_installed()) {
895
+							$columns[] = " FULLTEXT ($fields)";
896
+			} else {
897
+							$GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
898
+			}
858 899
 			break;
859 900
 		}
860 901
 	}
@@ -896,8 +937,9 @@  discard block
 block discarded – undo
896 937
 	{
897 938
 		$result = $this->query("SHOW TABLE STATUS LIKE '$table'");
898 939
 		$row = $this->fetchByAssoc($result);
899
-		if (!empty($row['Auto_increment']))
900
-			return $row['Auto_increment'];
940
+		if (!empty($row['Auto_increment'])) {
941
+					return $row['Auto_increment'];
942
+		}
901 943
 
902 944
 		return "";
903 945
 	}
@@ -915,8 +957,7 @@  discard block
 block discarded – undo
915 957
 			$index_type='index';
916 958
 			if ($row['Key_name'] =='PRIMARY') {
917 959
 				$index_type='primary';
918
-			}
919
-			elseif ( $row['Non_unique'] == '0' ) {
960
+			} elseif ( $row['Non_unique'] == '0' ) {
920 961
 				$index_type='unique';
921 962
 			}
922 963
 			$name = strtolower($row['Key_name']);
@@ -942,29 +983,33 @@  discard block
 block discarded – undo
942 983
 		case 'index':
943 984
 		case 'alternate_key':
944 985
 		case 'clustered':
945
-			if ($drop)
946
-				$sql = "ALTER TABLE {$table} DROP INDEX {$name} ";
947
-			else
948
-				$sql = "ALTER TABLE {$table} ADD INDEX {$name} ({$fields})";
986
+			if ($drop) {
987
+							$sql = "ALTER TABLE {$table} DROP INDEX {$name} ";
988
+			} else {
989
+							$sql = "ALTER TABLE {$table} ADD INDEX {$name} ({$fields})";
990
+			}
949 991
 			break;
950 992
 		// constraints as indices
951 993
 		case 'unique':
952
-			if ($drop)
953
-				$sql = "ALTER TABLE {$table} DROP INDEX $name";
954
-			else
955
-				$sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
994
+			if ($drop) {
995
+							$sql = "ALTER TABLE {$table} DROP INDEX $name";
996
+			} else {
997
+							$sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
998
+			}
956 999
 			break;
957 1000
 		case 'primary':
958
-			if ($drop)
959
-				$sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
960
-			else
961
-				$sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
1001
+			if ($drop) {
1002
+							$sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
1003
+			} else {
1004
+							$sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
1005
+			}
962 1006
 			break;
963 1007
 		case 'foreign':
964
-			if ($drop)
965
-				$sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
966
-			else
967
-				$sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignField']})";
1008
+			if ($drop) {
1009
+							$sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
1010
+			} else {
1011
+							$sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignField']})";
1012
+			}
968 1013
 			break;
969 1014
 		}
970 1015
 		return $sql;
@@ -1007,22 +1052,30 @@  discard block
 block discarded – undo
1007 1052
 			($fieldDef['dbType'] == 'text'
1008 1053
 				|| $fieldDef['dbType'] == 'blob'
1009 1054
 				|| $fieldDef['dbType'] == 'longtext'
1010
-				|| $fieldDef['dbType'] == 'longblob' ))
1011
-			unset($fieldDef['default']);
1012
-		if ($fieldDef['dbType'] == 'uint')
1013
-			$fieldDef['len'] = '10';
1014
-		if ($fieldDef['dbType'] == 'ulong')
1015
-			$fieldDef['len'] = '20';
1016
-		if ($fieldDef['dbType'] == 'bool')
1017
-			$fieldDef['type'] = 'tinyint';
1018
-		if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) )
1019
-			$fieldDef['default'] = '0';
1020
-		if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) )
1021
-			$fieldDef['len'] = '255';
1022
-		if ($fieldDef['dbType'] == 'uint')
1023
-			$fieldDef['len'] = '10';
1024
-		if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) )
1025
-			$fieldDef['len'] = '11';
1055
+				|| $fieldDef['dbType'] == 'longblob' )) {
1056
+					unset($fieldDef['default']);
1057
+		}
1058
+		if ($fieldDef['dbType'] == 'uint') {
1059
+					$fieldDef['len'] = '10';
1060
+		}
1061
+		if ($fieldDef['dbType'] == 'ulong') {
1062
+					$fieldDef['len'] = '20';
1063
+		}
1064
+		if ($fieldDef['dbType'] == 'bool') {
1065
+					$fieldDef['type'] = 'tinyint';
1066
+		}
1067
+		if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) ) {
1068
+					$fieldDef['default'] = '0';
1069
+		}
1070
+		if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) ) {
1071
+					$fieldDef['len'] = '255';
1072
+		}
1073
+		if ($fieldDef['dbType'] == 'uint') {
1074
+					$fieldDef['len'] = '10';
1075
+		}
1076
+		if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) ) {
1077
+					$fieldDef['len'] = '11';
1078
+		}
1026 1079
 
1027 1080
 		if($fieldDef['dbType'] == 'decimal') {
1028 1081
 			if(isset($fieldDef['len'])) {
@@ -1062,8 +1115,9 @@  discard block
 block discarded – undo
1062 1115
 		}
1063 1116
 		if (!empty($sql)) {
1064 1117
             $sql = "ALTER TABLE $tablename " . join(",", $sql) . ";";
1065
-			if($execute)
1066
-				$this->query($sql);
1118
+			if($execute) {
1119
+							$this->query($sql);
1120
+			}
1067 1121
 		} else {
1068 1122
 			$sql = '';
1069 1123
 		}
Please login to merge, or discard this patch.
include/database/DBManagerFactory.php 3 patches
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
                     }
81 81
                     break;
82 82
                 case "mssql":
83
-                  	if ( function_exists('sqlsrv_connect')
83
+                      if ( function_exists('sqlsrv_connect')
84 84
                                 && (empty($config['db_mssql_force_driver']) || $config['db_mssql_force_driver'] == 'sqlsrv' )) {
85 85
                         $my_db_manager = 'SqlsrvManager';
86 86
                     } elseif (self::isFreeTDS()
@@ -122,20 +122,20 @@  discard block
 block discarded – undo
122 122
     }
123 123
 
124 124
     /**
125
-	 * Returns a reference to the DB object for instance $instanceName, or the default
125
+     * Returns a reference to the DB object for instance $instanceName, or the default
126 126
      * instance if one is not specified
127 127
      *
128 128
      * @param  string $instanceName optional, name of the instance
129 129
      * @return object DBManager instance
130 130
      */
131
-	public static function getInstance($instanceName = '')
131
+    public static function getInstance($instanceName = '')
132 132
     {
133 133
         global $sugar_config;
134 134
         static $count = 0, $old_count = 0;
135 135
 
136 136
         //fall back to the default instance name
137 137
         if(empty($sugar_config['db'][$instanceName])){
138
-        	$instanceName = '';
138
+            $instanceName = '';
139 139
         }
140 140
         if(!isset(self::$instances[$instanceName])){
141 141
             $config = $sugar_config['dbconfig'];
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
     /**
249 249
      * Check if we have freeTDS driver installed
250 250
      * Invoked when connected to mssql. checks if we have freetds version of mssql library.
251
-	 * the response is put into a global variable.
251
+     * the response is put into a global variable.
252 252
      * @return bool
253 253
      */
254 254
     public static function isFreeTDS()
@@ -256,14 +256,14 @@  discard block
 block discarded – undo
256 256
         static $is_freetds = null;
257 257
 
258 258
         if($is_freetds === null) {
259
-    		ob_start();
260
-    		phpinfo(INFO_MODULES);
261
-    		$info=ob_get_contents();
262
-    		ob_end_clean();
259
+            ob_start();
260
+            phpinfo(INFO_MODULES);
261
+            $info=ob_get_contents();
262
+            ob_end_clean();
263 263
 
264
-    		$is_freetds = (strpos($info,'FreeTDS') !== false);
264
+            $is_freetds = (strpos($info,'FreeTDS') !== false);
265 265
         }
266 266
 
267 267
         return $is_freetds;
268
-     }
268
+        }
269 269
 }
270 270
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 3
 /*********************************************************************************
4 4
  * SugarCRM Community Edition is a customer relationship management program developed by
5 5
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
@@ -69,9 +69,9 @@  discard block
 block discarded – undo
69 69
     {
70 70
         global $sugar_config;
71 71
 
72
-        if(empty($config['db_manager'])) {
72
+        if (empty($config['db_manager'])) {
73 73
             // standard types
74
-            switch($type) {
74
+            switch ($type) {
75 75
                 case "mysql":
76 76
                     if (empty($sugar_config['mysqli_disabled']) && function_exists('mysqli_connect')) {
77 77
                         $my_db_manager = 'MysqliManager';
@@ -80,11 +80,11 @@  discard block
 block discarded – undo
80 80
                     }
81 81
                     break;
82 82
                 case "mssql":
83
-                  	if ( function_exists('sqlsrv_connect')
84
-                                && (empty($config['db_mssql_force_driver']) || $config['db_mssql_force_driver'] == 'sqlsrv' )) {
83
+                  	if (function_exists('sqlsrv_connect')
84
+                                && (empty($config['db_mssql_force_driver']) || $config['db_mssql_force_driver'] == 'sqlsrv')) {
85 85
                         $my_db_manager = 'SqlsrvManager';
86 86
                     } elseif (self::isFreeTDS()
87
-                                && (empty($config['db_mssql_force_driver']) || $config['db_mssql_force_driver'] == 'freetds' )) {
87
+                                && (empty($config['db_mssql_force_driver']) || $config['db_mssql_force_driver'] == 'freetds')) {
88 88
                         $my_db_manager = 'FreeTDSManager';
89 89
                     } else {
90 90
                         $my_db_manager = 'MssqlManager';
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
                     break;
93 93
                 default:
94 94
                     $my_db_manager = self::getManagerByType($type, false);
95
-                    if(empty($my_db_manager)) {
95
+                    if (empty($my_db_manager)) {
96 96
                         $GLOBALS['log']->fatal("unable to load DB manager for: $type");
97 97
                         sugar_die("Cannot load DB manager");
98 98
                     }
@@ -104,17 +104,17 @@  discard block
 block discarded – undo
104 104
         // sanitize the name
105 105
         $my_db_manager = preg_replace("/[^A-Za-z0-9_-]/", "", $my_db_manager);
106 106
 
107
-        if(!empty($config['db_manager_class'])){
107
+        if (!empty($config['db_manager_class'])) {
108 108
             $my_db_manager = $config['db_manager_class'];
109 109
         } else {
110
-            if(file_exists("custom/include/database/{$my_db_manager}.php")) {
110
+            if (file_exists("custom/include/database/{$my_db_manager}.php")) {
111 111
                 require_once("custom/include/database/{$my_db_manager}.php");
112 112
             } else {
113 113
                 require_once("include/database/{$my_db_manager}.php");
114 114
             }
115 115
         }
116 116
 
117
-        if(class_exists($my_db_manager)) {
117
+        if (class_exists($my_db_manager)) {
118 118
             return new $my_db_manager();
119 119
         } else {
120 120
             return null;
@@ -134,14 +134,14 @@  discard block
 block discarded – undo
134 134
         static $count = 0, $old_count = 0;
135 135
 
136 136
         //fall back to the default instance name
137
-        if(empty($sugar_config['db'][$instanceName])){
137
+        if (empty($sugar_config['db'][$instanceName])) {
138 138
         	$instanceName = '';
139 139
         }
140
-        if(!isset(self::$instances[$instanceName])){
140
+        if (!isset(self::$instances[$instanceName])) {
141 141
             $config = $sugar_config['dbconfig'];
142 142
             $count++;
143 143
                 self::$instances[$instanceName] = self::getTypeInstance($config['db_type'], $config);
144
-                if(!empty($sugar_config['dbconfigoption'])) {
144
+                if (!empty($sugar_config['dbconfigoption'])) {
145 145
                     self::$instances[$instanceName]->setOptions($sugar_config['dbconfigoption']);
146 146
                 }
147 147
                 self::$instances[$instanceName]->connect($config, true);
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
      */
160 160
     public static function disconnectAll()
161 161
     {
162
-        foreach(self::$instances as $instance) {
162
+        foreach (self::$instances as $instance) {
163 163
             $instance->disconnect();
164 164
         }
165 165
         self::$instances = array();
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
     public static function getManagerByType($type, $validate = true)
178 178
     {
179 179
         $drivers = self::getDbDrivers($validate);
180
-        if(!empty($drivers[$type])) {
180
+        if (!empty($drivers[$type])) {
181 181
             return get_class($drivers[$type]);
182 182
         }
183 183
         return false;
@@ -191,19 +191,19 @@  discard block
 block discarded – undo
191 191
      */
192 192
     protected static function scanDriverDir($dir, &$drivers, $validate = true)
193 193
     {
194
-        if(!is_dir($dir)) return;
194
+        if (!is_dir($dir)) return;
195 195
         $scandir = opendir($dir);
196
-        if($scandir === false) return;
197
-        while(($name = readdir($scandir)) !== false) {
198
-            if(substr($name, -11) != "Manager.php") continue;
199
-            if($name == "DBManager.php") continue;
196
+        if ($scandir === false) return;
197
+        while (($name = readdir($scandir)) !== false) {
198
+            if (substr($name, -11) != "Manager.php") continue;
199
+            if ($name == "DBManager.php") continue;
200 200
             require_once("$dir/$name");
201 201
             $classname = substr($name, 0, -4);
202
-            if(!class_exists($classname)) continue;
202
+            if (!class_exists($classname)) continue;
203 203
             $driver = new $classname;
204
-            if(!$validate || $driver->valid()) {
205
-                if(empty($drivers[$driver->dbType])) {
206
-                    $drivers[$driver->dbType]  = array();
204
+            if (!$validate || $driver->valid()) {
205
+                if (empty($drivers[$driver->dbType])) {
206
+                    $drivers[$driver->dbType] = array();
207 207
                 }
208 208
                 $drivers[$driver->dbType][] = $driver;
209 209
             }
@@ -235,9 +235,9 @@  discard block
 block discarded – undo
235 235
         self::scanDriverDir("custom/include/database", $drivers, $validate);
236 236
 
237 237
         $result = array();
238
-        foreach($drivers as $type => $tdrivers) {
239
-            if(empty($tdrivers)) continue;
240
-            if(count($tdrivers) > 1) {
238
+        foreach ($drivers as $type => $tdrivers) {
239
+            if (empty($tdrivers)) continue;
240
+            if (count($tdrivers) > 1) {
241 241
                 usort($tdrivers, array(__CLASS__, "_compareDrivers"));
242 242
             }
243 243
             $result[$type] = $tdrivers[0];
@@ -255,13 +255,13 @@  discard block
 block discarded – undo
255 255
     {
256 256
         static $is_freetds = null;
257 257
 
258
-        if($is_freetds === null) {
258
+        if ($is_freetds === null) {
259 259
     		ob_start();
260 260
     		phpinfo(INFO_MODULES);
261
-    		$info=ob_get_contents();
261
+    		$info = ob_get_contents();
262 262
     		ob_end_clean();
263 263
 
264
-    		$is_freetds = (strpos($info,'FreeTDS') !== false);
264
+    		$is_freetds = (strpos($info, 'FreeTDS') !== false);
265 265
         }
266 266
 
267 267
         return $is_freetds;
Please login to merge, or discard this patch.
Braces   +21 added lines, -7 removed lines patch added patch discarded remove patch
@@ -1,5 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if(!defined('sugarEntry') || !sugarEntry) {
3
+    die('Not A Valid Entry Point');
4
+}
3 5
 /*********************************************************************************
4 6
  * SugarCRM Community Edition is a customer relationship management program developed by
5 7
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
@@ -191,15 +193,25 @@  discard block
 block discarded – undo
191 193
      */
192 194
     protected static function scanDriverDir($dir, &$drivers, $validate = true)
193 195
     {
194
-        if(!is_dir($dir)) return;
196
+        if(!is_dir($dir)) {
197
+            return;
198
+        }
195 199
         $scandir = opendir($dir);
196
-        if($scandir === false) return;
200
+        if($scandir === false) {
201
+            return;
202
+        }
197 203
         while(($name = readdir($scandir)) !== false) {
198
-            if(substr($name, -11) != "Manager.php") continue;
199
-            if($name == "DBManager.php") continue;
204
+            if(substr($name, -11) != "Manager.php") {
205
+                continue;
206
+            }
207
+            if($name == "DBManager.php") {
208
+                continue;
209
+            }
200 210
             require_once("$dir/$name");
201 211
             $classname = substr($name, 0, -4);
202
-            if(!class_exists($classname)) continue;
212
+            if(!class_exists($classname)) {
213
+                continue;
214
+            }
203 215
             $driver = new $classname;
204 216
             if(!$validate || $driver->valid()) {
205 217
                 if(empty($drivers[$driver->dbType])) {
@@ -236,7 +248,9 @@  discard block
 block discarded – undo
236 248
 
237 249
         $result = array();
238 250
         foreach($drivers as $type => $tdrivers) {
239
-            if(empty($tdrivers)) continue;
251
+            if(empty($tdrivers)) {
252
+                continue;
253
+            }
240 254
             if(count($tdrivers) > 1) {
241 255
                 usort($tdrivers, array(__CLASS__, "_compareDrivers"));
242 256
             }
Please login to merge, or discard this patch.
include/connectors/ConnectorFactory.php 3 patches
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -44,45 +44,45 @@
 block discarded – undo
44 44
  */
45 45
 class ConnectorFactory{
46 46
 
47
-	static $source_map = array();
47
+    static $source_map = array();
48 48
 
49
-	public static function getInstance($source_name){
50
-		if(empty(self::$source_map[$source_name])) {
51
-			require_once('include/connectors/sources/SourceFactory.php');
52
-			require_once('include/connectors/component.php');
53
-			$source = SourceFactory::getSource($source_name);
54
-			$component = new component();
55
-			$component->setSource($source);
56
-			$component->init();
57
-			self::$source_map[$source_name] = $component;
58
-		}
59
-		return self::$source_map[$source_name];
60
-	}
49
+    public static function getInstance($source_name){
50
+        if(empty(self::$source_map[$source_name])) {
51
+            require_once('include/connectors/sources/SourceFactory.php');
52
+            require_once('include/connectors/component.php');
53
+            $source = SourceFactory::getSource($source_name);
54
+            $component = new component();
55
+            $component->setSource($source);
56
+            $component->init();
57
+            self::$source_map[$source_name] = $component;
58
+        }
59
+        return self::$source_map[$source_name];
60
+    }
61 61
 
62
-	/**
63
-	 * Split the class name by _ and go through the class name
64
-	 * which represents the inheritance structure to load up all required parents.
65
-	 * @param string $class the root class we want to load.
66
-	 */
67
-	public static function load($class, $type){
68
-		self::loadClass($class, $type);
69
-	}
62
+    /**
63
+     * Split the class name by _ and go through the class name
64
+     * which represents the inheritance structure to load up all required parents.
65
+     * @param string $class the root class we want to load.
66
+     */
67
+    public static function load($class, $type){
68
+        self::loadClass($class, $type);
69
+    }
70 70
 
71
-	/**
72
-	 * include a source class file.
73
-	 * @param string $class a class file to include.
74
-	 */
75
-	public static function loadClass($class, $type){
76
-		$dir = str_replace('_','/',$class);
77
-		$parts = explode("/", $dir);
78
-		$file = $parts[count($parts)-1] . '.php';
79
-		if(file_exists("custom/modules/Connectors/connectors/{$type}/{$dir}/$file")){
80
-			require_once("custom/modules/Connectors/connectors/{$type}/{$dir}/$file");
81
-		} else if(file_exists("modules/Connectors/connectors/{$type}/{$dir}/$file")) {
82
-			require_once("modules/Connectors/connectors/{$type}/{$dir}/$file");
83
-		} else if(file_exists("connectors/{$type}/{$dir}/$file")) {
84
-			require_once("connectors/{$type}/{$dir}/$file");
85
-		}
86
-	}
71
+    /**
72
+     * include a source class file.
73
+     * @param string $class a class file to include.
74
+     */
75
+    public static function loadClass($class, $type){
76
+        $dir = str_replace('_','/',$class);
77
+        $parts = explode("/", $dir);
78
+        $file = $parts[count($parts)-1] . '.php';
79
+        if(file_exists("custom/modules/Connectors/connectors/{$type}/{$dir}/$file")){
80
+            require_once("custom/modules/Connectors/connectors/{$type}/{$dir}/$file");
81
+        } else if(file_exists("modules/Connectors/connectors/{$type}/{$dir}/$file")) {
82
+            require_once("modules/Connectors/connectors/{$type}/{$dir}/$file");
83
+        } else if(file_exists("connectors/{$type}/{$dir}/$file")) {
84
+            require_once("connectors/{$type}/{$dir}/$file");
85
+        }
86
+    }
87 87
 }
88 88
 ?>
89 89
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 3
 /*********************************************************************************
4 4
  * SugarCRM Community Edition is a customer relationship management program developed by
5 5
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
@@ -42,12 +42,12 @@  discard block
 block discarded – undo
42 42
  * Connector factory
43 43
  * @api
44 44
  */
45
-class ConnectorFactory{
45
+class ConnectorFactory {
46 46
 
47 47
 	static $source_map = array();
48 48
 
49
-	public static function getInstance($source_name){
50
-		if(empty(self::$source_map[$source_name])) {
49
+	public static function getInstance($source_name) {
50
+		if (empty(self::$source_map[$source_name])) {
51 51
 			require_once('include/connectors/sources/SourceFactory.php');
52 52
 			require_once('include/connectors/component.php');
53 53
 			$source = SourceFactory::getSource($source_name);
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
 	 * which represents the inheritance structure to load up all required parents.
65 65
 	 * @param string $class the root class we want to load.
66 66
 	 */
67
-	public static function load($class, $type){
67
+	public static function load($class, $type) {
68 68
 		self::loadClass($class, $type);
69 69
 	}
70 70
 
@@ -72,15 +72,15 @@  discard block
 block discarded – undo
72 72
 	 * include a source class file.
73 73
 	 * @param string $class a class file to include.
74 74
 	 */
75
-	public static function loadClass($class, $type){
76
-		$dir = str_replace('_','/',$class);
75
+	public static function loadClass($class, $type) {
76
+		$dir = str_replace('_', '/', $class);
77 77
 		$parts = explode("/", $dir);
78
-		$file = $parts[count($parts)-1] . '.php';
79
-		if(file_exists("custom/modules/Connectors/connectors/{$type}/{$dir}/$file")){
78
+		$file = $parts[count($parts) - 1].'.php';
79
+		if (file_exists("custom/modules/Connectors/connectors/{$type}/{$dir}/$file")) {
80 80
 			require_once("custom/modules/Connectors/connectors/{$type}/{$dir}/$file");
81
-		} else if(file_exists("modules/Connectors/connectors/{$type}/{$dir}/$file")) {
81
+		} else if (file_exists("modules/Connectors/connectors/{$type}/{$dir}/$file")) {
82 82
 			require_once("modules/Connectors/connectors/{$type}/{$dir}/$file");
83
-		} else if(file_exists("connectors/{$type}/{$dir}/$file")) {
83
+		} else if (file_exists("connectors/{$type}/{$dir}/$file")) {
84 84
 			require_once("connectors/{$type}/{$dir}/$file");
85 85
 		}
86 86
 	}
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,5 +1,7 @@
 block discarded – undo
1 1
 <?php
2
-if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if(!defined('sugarEntry') || !sugarEntry) {
3
+    die('Not A Valid Entry Point');
4
+}
3 5
 /*********************************************************************************
4 6
  * SugarCRM Community Edition is a customer relationship management program developed by
5 7
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
Please login to merge, or discard this patch.
include/MVC/Controller/ControllerFactory.php 3 patches
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -44,43 +44,43 @@
 block discarded – undo
44 44
  */
45 45
 class ControllerFactory
46 46
 {
47
-	/**
48
-	 * Obtain an instance of the correct controller.
49
-	 *
50
-	 * @return an instance of SugarController
51
-	 */
52
-	static function getController($module){
53
-		$class = ucfirst($module).'Controller';
54
-		$customClass = 'Custom' . $class;
55
-		if(file_exists('custom/modules/'.$module.'/controller.php')){
56
-			$customClass = 'Custom' . $class;
57
-			require_once('custom/modules/'.$module.'/controller.php');
58
-			if(class_exists($customClass)){
59
-				$controller = new $customClass();
60
-			}else if(class_exists($class)){
61
-				$controller = new $class();
62
-			}
63
-		}elseif(file_exists('modules/'.$module.'/controller.php')){
64
-			require_once('modules/'.$module.'/controller.php');
65
-			if(class_exists($customClass)){
66
-				$controller = new $customClass();
67
-			}else if(class_exists($class)){
68
-				$controller = new $class();
69
-			}
70
-		}else{
71
-			if(file_exists('custom/include/MVC/Controller/SugarController.php')){
72
-				require_once('custom/include/MVC/Controller/SugarController.php');
73
-			}
74
-			if(class_exists('CustomSugarController')){
75
-				$controller = new CustomSugarController();
76
-			}else{
77
-			$controller = new SugarController();
78
-			}
79
-		}
80
-		//setup the controller
81
-		$controller->setup($module);
82
-		return $controller;
83
-	}
47
+    /**
48
+     * Obtain an instance of the correct controller.
49
+     *
50
+     * @return an instance of SugarController
51
+     */
52
+    static function getController($module){
53
+        $class = ucfirst($module).'Controller';
54
+        $customClass = 'Custom' . $class;
55
+        if(file_exists('custom/modules/'.$module.'/controller.php')){
56
+            $customClass = 'Custom' . $class;
57
+            require_once('custom/modules/'.$module.'/controller.php');
58
+            if(class_exists($customClass)){
59
+                $controller = new $customClass();
60
+            }else if(class_exists($class)){
61
+                $controller = new $class();
62
+            }
63
+        }elseif(file_exists('modules/'.$module.'/controller.php')){
64
+            require_once('modules/'.$module.'/controller.php');
65
+            if(class_exists($customClass)){
66
+                $controller = new $customClass();
67
+            }else if(class_exists($class)){
68
+                $controller = new $class();
69
+            }
70
+        }else{
71
+            if(file_exists('custom/include/MVC/Controller/SugarController.php')){
72
+                require_once('custom/include/MVC/Controller/SugarController.php');
73
+            }
74
+            if(class_exists('CustomSugarController')){
75
+                $controller = new CustomSugarController();
76
+            }else{
77
+            $controller = new SugarController();
78
+            }
79
+        }
80
+        //setup the controller
81
+        $controller->setup($module);
82
+        return $controller;
83
+    }
84 84
 
85 85
 }
86 86
 ?>
87 87
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -49,31 +49,31 @@
 block discarded – undo
49 49
 	 *
50 50
 	 * @return an instance of SugarController
51 51
 	 */
52
-	static function getController($module){
52
+	static function getController($module) {
53 53
 		$class = ucfirst($module).'Controller';
54
-		$customClass = 'Custom' . $class;
55
-		if(file_exists('custom/modules/'.$module.'/controller.php')){
56
-			$customClass = 'Custom' . $class;
54
+		$customClass = 'Custom'.$class;
55
+		if (file_exists('custom/modules/'.$module.'/controller.php')) {
56
+			$customClass = 'Custom'.$class;
57 57
 			require_once('custom/modules/'.$module.'/controller.php');
58
-			if(class_exists($customClass)){
58
+			if (class_exists($customClass)) {
59 59
 				$controller = new $customClass();
60
-			}else if(class_exists($class)){
60
+			} else if (class_exists($class)) {
61 61
 				$controller = new $class();
62 62
 			}
63
-		}elseif(file_exists('modules/'.$module.'/controller.php')){
63
+		}elseif (file_exists('modules/'.$module.'/controller.php')) {
64 64
 			require_once('modules/'.$module.'/controller.php');
65
-			if(class_exists($customClass)){
65
+			if (class_exists($customClass)) {
66 66
 				$controller = new $customClass();
67
-			}else if(class_exists($class)){
67
+			} else if (class_exists($class)) {
68 68
 				$controller = new $class();
69 69
 			}
70
-		}else{
71
-			if(file_exists('custom/include/MVC/Controller/SugarController.php')){
70
+		} else {
71
+			if (file_exists('custom/include/MVC/Controller/SugarController.php')) {
72 72
 				require_once('custom/include/MVC/Controller/SugarController.php');
73 73
 			}
74
-			if(class_exists('CustomSugarController')){
74
+			if (class_exists('CustomSugarController')) {
75 75
 				$controller = new CustomSugarController();
76
-			}else{
76
+			} else {
77 77
 			$controller = new SugarController();
78 78
 			}
79 79
 		}
Please login to merge, or discard this patch.
Braces   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -57,23 +57,23 @@
 block discarded – undo
57 57
 			require_once('custom/modules/'.$module.'/controller.php');
58 58
 			if(class_exists($customClass)){
59 59
 				$controller = new $customClass();
60
-			}else if(class_exists($class)){
60
+			} else if(class_exists($class)){
61 61
 				$controller = new $class();
62 62
 			}
63
-		}elseif(file_exists('modules/'.$module.'/controller.php')){
63
+		} elseif(file_exists('modules/'.$module.'/controller.php')){
64 64
 			require_once('modules/'.$module.'/controller.php');
65 65
 			if(class_exists($customClass)){
66 66
 				$controller = new $customClass();
67
-			}else if(class_exists($class)){
67
+			} else if(class_exists($class)){
68 68
 				$controller = new $class();
69 69
 			}
70
-		}else{
70
+		} else{
71 71
 			if(file_exists('custom/include/MVC/Controller/SugarController.php')){
72 72
 				require_once('custom/include/MVC/Controller/SugarController.php');
73 73
 			}
74 74
 			if(class_exists('CustomSugarController')){
75 75
 				$controller = new CustomSugarController();
76
-			}else{
76
+			} else{
77 77
 			$controller = new SugarController();
78 78
 			}
79 79
 		}
Please login to merge, or discard this patch.
include/MVC/Controller/action_view_map.php 2 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -43,7 +43,7 @@
 block discarded – undo
43 43
  * To change the template for this generated file go to
44 44
  * Window - Preferences - PHPeclipse - PHP - Code Templates
45 45
  */
46
- //format '<action_name>' => '<view_name>'
46
+    //format '<action_name>' => '<view_name>'
47 47
 $action_view_map['multieditview']= 'multiedit';
48 48
 $action_view_map['detailview']= 'detail';
49 49
 $action_view_map['editview']= 'edit';
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -44,21 +44,21 @@
 block discarded – undo
44 44
  * Window - Preferences - PHPeclipse - PHP - Code Templates
45 45
  */
46 46
  //format '<action_name>' => '<view_name>'
47
-$action_view_map['multieditview']= 'multiedit';
48
-$action_view_map['detailview']= 'detail';
49
-$action_view_map['editview']= 'edit';
50
-$action_view_map['listview']= 'list';
51
-$action_view_map['popup']= 'popup';
52
-$action_view_map['vcard']= 'vcard';
53
-$action_view_map['importvcard']= 'importvcard';
54
-$action_view_map['importvcardsave']= 'importvcardsave';
55
-$action_view_map['modulelistmenu']= 'modulelistmenu';
56
-$action_view_map['favorites']= 'favorites';
57
-$action_view_map['ajaxui']= 'ajaxui';
58
-$action_view_map['noaccess']= 'noaccess';
47
+$action_view_map['multieditview'] = 'multiedit';
48
+$action_view_map['detailview'] = 'detail';
49
+$action_view_map['editview'] = 'edit';
50
+$action_view_map['listview'] = 'list';
51
+$action_view_map['popup'] = 'popup';
52
+$action_view_map['vcard'] = 'vcard';
53
+$action_view_map['importvcard'] = 'importvcard';
54
+$action_view_map['importvcardsave'] = 'importvcardsave';
55
+$action_view_map['modulelistmenu'] = 'modulelistmenu';
56
+$action_view_map['favorites'] = 'favorites';
57
+$action_view_map['ajaxui'] = 'ajaxui';
58
+$action_view_map['noaccess'] = 'noaccess';
59 59
 
60 60
 // SugarPDF
61
-$action_view_map['sugarpdf']= 'sugarpdf';
61
+$action_view_map['sugarpdf'] = 'sugarpdf';
62 62
 $action_view_map['dc'] = 'dc';
63 63
 $action_view_map['dcajax'] = 'dcajax';
64 64
 $action_view_map['quick'] = 'quick';
Please login to merge, or discard this patch.
include/MVC/Controller/file_access_control_map.php 3 patches
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -46,29 +46,29 @@
 block discarded – undo
46 46
  * Contributor(s): ______________________________________..
47 47
  ********************************************************************************/
48 48
 $file_access_control_map = array(
49
-	'modules' => array(
50
-		'administration' => array(
51
-			'actions' => array(
52
-				'backups',
53
-				'updater',
54
-			),
55
-			'links'	=> array(
56
-				'update',
57
-				'backup_management',
58
-				'upgrade_wizard',
59
-				'moduleBuilder',
60
-			),
61
-		),
62
-		'upgradewizard' => array(
63
-				'actions' => array(
64
-					'index',
65
-				),
66
-		),
67
-		'modulebuilder' => array(
68
-				'actions' => array(
69
-					'index' => array('params' => array('type' => array('mb'))),
70
-				),
71
-		),
72
-	)
49
+    'modules' => array(
50
+        'administration' => array(
51
+            'actions' => array(
52
+                'backups',
53
+                'updater',
54
+            ),
55
+            'links'	=> array(
56
+                'update',
57
+                'backup_management',
58
+                'upgrade_wizard',
59
+                'moduleBuilder',
60
+            ),
61
+        ),
62
+        'upgradewizard' => array(
63
+                'actions' => array(
64
+                    'index',
65
+                ),
66
+        ),
67
+        'modulebuilder' => array(
68
+                'actions' => array(
69
+                    'index' => array('params' => array('type' => array('mb'))),
70
+                ),
71
+        ),
72
+    )
73 73
 );
74 74
 ?>
75 75
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@
 block discarded – undo
1 1
 <?php
2
-if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 3
 /*********************************************************************************
4 4
  * SugarCRM Community Edition is a customer relationship management program developed by
5 5
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,5 +1,7 @@
 block discarded – undo
1 1
 <?php
2
-if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if(!defined('sugarEntry') || !sugarEntry) {
3
+    die('Not A Valid Entry Point');
4
+}
3 5
 /*********************************************************************************
4 6
  * SugarCRM Community Edition is a customer relationship management program developed by
5 7
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
Please login to merge, or discard this patch.