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