Completed
Push — develop ( 0c0e51 )
by Adam
26:01 queued 12:43
created
include/SugarObjects/templates/basic/vardefs.php 2 patches
Indentation   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -39,141 +39,141 @@  discard block
 block discarded – undo
39 39
 
40 40
 $vardefs = array(  
41 41
 'fields' => array (
42
-	  'id' =>
43
-	  array (
44
-	    'name' => 'id',
45
-	    'vname' => 'LBL_ID',
46
-	    'type' => 'id',
47
-	    'required'=>true,
48
-	    'reportable'=>true,
49
-	    'comment' => 'Unique identifier',
50
-		'inline_edit' => false,
51
-	  ),
52
-	  'name'=>
53
-	    array(
54
-	    'name'=>'name',
55
-	    'vname'=> 'LBL_NAME',
56
-	    'type'=>'name',
57
-	    'link' => true, // bug 39288 
58
-		'dbType' => 'varchar',
59
-	    'len'=>255,
42
+        'id' =>
43
+        array (
44
+        'name' => 'id',
45
+        'vname' => 'LBL_ID',
46
+        'type' => 'id',
47
+        'required'=>true,
48
+        'reportable'=>true,
49
+        'comment' => 'Unique identifier',
50
+        'inline_edit' => false,
51
+        ),
52
+        'name'=>
53
+        array(
54
+        'name'=>'name',
55
+        'vname'=> 'LBL_NAME',
56
+        'type'=>'name',
57
+        'link' => true, // bug 39288 
58
+        'dbType' => 'varchar',
59
+        'len'=>255,
60 60
         'unified_search' => true,
61 61
         'full_text_search' => array('boost' => 3),
62 62
         'required'=>true,
63
-		'importable' => 'required',
63
+        'importable' => 'required',
64 64
         'duplicate_merge' => 'enabled',
65 65
         //'duplicate_merge_dom_value' => '3',
66 66
         'merge_filter' => 'selected',
67
-	    ),
68
-	  'date_entered' =>
69
-	  array (
70
-	    'name' => 'date_entered',
71
-	    'vname' => 'LBL_DATE_ENTERED',
72
-	    'type' => 'datetime',
73
-	    'group'=>'created_by_name',
74
-	    'comment' => 'Date record created',
75
-	    'enable_range_search' => true,
76
-	  	'options' => 'date_range_search_dom',
77
-		'inline_edit' => false,
78
-	  ),
79
-	  'date_modified' =>
80
-	  array (
81
-	    'name' => 'date_modified',
82
-	    'vname' => 'LBL_DATE_MODIFIED',
83
-	    'type' => 'datetime',
84
-	    'group'=>'modified_by_name',
85
-	    'comment' => 'Date record last modified',
86
-	    'enable_range_search' => true,
87
-	    'options' => 'date_range_search_dom',
88
-		'inline_edit' => false,
89
-	  ),
90
-		'modified_user_id' =>
91
-	  array (
92
-	    'name' => 'modified_user_id',
93
-	    'rname' => 'user_name',
94
-	    'id_name' => 'modified_user_id',
95
-	    'vname' => 'LBL_MODIFIED',
96
-	    'type' => 'assigned_user_name',
97
-	    'table' => 'users',
98
-	    'isnull' => 'false',
99
-	     'group'=>'modified_by_name',
100
-	    'dbType' => 'id',
101
-	    'reportable'=>true,
102
-	    'comment' => 'User who last modified record',
67
+        ),
68
+        'date_entered' =>
69
+        array (
70
+        'name' => 'date_entered',
71
+        'vname' => 'LBL_DATE_ENTERED',
72
+        'type' => 'datetime',
73
+        'group'=>'created_by_name',
74
+        'comment' => 'Date record created',
75
+        'enable_range_search' => true,
76
+            'options' => 'date_range_search_dom',
77
+        'inline_edit' => false,
78
+        ),
79
+        'date_modified' =>
80
+        array (
81
+        'name' => 'date_modified',
82
+        'vname' => 'LBL_DATE_MODIFIED',
83
+        'type' => 'datetime',
84
+        'group'=>'modified_by_name',
85
+        'comment' => 'Date record last modified',
86
+        'enable_range_search' => true,
87
+        'options' => 'date_range_search_dom',
88
+        'inline_edit' => false,
89
+        ),
90
+        'modified_user_id' =>
91
+        array (
92
+        'name' => 'modified_user_id',
93
+        'rname' => 'user_name',
94
+        'id_name' => 'modified_user_id',
95
+        'vname' => 'LBL_MODIFIED',
96
+        'type' => 'assigned_user_name',
97
+        'table' => 'users',
98
+        'isnull' => 'false',
99
+            'group'=>'modified_by_name',
100
+        'dbType' => 'id',
101
+        'reportable'=>true,
102
+        'comment' => 'User who last modified record',
103 103
         'massupdate' => false,
104
-		'inline_edit' => false,
105
-	  ),
106
-	  'modified_by_name' => 
107
-	  array (
108
-	    'name' => 'modified_by_name',
109
-	    'vname' => 'LBL_MODIFIED_NAME',
110
-	    'type' => 'relate',
111
-	    'reportable'=>false,
112
-	    'source'=>'non-db',
113
-	    'rname'=>'user_name',
114
-	    'table' => 'users',
115
-	    'id_name' => 'modified_user_id',
116
-	    'module'=>'Users',
117
-	    'link'=>'modified_user_link',
118
-	    'duplicate_merge'=>'disabled',
104
+        'inline_edit' => false,
105
+        ),
106
+        'modified_by_name' => 
107
+        array (
108
+        'name' => 'modified_by_name',
109
+        'vname' => 'LBL_MODIFIED_NAME',
110
+        'type' => 'relate',
111
+        'reportable'=>false,
112
+        'source'=>'non-db',
113
+        'rname'=>'user_name',
114
+        'table' => 'users',
115
+        'id_name' => 'modified_user_id',
116
+        'module'=>'Users',
117
+        'link'=>'modified_user_link',
118
+        'duplicate_merge'=>'disabled',
119 119
         'massupdate' => false,
120
-		'inline_edit' => false,
121
-	  ),  
122
-	  'created_by' =>
123
-	  array (
124
-	    'name' => 'created_by',
125
-	    'rname' => 'user_name',
126
-	    'id_name' => 'modified_user_id',
127
-	    'vname' => 'LBL_CREATED',
128
-	    'type' => 'assigned_user_name',
129
-	    'table' => 'users',
130
-	    'isnull' => 'false',
131
-	    'dbType' => 'id',
132
-	    'group'=>'created_by_name',
133
-	    'comment' => 'User who created record',
120
+        'inline_edit' => false,
121
+        ),  
122
+        'created_by' =>
123
+        array (
124
+        'name' => 'created_by',
125
+        'rname' => 'user_name',
126
+        'id_name' => 'modified_user_id',
127
+        'vname' => 'LBL_CREATED',
128
+        'type' => 'assigned_user_name',
129
+        'table' => 'users',
130
+        'isnull' => 'false',
131
+        'dbType' => 'id',
132
+        'group'=>'created_by_name',
133
+        'comment' => 'User who created record',
134 134
         'massupdate' => false,
135
-		'inline_edit' => false,
136
-	  ),
137
-	  'created_by_name' =>
138
-	  array (
139
-	    'name' => 'created_by_name',
140
-		'vname' => 'LBL_CREATED',
141
-		'type' => 'relate',
142
-		'reportable'=>false,
143
-	    'link' => 'created_by_link',
144
-	    'rname' => 'user_name',
145
-		'source'=>'non-db',
146
-		'table' => 'users',
147
-		'id_name' => 'created_by',
148
-		'module'=>'Users',
149
-		'duplicate_merge'=>'disabled',
135
+        'inline_edit' => false,
136
+        ),
137
+        'created_by_name' =>
138
+        array (
139
+        'name' => 'created_by_name',
140
+        'vname' => 'LBL_CREATED',
141
+        'type' => 'relate',
142
+        'reportable'=>false,
143
+        'link' => 'created_by_link',
144
+        'rname' => 'user_name',
145
+        'source'=>'non-db',
146
+        'table' => 'users',
147
+        'id_name' => 'created_by',
148
+        'module'=>'Users',
149
+        'duplicate_merge'=>'disabled',
150 150
         'importable' => 'false',
151 151
         'massupdate' => false,
152
-		'inline_edit' => false,
153
-	),
154
-	  'description' =>
155
-	  array (
156
-	    'name' => 'description',
157
-	    'vname' => 'LBL_DESCRIPTION',
158
-	    'type' => 'text',
159
-	    'comment' => 'Full text of the note',
160
-	    'rows' => 6,
161
-	    'cols' => 80,
162
-	  ),
163
-	  'deleted' =>
164
-	  array (
165
-	    'name' => 'deleted',
166
-	    'vname' => 'LBL_DELETED',
167
-	    'type' => 'bool',
168
-	    'default' => '0',
169
-	    'reportable'=>false,
170
-	    'comment' => 'Record deletion indicator'
171
-	  ),
152
+        'inline_edit' => false,
153
+    ),
154
+        'description' =>
155
+        array (
156
+        'name' => 'description',
157
+        'vname' => 'LBL_DESCRIPTION',
158
+        'type' => 'text',
159
+        'comment' => 'Full text of the note',
160
+        'rows' => 6,
161
+        'cols' => 80,
162
+        ),
163
+        'deleted' =>
164
+        array (
165
+        'name' => 'deleted',
166
+        'vname' => 'LBL_DELETED',
167
+        'type' => 'bool',
168
+        'default' => '0',
169
+        'reportable'=>false,
170
+        'comment' => 'Record deletion indicator'
171
+        ),
172 172
 	    
173 173
 /////////////////RELATIONSHIP LINKS////////////////////////////
174
-	  'created_by_link' =>
175
-  array (
176
-     'name' => 'created_by_link',
174
+        'created_by_link' =>
175
+    array (
176
+        'name' => 'created_by_link',
177 177
     'type' => 'link',
178 178
     'relationship' => strtolower($module) . '_created_by',
179 179
     'vname' => 'LBL_CREATED_USER',
@@ -181,9 +181,9 @@  discard block
 block discarded – undo
181 181
     'module'=>'Users',
182 182
     'bean_name'=>'User',
183 183
     'source'=>'non-db',
184
-  ),
185
-  'modified_user_link' =>
186
-  array (
184
+    ),
185
+    'modified_user_link' =>
186
+    array (
187 187
         'name' => 'modified_user_link',
188 188
     'type' => 'link',
189 189
     'relationship' => strtolower($module). '_modified_user',
@@ -192,21 +192,21 @@  discard block
 block discarded – undo
192 192
     'module'=>'Users',
193 193
     'bean_name'=>'User',
194 194
     'source'=>'non-db',
195
-  ),
195
+    ),
196 196
 
197 197
 ),
198 198
 'indices' => array (
199
-       'id'=>array('name' =>strtolower($module).'pk', 'type' =>'primary', 'fields'=>array('id')),
200
-       ),
199
+        'id'=>array('name' =>strtolower($module).'pk', 'type' =>'primary', 'fields'=>array('id')),
200
+        ),
201 201
 'relationships'=>array(
202
-	strtolower($module).'_modified_user' =>
203
-   array('lhs_module'=> 'Users', 'lhs_table'=> 'users', 'lhs_key' => 'id',
204
-   'rhs_module'=> $module, 'rhs_table'=> strtolower($module), 'rhs_key' => 'modified_user_id',
205
-   'relationship_type'=>'one-to-many')
206
-   ,strtolower($module).'_created_by' =>
207
-   array('lhs_module'=> 'Users', 'lhs_table'=> 'users', 'lhs_key' => 'id',
208
-   'rhs_module'=> $module, 'rhs_table'=> strtolower($module), 'rhs_key' => 'created_by',
209
-   'relationship_type'=>'one-to-many')
202
+    strtolower($module).'_modified_user' =>
203
+    array('lhs_module'=> 'Users', 'lhs_table'=> 'users', 'lhs_key' => 'id',
204
+    'rhs_module'=> $module, 'rhs_table'=> strtolower($module), 'rhs_key' => 'modified_user_id',
205
+    'relationship_type'=>'one-to-many')
206
+    ,strtolower($module).'_created_by' =>
207
+    array('lhs_module'=> 'Users', 'lhs_table'=> 'users', 'lhs_key' => 'id',
208
+    'rhs_module'=> $module, 'rhs_table'=> strtolower($module), 'rhs_key' => 'created_by',
209
+    'relationship_type'=>'one-to-many')
210 210
 ),
211 211
 
212 212
 
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -38,9 +38,9 @@  discard block
 block discarded – undo
38 38
  ********************************************************************************/
39 39
 
40 40
 $vardefs = array(  
41
-'fields' => array (
41
+'fields' => array(
42 42
 	  'id' =>
43
-	  array (
43
+	  array(
44 44
 	    'name' => 'id',
45 45
 	    'vname' => 'LBL_ID',
46 46
 	    'type' => 'id',
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
         'merge_filter' => 'selected',
67 67
 	    ),
68 68
 	  'date_entered' =>
69
-	  array (
69
+	  array(
70 70
 	    'name' => 'date_entered',
71 71
 	    'vname' => 'LBL_DATE_ENTERED',
72 72
 	    'type' => 'datetime',
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 		'inline_edit' => false,
78 78
 	  ),
79 79
 	  'date_modified' =>
80
-	  array (
80
+	  array(
81 81
 	    'name' => 'date_modified',
82 82
 	    'vname' => 'LBL_DATE_MODIFIED',
83 83
 	    'type' => 'datetime',
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 		'inline_edit' => false,
89 89
 	  ),
90 90
 		'modified_user_id' =>
91
-	  array (
91
+	  array(
92 92
 	    'name' => 'modified_user_id',
93 93
 	    'rname' => 'user_name',
94 94
 	    'id_name' => 'modified_user_id',
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		'inline_edit' => false,
105 105
 	  ),
106 106
 	  'modified_by_name' => 
107
-	  array (
107
+	  array(
108 108
 	    'name' => 'modified_by_name',
109 109
 	    'vname' => 'LBL_MODIFIED_NAME',
110 110
 	    'type' => 'relate',
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
 		'inline_edit' => false,
121 121
 	  ),  
122 122
 	  'created_by' =>
123
-	  array (
123
+	  array(
124 124
 	    'name' => 'created_by',
125 125
 	    'rname' => 'user_name',
126 126
 	    'id_name' => 'modified_user_id',
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 		'inline_edit' => false,
136 136
 	  ),
137 137
 	  'created_by_name' =>
138
-	  array (
138
+	  array(
139 139
 	    'name' => 'created_by_name',
140 140
 		'vname' => 'LBL_CREATED',
141 141
 		'type' => 'relate',
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 		'inline_edit' => false,
153 153
 	),
154 154
 	  'description' =>
155
-	  array (
155
+	  array(
156 156
 	    'name' => 'description',
157 157
 	    'vname' => 'LBL_DESCRIPTION',
158 158
 	    'type' => 'text',
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 	    'cols' => 80,
162 162
 	  ),
163 163
 	  'deleted' =>
164
-	  array (
164
+	  array(
165 165
 	    'name' => 'deleted',
166 166
 	    'vname' => 'LBL_DELETED',
167 167
 	    'type' => 'bool',
@@ -172,10 +172,10 @@  discard block
 block discarded – undo
172 172
 	    
173 173
 /////////////////RELATIONSHIP LINKS////////////////////////////
174 174
 	  'created_by_link' =>
175
-  array (
175
+  array(
176 176
      'name' => 'created_by_link',
177 177
     'type' => 'link',
178
-    'relationship' => strtolower($module) . '_created_by',
178
+    'relationship' => strtolower($module).'_created_by',
179 179
     'vname' => 'LBL_CREATED_USER',
180 180
     'link_type' => 'one',
181 181
     'module'=>'Users',
@@ -183,10 +183,10 @@  discard block
 block discarded – undo
183 183
     'source'=>'non-db',
184 184
   ),
185 185
   'modified_user_link' =>
186
-  array (
186
+  array(
187 187
         'name' => 'modified_user_link',
188 188
     'type' => 'link',
189
-    'relationship' => strtolower($module). '_modified_user',
189
+    'relationship' => strtolower($module).'_modified_user',
190 190
     'vname' => 'LBL_MODIFIED_USER',
191 191
     'link_type' => 'one',
192 192
     'module'=>'Users',
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
   ),
196 196
 
197 197
 ),
198
-'indices' => array (
198
+'indices' => array(
199 199
        'id'=>array('name' =>strtolower($module).'pk', 'type' =>'primary', 'fields'=>array('id')),
200 200
        ),
201 201
 'relationships'=>array(
Please login to merge, or discard this patch.
include/SugarObjects/templates/basic/language/en_us.lang.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@
 block discarded – undo
54 54
 'LBL_MODIFIED_USER'=>'Modified by User',
55 55
 'LBL_LIST_NAME'=>'Name',
56 56
 'LBL_EDIT_BUTTON' => 'Edit',
57
- 'LBL_REMOVE' => 'Remove',
57
+    'LBL_REMOVE' => 'Remove',
58 58
 
59 59
 
60 60
 );
61 61
\ No newline at end of file
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/MssqlManager.php 4 patches
Indentation   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -140,8 +140,8 @@  discard block
 block discarded – undo
140 140
             'relate'   => 'varchar',
141 141
             'multienum'=> 'text',
142 142
             'html'     => 'text',
143
-			'longhtml' => 'text',
144
-    		'datetime' => 'datetime',
143
+            'longhtml' => 'text',
144
+            'datetime' => 'datetime',
145 145
             'datetimecombo' => 'datetime',
146 146
             'time'     => 'datetime',
147 147
             'bool'     => 'bit',
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
             'url'      => 'varchar',
157 157
             'encrypt'  => 'varchar',
158 158
             'file'     => 'varchar',
159
-	        'decimal_tpl' => 'decimal(%d, %d)',
159
+            'decimal_tpl' => 'decimal(%d, %d)',
160 160
             );
161 161
 
162 162
     protected $connectOptions = null;
@@ -236,16 +236,16 @@  discard block
 block discarded – undo
236 236
         //it will throw an Unable to select database message.
237 237
 
238 238
         if(!empty($configOptions['db_name']) && !@mssql_select_db($configOptions['db_name'], $this->database)){
239
-			$connected = false;
240
-			for($i=0;$i<5;$i++){
241
-				usleep(200000);
242
-				if(@mssql_select_db($configOptions['db_name'], $this->database)){
243
-					$connected = true;
244
-					break;
245
-				}
246
-			}
247
-			if(!$connected){
248
-			    $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}");
239
+            $connected = false;
240
+            for($i=0;$i<5;$i++){
241
+                usleep(200000);
242
+                if(@mssql_select_db($configOptions['db_name'], $this->database)){
243
+                    $connected = true;
244
+                    break;
245
+                }
246
+            }
247
+            if(!$connected){
248
+                $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}");
249 249
                 if($dieOnError) {
250 250
                     if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
251 251
                         sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
@@ -255,8 +255,8 @@  discard block
 block discarded – undo
255 255
                 } else {
256 256
                     return false;
257 257
                 }
258
-			}
259
-         }
258
+            }
259
+            }
260 260
 
261 261
         if(!$this->checkError('Could Not Connect', $dieOnError))
262 262
             $GLOBALS['log']->info("connected to db");
@@ -267,18 +267,18 @@  discard block
 block discarded – undo
267 267
         return true;
268 268
     }
269 269
 
270
-	/**
270
+    /**
271 271
      * @see DBManager::version()
272 272
      */
273 273
     public function version()
274 274
     {
275 275
         return $this->getOne("SELECT @@VERSION as version");
276
-	}
276
+    }
277 277
 
278
-	/**
278
+    /**
279 279
      * @see DBManager::query()
280
-	 */
281
-	public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
280
+     */
281
+    public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
282 282
     {
283 283
         if(is_array($sql)) {
284 284
             return $this->queryArray($sql, $dieOnError, $msg, $suppress);
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
         if ((substr_count($sql, "'") & 1))
288 288
             $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
289 289
 
290
-		$sql = $this->_appendN($sql);
290
+        $sql = $this->_appendN($sql);
291 291
 
292 292
         $GLOBALS['log']->info('Query:' . $sql);
293 293
         $this->checkConnection();
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
         $this->query_time = microtime(true);
296 296
 
297 297
         // Bug 34892 - Clear out previous error message by checking the @@ERROR global variable
298
-		@mssql_query("SELECT @@ERROR", $this->database);
298
+        @mssql_query("SELECT @@ERROR", $this->database);
299 299
 
300 300
         $result = $suppress?@mssql_query($sql, $this->database):mssql_query($sql, $this->database);
301 301
 
@@ -305,18 +305,18 @@  discard block
 block discarded – undo
305 305
             //				  not affect the functionality of the query
306 306
             $sqlmsg = mssql_get_last_message();
307 307
             $sqlpos = strpos($sqlmsg, 'Changed database context to');
308
-			$sqlpos2 = strpos($sqlmsg, 'Warning:');
309
-			$sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
308
+            $sqlpos2 = strpos($sqlmsg, 'Warning:');
309
+            $sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
310 310
 
311
-			if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false)		// if sqlmsg has 'Changed database context to', just log it
312
-				$GLOBALS['log']->debug($sqlmsg . ": " . $sql );
313
-			else {
314
-				$GLOBALS['log']->fatal($sqlmsg . ": " . $sql );
315
-				if($dieOnError)
316
-					sugar_die('SQL Error : ' . $sqlmsg);
317
-				else
318
-					echo 'SQL Error : ' . $sqlmsg;
319
-			}
311
+            if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false)		// if sqlmsg has 'Changed database context to', just log it
312
+                $GLOBALS['log']->debug($sqlmsg . ": " . $sql );
313
+            else {
314
+                $GLOBALS['log']->fatal($sqlmsg . ": " . $sql );
315
+                if($dieOnError)
316
+                    sugar_die('SQL Error : ' . $sqlmsg);
317
+                else
318
+                    echo 'SQL Error : ' . $sqlmsg;
319
+            }
320 320
         }
321 321
 
322 322
         $this->query_time = microtime(true) - $this->query_time;
@@ -426,8 +426,8 @@  discard block
 block discarded – undo
426 426
         return $limitUnionSQL;
427 427
     }
428 428
 
429
-	/**
430
-	 * FIXME: verify and thoroughly test this code, these regexps look fishy
429
+    /**
430
+     * FIXME: verify and thoroughly test this code, these regexps look fishy
431 431
      * @see DBManager::limitQuery()
432 432
      */
433 433
     public function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true)
@@ -569,7 +569,7 @@  discard block
 block discarded – undo
569 569
                     }else{
570 570
                         //if there is a distinct clause, form query with rownumber after distinct
571 571
                         if ($hasDistinct) {
572
-                             $newSQL = "SELECT TOP $count * FROM
572
+                                $newSQL = "SELECT TOP $count * FROM
573 573
                                             (
574 574
                             SELECT ROW_NUMBER() OVER (ORDER BY ".$grpByStr.") AS row_number, count(*) counter, " . $distinctSQLARRAY[0] . "
575 575
                                                         " . $distinctSQLARRAY[1] . "
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
                                             WHERE row_number > $start";
580 580
                         }
581 581
                         else {
582
-                             $newSQL = "SELECT TOP $count * FROM
582
+                                $newSQL = "SELECT TOP $count * FROM
583 583
                                            (
584 584
                                   " . $matches[1] . " ROW_NUMBER() OVER (ORDER BY " . $sqlArray['FROM'][0]['alias'] . ".id) AS row_number, " . $matches[2] . $matches[3]. "
585 585
                                            )
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
         while ($i<$count && $offset<strlen($p_sql)) {
627 627
             if ($offset > strlen($p_sql))
628 628
             {
629
-				break;
629
+                break;
630 630
             }
631 631
 
632 632
             $beg_sin = strpos($p_sql, $strip_beg, $offset);
@@ -665,7 +665,7 @@  discard block
 block discarded – undo
665 665
      * @param  array  $pattern_array
666 666
      * @return string
667 667
      */
668
-	private function addPatternToSQL($token, array $pattern_array)
668
+    private function addPatternToSQL($token, array $pattern_array)
669 669
     {
670 670
         //strip all single quotes out
671 671
         $pattern_array = array_reverse($pattern_array);
@@ -684,7 +684,7 @@  discard block
 block discarded – undo
684 684
      * @param  string $alias
685 685
      * @return string
686 686
      */
687
-	private function getAliasFromSQL($sql, $alias)
687
+    private function getAliasFromSQL($sql, $alias)
688 688
     {
689 689
         $matches = array();
690 690
         preg_match('/^(.*SELECT)(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
@@ -786,7 +786,7 @@  discard block
 block discarded – undo
786 786
 
787 787
         // If there is no ordering direction (ASC/DESC), use ASC by default
788 788
         if (strpos($orig_order_match, " ") === false) {
789
-        	$orig_order_match .= " ASC";
789
+            $orig_order_match .= " ASC";
790 790
         }
791 791
 
792 792
         //grab first space in order by
@@ -810,11 +810,11 @@  discard block
 block discarded – undo
810 810
                 $lastSpacePos = strrpos($containsColStr, " ");
811 811
                 //use positions of column name, space before name, and length of column to find the correct column name
812 812
                 $col_name = substr($sql, $lastSpacePos, $colMatchPos-$lastSpacePos+strlen($orderMatch));
813
-				//bug 25485. When sorting by a custom field in Account List and then pressing NEXT >, system gives an error
814
-				$containsCommaPos = strpos($col_name, ",");
815
-				if($containsCommaPos !== false) {
816
-					$col_name = substr($col_name, $containsCommaPos+1);
817
-				}
813
+                //bug 25485. When sorting by a custom field in Account List and then pressing NEXT >, system gives an error
814
+                $containsCommaPos = strpos($col_name, ",");
815
+                if($containsCommaPos !== false) {
816
+                    $col_name = substr($col_name, $containsCommaPos+1);
817
+                }
818 818
                 //add the "asc/desc" order back
819 819
                 $col_name = $col_name. " ". $asc_desc;
820 820
 
@@ -967,14 +967,14 @@  discard block
 block discarded – undo
967 967
     }
968 968
 
969 969
 
970
-	/**
970
+    /**
971 971
      * @see DBManager::getFieldsArray()
972 972
      */
973
-	public function getFieldsArray($result, $make_lower_case = false)
974
-	{
975
-		$field_array = array();
973
+    public function getFieldsArray($result, $make_lower_case = false)
974
+    {
975
+        $field_array = array();
976 976
 
977
-		if(! isset($result) || empty($result))
977
+        if(! isset($result) || empty($result))
978 978
             return 0;
979 979
 
980 980
         $i = 0;
@@ -991,37 +991,37 @@  discard block
 block discarded – undo
991 991
         }
992 992
 
993 993
         return $field_array;
994
-	}
994
+    }
995 995
 
996 996
     /**
997 997
      * @see DBManager::getAffectedRowCount()
998 998
      */
999
-	public function getAffectedRowCount($result)
999
+    public function getAffectedRowCount($result)
1000 1000
     {
1001 1001
         return $this->getOne("SELECT @@ROWCOUNT");
1002 1002
     }
1003 1003
 
1004
-	/**
1005
-	 * @see DBManager::fetchRow()
1006
-	 */
1007
-	public function fetchRow($result)
1008
-	{
1009
-		if (empty($result))	return false;
1004
+    /**
1005
+     * @see DBManager::fetchRow()
1006
+     */
1007
+    public function fetchRow($result)
1008
+    {
1009
+        if (empty($result))	return false;
1010 1010
 
1011 1011
         $row = mssql_fetch_assoc($result);
1012 1012
         //MSSQL returns a space " " when a varchar column is empty ("") and not null.
1013 1013
         //We need to iterate through the returned row array and strip empty spaces
1014 1014
         if(!empty($row)){
1015 1015
             foreach($row as $key => $column) {
1016
-               //notice we only strip if one space is returned.  we do not want to strip
1017
-               //strings with intentional spaces (" foo ")
1018
-               if (!empty($column) && $column ==" ") {
1019
-                   $row[$key] = '';
1020
-               }
1016
+                //notice we only strip if one space is returned.  we do not want to strip
1017
+                //strings with intentional spaces (" foo ")
1018
+                if (!empty($column) && $column ==" ") {
1019
+                    $row[$key] = '';
1020
+                }
1021 1021
             }
1022 1022
         }
1023 1023
         return $row;
1024
-	}
1024
+    }
1025 1025
 
1026 1026
     /**
1027 1027
      * @see DBManager::quote()
@@ -1069,7 +1069,7 @@  discard block
 block discarded – undo
1069 1069
             if (!empty($r)) {
1070 1070
                 while ($a = $this->fetchByAssoc($r)) {
1071 1071
                     $row = array_values($a);
1072
-					$tables[]=$row[0];
1072
+                    $tables[]=$row[0];
1073 1073
                 }
1074 1074
                 return $tables;
1075 1075
             }
@@ -1126,7 +1126,7 @@  discard block
 block discarded – undo
1126 1126
                 )
1127 1127
                 ";
1128 1128
                 //create full text index
1129
-                 $FTSqry[] = "CREATE FULLTEXT INDEX ON fts_wakeup
1129
+                    $FTSqry[] = "CREATE FULLTEXT INDEX ON fts_wakeup
1130 1130
                 (
1131 1131
                     body
1132 1132
                     Language 0X0
@@ -1195,7 +1195,7 @@  discard block
 block discarded – undo
1195 1195
                     $len = $this->date_formats[$additional_parameters[0]];
1196 1196
                     return "LEFT(CONVERT(varchar($len),". $string . ",120),$len)";
1197 1197
                 } else {
1198
-                   return "LEFT(CONVERT(varchar(10),". $string . ",120),10)";
1198
+                    return "LEFT(CONVERT(varchar(10),". $string . ",120),10)";
1199 1199
                 }
1200 1200
             case 'ifnull':
1201 1201
                 if(empty($additional_parameters_string)) {
@@ -1237,14 +1237,14 @@  discard block
 block discarded – undo
1237 1237
             case 'datetime': return substr($string, 0,19);
1238 1238
             case 'date': return substr($string, 0, 10);
1239 1239
             case 'time': return substr($string, 11);
1240
-		}
1241
-		return $string;
1240
+        }
1241
+        return $string;
1242 1242
     }
1243 1243
 
1244 1244
     /**
1245 1245
      * @see DBManager::createTableSQLParams()
1246 1246
      */
1247
-	public function createTableSQLParams($tablename, $fieldDefs, $indices)
1247
+    public function createTableSQLParams($tablename, $fieldDefs, $indices)
1248 1248
     {
1249 1249
         if (empty($tablename) || empty($fieldDefs))
1250 1250
             return '';
@@ -1322,7 +1322,7 @@  discard block
 block discarded – undo
1322 1322
             break;
1323 1323
         default:
1324 1324
             return '';
1325
-    	}
1325
+        }
1326 1326
     }
1327 1327
 
1328 1328
     /**
@@ -1338,14 +1338,14 @@  discard block
 block discarded – undo
1338 1338
         $columns = array();
1339 1339
         if ($this->isFieldArray($fieldDefs)) {
1340 1340
             foreach ($fieldDefs as $def)
1341
-      		{
1342
-          		//if the column is being modified drop the default value
1343
-          		//constraint if it exists. alterSQLRep will add the constraint back
1344
-          		if (!empty($constraints[$def['name']])) {
1345
-          			$sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$def['name']];
1346
-          		}
1347
-          		//check to see if we need to drop related indexes before the alter
1348
-          		$indices = $this->get_indices($tablename);
1341
+                {
1342
+                    //if the column is being modified drop the default value
1343
+                    //constraint if it exists. alterSQLRep will add the constraint back
1344
+                    if (!empty($constraints[$def['name']])) {
1345
+                        $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$def['name']];
1346
+                    }
1347
+                    //check to see if we need to drop related indexes before the alter
1348
+                    $indices = $this->get_indices($tablename);
1349 1349
                 foreach ( $indices as $index ) {
1350 1350
                     if ( in_array($def['name'],$index['fields']) ) {
1351 1351
                         $sql  .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
@@ -1353,16 +1353,16 @@  discard block
 block discarded – undo
1353 1353
                     }
1354 1354
                 }
1355 1355
 
1356
-          		$columns[] = $this->alterSQLRep($action, $def, $ignoreRequired,$tablename);
1357
-      		}
1356
+                    $columns[] = $this->alterSQLRep($action, $def, $ignoreRequired,$tablename);
1357
+                }
1358 1358
         }
1359 1359
         else {
1360 1360
             //if the column is being modified drop the default value
1361
-      		//constraint if it exists. alterSQLRep will add the constraint back
1362
-      		if (!empty($constraints[$fieldDefs['name']])) {
1363
-      			$sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$fieldDefs['name']];
1364
-      		}
1365
-      		//check to see if we need to drop related indexes before the alter
1361
+                //constraint if it exists. alterSQLRep will add the constraint back
1362
+                if (!empty($constraints[$fieldDefs['name']])) {
1363
+                    $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$fieldDefs['name']];
1364
+                }
1365
+                //check to see if we need to drop related indexes before the alter
1366 1366
             $indices = $this->get_indices($tablename);
1367 1367
             foreach ( $indices as $index ) {
1368 1368
                 if ( in_array($fieldDefs['name'],$index['fields']) ) {
@@ -1372,7 +1372,7 @@  discard block
 block discarded – undo
1372 1372
             }
1373 1373
 
1374 1374
 
1375
-          	$columns[] = $this->alterSQLRep($action, $fieldDefs, $ignoreRequired,$tablename);
1375
+                $columns[] = $this->alterSQLRep($action, $fieldDefs, $ignoreRequired,$tablename);
1376 1376
         }
1377 1377
 
1378 1378
         $columns = implode(", ", $columns);
@@ -1383,8 +1383,8 @@  discard block
 block discarded – undo
1383 1383
 
1384 1384
     protected function setAutoIncrement($table, $field_name)
1385 1385
     {
1386
-		return "identity(1,1)";
1387
-	}
1386
+        return "identity(1,1)";
1387
+    }
1388 1388
 
1389 1389
     /**
1390 1390
      * @see DBManager::setAutoIncrementStart()
@@ -1393,16 +1393,16 @@  discard block
 block discarded – undo
1393 1393
     {
1394 1394
         if($start_value > 1)
1395 1395
             $start_value -= 1;
1396
-		$this->query("DBCC CHECKIDENT ('$table', RESEED, $start_value) WITH NO_INFOMSGS");
1396
+        $this->query("DBCC CHECKIDENT ('$table', RESEED, $start_value) WITH NO_INFOMSGS");
1397 1397
         return true;
1398 1398
     }
1399 1399
 
1400
-	/**
1400
+    /**
1401 1401
      * @see DBManager::getAutoIncrement()
1402 1402
      */
1403 1403
     public function getAutoIncrement($table, $field_name)
1404 1404
     {
1405
-		$result = $this->getOne("select IDENT_CURRENT('$table') + IDENT_INCR ( '$table' ) as 'Auto_increment'");
1405
+        $result = $this->getOne("select IDENT_CURRENT('$table') + IDENT_INCR ( '$table' ) as 'Auto_increment'");
1406 1406
         return $result;
1407 1407
     }
1408 1408
 
@@ -1457,8 +1457,8 @@  discard block
 block discarded – undo
1457 1457
                 $columns[$column_name]['len']=strtolower($row['PRECISION']);
1458 1458
                 $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
1459 1459
             }
1460
-			elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) )
1461
-				$columns[$column_name]['len']=strtolower($row['PRECISION']);
1460
+            elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) )
1461
+                $columns[$column_name]['len']=strtolower($row['PRECISION']);
1462 1462
             elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) )
1463 1463
                 $columns[$column_name]['len']=strtolower($row['LENGTH']);
1464 1464
             if ( stristr($row['TYPE_NAME'],'identity') ) {
@@ -1585,7 +1585,7 @@  discard block
 block discarded – undo
1585 1585
     protected function full_text_indexing_enabled($dbname = null)
1586 1586
     {
1587 1587
         // check to see if we already have install setting in session
1588
-    	if(!isset($_SESSION['IsFulltextInstalled']))
1588
+        if(!isset($_SESSION['IsFulltextInstalled']))
1589 1589
             $_SESSION['IsFulltextInstalled'] = $this->full_text_indexing_installed();
1590 1590
 
1591 1591
         // check to see if FTS Indexing service is installed
@@ -1593,27 +1593,27 @@  discard block
 block discarded – undo
1593 1593
             return false;
1594 1594
 
1595 1595
         // grab the dbname if it was not passed through
1596
-		if (empty($dbname)) {
1597
-			global $sugar_config;
1598
-			$dbname = $sugar_config['dbconfig']['db_name'];
1599
-		}
1596
+        if (empty($dbname)) {
1597
+            global $sugar_config;
1598
+            $dbname = $sugar_config['dbconfig']['db_name'];
1599
+        }
1600 1600
         //we already know that Indexing service is installed, now check
1601 1601
         //to see if it is enabled
1602
-		$res = $this->getOne("SELECT DATABASEPROPERTY('$dbname', 'IsFulltextEnabled') ftext");
1602
+        $res = $this->getOne("SELECT DATABASEPROPERTY('$dbname', 'IsFulltextEnabled') ftext");
1603 1603
         return !empty($res);
1604
-	}
1604
+    }
1605 1605
 
1606 1606
     /**
1607 1607
      * Creates default full text catalog
1608 1608
      */
1609
-	protected function create_default_full_text_catalog()
1609
+    protected function create_default_full_text_catalog()
1610 1610
     {
1611
-		if ($this->full_text_indexing_enabled()) {
1612
-		    $catalog = $this->ftsCatalogName();
1611
+        if ($this->full_text_indexing_enabled()) {
1612
+            $catalog = $this->ftsCatalogName();
1613 1613
             $GLOBALS['log']->debug("Creating the default catalog for full-text indexing, $catalog");
1614 1614
 
1615 1615
             //drop catalog if exists.
1616
-			$ret = $this->query("
1616
+            $ret = $this->query("
1617 1617
                 if not exists(
1618 1618
                     select *
1619 1619
                         from sys.fulltext_catalogs
@@ -1621,11 +1621,11 @@  discard block
 block discarded – undo
1621 1621
                         )
1622 1622
                 CREATE FULLTEXT CATALOG $catalog");
1623 1623
 
1624
-			if (empty($ret)) {
1625
-				$GLOBALS['log']->error("Error creating default full-text catalog, $catalog");
1626
-			}
1627
-		}
1628
-	}
1624
+            if (empty($ret)) {
1625
+                $GLOBALS['log']->error("Error creating default full-text catalog, $catalog");
1626
+            }
1627
+        }
1628
+    }
1629 1629
 
1630 1630
     /**
1631 1631
      * Function returns name of the constraint automatically generated by sql-server.
@@ -1635,7 +1635,7 @@  discard block
 block discarded – undo
1635 1635
      * @param  string $column
1636 1636
      * @return string
1637 1637
      */
1638
-	private function get_field_default_constraint_name($table, $column = null)
1638
+    private function get_field_default_constraint_name($table, $column = null)
1639 1639
     {
1640 1640
         static $results = array();
1641 1641
 
@@ -1670,7 +1670,7 @@  discard block
 block discarded – undo
1670 1670
         }
1671 1671
 
1672 1672
         return null;
1673
-	}
1673
+    }
1674 1674
 
1675 1675
     /**
1676 1676
      * @see DBManager::massageFieldDef()
@@ -1692,7 +1692,7 @@  discard block
 block discarded – undo
1692 1692
                 case 'varchar'  :
1693 1693
                 case 'nvarchar' :
1694 1694
                                   $fieldDef['len'] = $this->isTextType($fieldDef['dbType']) ? 'max' : '255';
1695
-                                  break;
1695
+                                    break;
1696 1696
                 case 'image'    : $fieldDef['len'] = '2147483647'; break;
1697 1697
                 case 'ntext'    : $fieldDef['len'] = '2147483646'; break;   // Note: this is from legacy code, don't know if this is correct
1698 1698
             }
@@ -1701,7 +1701,7 @@  discard block
 block discarded – undo
1701 1701
            && empty($fieldDef['precision'])
1702 1702
            && !strpos($fieldDef['len'], ','))
1703 1703
         {
1704
-             $fieldDef['len'] .= ',0'; // Adding 0 precision if it is not specified
1704
+                $fieldDef['len'] .= ',0'; // Adding 0 precision if it is not specified
1705 1705
         }
1706 1706
 
1707 1707
         if(empty($fieldDef['default'])
@@ -1709,8 +1709,8 @@  discard block
 block discarded – undo
1709 1709
         {
1710 1710
             $fieldDef['default'] = '0';
1711 1711
         }
1712
-		if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']) )
1713
-			$fieldDef['default'] = '';
1712
+        if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']) )
1713
+            $fieldDef['default'] = '';
1714 1714
 //        if ($fieldDef['type'] == 'bit' && empty($fieldDef['len']) )
1715 1715
 //            $fieldDef['len'] = '1';
1716 1716
 //		if ($fieldDef['type'] == 'bool' && empty($fieldDef['len']) )
@@ -1739,30 +1739,30 @@  discard block
 block discarded – undo
1739 1739
      */
1740 1740
     protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
1741 1741
     {
1742
-    	//Bug 25814
1743
-		if(isset($fieldDef['name'])){
1744
-		    $colType = $this->getFieldType($fieldDef);
1745
-        	if(stristr($this->getFieldType($fieldDef), 'decimal') && isset($fieldDef['len'])){
1746
-				$fieldDef['len'] = min($fieldDef['len'],38);
1747
-			}
1748
-		    //bug: 39690 float(8) is interpreted as real and this generates a diff when doing repair
1749
-			if(stristr($colType, 'float') && isset($fieldDef['len']) && $fieldDef['len'] == 8){
1750
-				unset($fieldDef['len']);
1751
-			}
1752
-		}
1753
-
1754
-		// always return as array for post-processing
1755
-		$ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
1756
-
1757
-		// Bug 24307 - Don't add precision for float fields.
1758
-		if ( stristr($ref['colType'],'float') )
1759
-			$ref['colType'] = preg_replace('/(,\d+)/','',$ref['colType']);
1742
+        //Bug 25814
1743
+        if(isset($fieldDef['name'])){
1744
+            $colType = $this->getFieldType($fieldDef);
1745
+            if(stristr($this->getFieldType($fieldDef), 'decimal') && isset($fieldDef['len'])){
1746
+                $fieldDef['len'] = min($fieldDef['len'],38);
1747
+            }
1748
+            //bug: 39690 float(8) is interpreted as real and this generates a diff when doing repair
1749
+            if(stristr($colType, 'float') && isset($fieldDef['len']) && $fieldDef['len'] == 8){
1750
+                unset($fieldDef['len']);
1751
+            }
1752
+        }
1753
+
1754
+        // always return as array for post-processing
1755
+        $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
1756
+
1757
+        // Bug 24307 - Don't add precision for float fields.
1758
+        if ( stristr($ref['colType'],'float') )
1759
+            $ref['colType'] = preg_replace('/(,\d+)/','',$ref['colType']);
1760 1760
 
1761 1761
         if ( $return_as_array )
1762 1762
             return $ref;
1763 1763
         else
1764 1764
             return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
1765
-	}
1765
+    }
1766 1766
 
1767 1767
     /**
1768 1768
      * Saves changes to module's audit table
@@ -1771,13 +1771,13 @@  discard block
 block discarded – undo
1771 1771
      * @param array  $changes changes
1772 1772
      */
1773 1773
     public function save_audit_records(SugarBean $bean, $changes)
1774
-	{
1775
-		//Bug 25078 fixed by Martin Hu: sqlserver haven't 'date' type, trim extra "00:00:00"
1776
-		if($changes['data_type'] == 'date'){
1777
-			$changes['before'] = str_replace(' 00:00:00','',$changes['before']);
1778
-		}
1779
-		parent::save_audit_records($bean,$changes);
1780
-	}
1774
+    {
1775
+        //Bug 25078 fixed by Martin Hu: sqlserver haven't 'date' type, trim extra "00:00:00"
1776
+        if($changes['data_type'] == 'date'){
1777
+            $changes['before'] = str_replace(' 00:00:00','',$changes['before']);
1778
+        }
1779
+        parent::save_audit_records($bean,$changes);
1780
+    }
1781 1781
 
1782 1782
     /**
1783 1783
      * Disconnects from the database
@@ -1786,7 +1786,7 @@  discard block
 block discarded – undo
1786 1786
      */
1787 1787
     public function disconnect()
1788 1788
     {
1789
-    	$GLOBALS['log']->debug('Calling Mssql::disconnect()');
1789
+        $GLOBALS['log']->debug('Calling Mssql::disconnect()');
1790 1790
         if(!empty($this->database)){
1791 1791
             $this->freeResult();
1792 1792
             mssql_close($this->database);
@@ -1803,21 +1803,21 @@  discard block
 block discarded – undo
1803 1803
             mssql_free_result($dbResult);
1804 1804
     }
1805 1805
 
1806
-	/**
1807
-	 * (non-PHPdoc)
1808
-	 * @see DBManager::lastDbError()
1809
-	 */
1806
+    /**
1807
+     * (non-PHPdoc)
1808
+     * @see DBManager::lastDbError()
1809
+     */
1810 1810
     public function lastDbError()
1811 1811
     {
1812 1812
         $sqlmsg = mssql_get_last_message();
1813 1813
         if(empty($sqlmsg)) return false;
1814 1814
         global $app_strings;
1815 1815
         if (empty($app_strings)
1816
-		    or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
1817
-			or !isset($app_strings['ERR_MSSQL_WARNING']) ) {
1816
+            or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
1817
+            or !isset($app_strings['ERR_MSSQL_WARNING']) ) {
1818 1818
         //ignore the message from sql-server if $app_strings array is empty. This will happen
1819 1819
         //only if connection if made before language is set.
1820
-		    return false;
1820
+            return false;
1821 1821
         }
1822 1822
 
1823 1823
         $sqlpos = strpos($sqlmsg, 'Changed database context to');
@@ -1826,7 +1826,7 @@  discard block
 block discarded – undo
1826 1826
         if ( $sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false ) {
1827 1827
             return false;
1828 1828
         } else {
1829
-        	global $app_strings;
1829
+            global $app_strings;
1830 1830
             //ERR_MSSQL_DB_CONTEXT: localized version of 'Changed database context to' message
1831 1831
             if (empty($app_strings) or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])) {
1832 1832
                 //ignore the message from sql-server if $app_strings array is empty. This will happen
@@ -1842,7 +1842,7 @@  discard block
 block discarded – undo
1842 1842
         }
1843 1843
 
1844 1844
         if ( strlen($sqlmsg) > 2 ) {
1845
-        	return "SQL Server error: " . $sqlmsg;
1845
+            return "SQL Server error: " . $sqlmsg;
1846 1846
         }
1847 1847
 
1848 1848
         return false;
@@ -2065,7 +2065,7 @@  discard block
 block discarded – undo
2065 2065
     public function installConfig()
2066 2066
     {
2067 2067
         return array(
2068
-        	'LBL_DBCONFIG_MSG3' =>  array(
2068
+            'LBL_DBCONFIG_MSG3' =>  array(
2069 2069
                 "setup_db_database_name" => array("label" => 'LBL_DBCONF_DB_NAME', "required" => true),
2070 2070
             ),
2071 2071
             'LBL_DBCONFIG_MSG2' =>  array(
@@ -2097,8 +2097,8 @@  discard block
 block discarded – undo
2097 2097
      * @return string
2098 2098
      */
2099 2099
 
2100
-	public function getGuidSQL()
2100
+    public function getGuidSQL()
2101 2101
     {
2102
-      	return 'NEWID()';
2102
+            return 'NEWID()';
2103 2103
     }
2104 2104
 }
Please login to merge, or discard this patch.
Switch Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -1304,24 +1304,24 @@  discard block
 block discarded – undo
1304 1304
     protected function alterSQLRep($action, array $def, $ignoreRequired, $tablename)
1305 1305
     {
1306 1306
         switch($action){
1307
-        case 'add':
1308
-             $f_def=$this->oneColumnSQLRep($def, $ignoreRequired,$tablename,false);
1309
-            return "ADD " . $f_def;
1310
-            break;
1311
-        case 'drop':
1312
-            return "DROP COLUMN " . $def['name'];
1313
-            break;
1314
-        case 'modify':
1315
-            //You cannot specify a default value for a column for MSSQL
1316
-            $f_def  = $this->oneColumnSQLRep($def, $ignoreRequired,$tablename, true);
1317
-            $f_stmt = "ALTER COLUMN ".$f_def['name'].' '.$f_def['colType'].' '.
1318
-                        $f_def['required'].' '.$f_def['auto_increment']."\n";
1319
-            if (!empty( $f_def['default']))
1320
-                $f_stmt .= " ALTER TABLE " . $tablename .  " ADD  ". $f_def['default'] . " FOR " . $def['name'];
1321
-            return $f_stmt;
1322
-            break;
1323
-        default:
1324
-            return '';
1307
+            case 'add':
1308
+                 $f_def=$this->oneColumnSQLRep($def, $ignoreRequired,$tablename,false);
1309
+                return "ADD " . $f_def;
1310
+                break;
1311
+            case 'drop':
1312
+                return "DROP COLUMN " . $def['name'];
1313
+                break;
1314
+            case 'modify':
1315
+                //You cannot specify a default value for a column for MSSQL
1316
+                $f_def  = $this->oneColumnSQLRep($def, $ignoreRequired,$tablename, true);
1317
+                $f_stmt = "ALTER COLUMN ".$f_def['name'].' '.$f_def['colType'].' '.
1318
+                            $f_def['required'].' '.$f_def['auto_increment']."\n";
1319
+                if (!empty( $f_def['default']))
1320
+                    $f_stmt .= " ALTER TABLE " . $tablename .  " ADD  ". $f_def['default'] . " FOR " . $def['name'];
1321
+                return $f_stmt;
1322
+                break;
1323
+            default:
1324
+                return '';
1325 1325
     	}
1326 1326
     }
1327 1327
 
@@ -1511,59 +1511,59 @@  discard block
 block discarded – undo
1511 1511
 
1512 1512
         switch ($type){
1513 1513
         // generic indices
1514
-        case 'index':
1515
-        case 'alternate_key':
1516
-            if ($drop)
1517
-                $sql = "DROP INDEX {$name} ON {$table}";
1518
-            else
1519
-                $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
1520
-            break;
1521
-        case 'clustered':
1522
-            if ($drop)
1523
-                $sql = "DROP INDEX {$name} ON {$table}";
1524
-            else
1525
-                $sql = "CREATE CLUSTERED INDEX $name ON $table ($fields)";
1526
-            break;
1527
-            // constraints as indices
1528
-        case 'unique':
1529
-            if ($drop)
1530
-                $sql = "ALTER TABLE {$table} DROP CONSTRAINT $name";
1531
-            else
1532
-                $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE ({$fields})";
1533
-            break;
1534
-        case 'primary':
1535
-            if ($drop)
1536
-                $sql = "ALTER TABLE {$table} DROP CONSTRAINT {$name}";
1537
-            else
1538
-                $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} PRIMARY KEY ({$fields})";
1539
-            break;
1540
-        case 'foreign':
1541
-            if ($drop)
1542
-                $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
1543
-            else
1544
-                $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name}  FOREIGN KEY ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignFields']})";
1545
-            break;
1546
-        case 'fulltext':
1547
-            if ($this->full_text_indexing_enabled() && $drop) {
1548
-                $sql = "DROP FULLTEXT INDEX ON {$table}";
1549
-            } elseif ($this->full_text_indexing_enabled()) {
1550
-                $catalog_name=$this->ftsCatalogName();
1551
-                if ( isset($definition['catalog_name']) && $definition['catalog_name'] != 'default')
1552
-                    $catalog_name = $definition['catalog_name'];
1553
-
1554
-                $language = "Language 1033";
1555
-                if (isset($definition['language']) && !empty($definition['language']))
1556
-                    $language = "Language " . $definition['language'];
1557
-
1558
-                $key_index = $definition['key_index'];
1559
-
1560
-                $change_tracking = "auto";
1561
-                if (isset($definition['change_tracking']) && !empty($definition['change_tracking']))
1562
-                    $change_tracking = $definition['change_tracking'];
1563
-
1564
-                $sql = " CREATE FULLTEXT INDEX ON $table ($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
1565
-            }
1566
-            break;
1514
+            case 'index':
1515
+            case 'alternate_key':
1516
+                if ($drop)
1517
+                    $sql = "DROP INDEX {$name} ON {$table}";
1518
+                else
1519
+                    $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
1520
+                break;
1521
+            case 'clustered':
1522
+                if ($drop)
1523
+                    $sql = "DROP INDEX {$name} ON {$table}";
1524
+                else
1525
+                    $sql = "CREATE CLUSTERED INDEX $name ON $table ($fields)";
1526
+                break;
1527
+                // constraints as indices
1528
+            case 'unique':
1529
+                if ($drop)
1530
+                    $sql = "ALTER TABLE {$table} DROP CONSTRAINT $name";
1531
+                else
1532
+                    $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE ({$fields})";
1533
+                break;
1534
+            case 'primary':
1535
+                if ($drop)
1536
+                    $sql = "ALTER TABLE {$table} DROP CONSTRAINT {$name}";
1537
+                else
1538
+                    $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} PRIMARY KEY ({$fields})";
1539
+                break;
1540
+            case 'foreign':
1541
+                if ($drop)
1542
+                    $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
1543
+                else
1544
+                    $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name}  FOREIGN KEY ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignFields']})";
1545
+                break;
1546
+            case 'fulltext':
1547
+                if ($this->full_text_indexing_enabled() && $drop) {
1548
+                    $sql = "DROP FULLTEXT INDEX ON {$table}";
1549
+                } elseif ($this->full_text_indexing_enabled()) {
1550
+                    $catalog_name=$this->ftsCatalogName();
1551
+                    if ( isset($definition['catalog_name']) && $definition['catalog_name'] != 'default')
1552
+                        $catalog_name = $definition['catalog_name'];
1553
+
1554
+                    $language = "Language 1033";
1555
+                    if (isset($definition['language']) && !empty($definition['language']))
1556
+                        $language = "Language " . $definition['language'];
1557
+
1558
+                    $key_index = $definition['key_index'];
1559
+
1560
+                    $change_tracking = "auto";
1561
+                    if (isset($definition['change_tracking']) && !empty($definition['change_tracking']))
1562
+                        $change_tracking = $definition['change_tracking'];
1563
+
1564
+                    $sql = " CREATE FULLTEXT INDEX ON $table ($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
1565
+                }
1566
+                break;
1567 1567
         }
1568 1568
         return $sql;
1569 1569
     }
Please login to merge, or discard this patch.
Braces   +202 added lines, -159 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.
@@ -168,8 +170,9 @@  discard block
 block discarded – undo
168 170
     {
169 171
         global $sugar_config;
170 172
 
171
-        if (is_null($configOptions))
172
-            $configOptions = $sugar_config['dbconfig'];
173
+        if (is_null($configOptions)) {
174
+                    $configOptions = $sugar_config['dbconfig'];
175
+        }
173 176
 
174 177
         //SET DATEFORMAT to 'YYYY-MM-DD''
175 178
         ini_set('mssql.datetimeconvert', '0');
@@ -258,8 +261,9 @@  discard block
 block discarded – undo
258 261
 			}
259 262
          }
260 263
 
261
-        if(!$this->checkError('Could Not Connect', $dieOnError))
262
-            $GLOBALS['log']->info("connected to db");
264
+        if(!$this->checkError('Could Not Connect', $dieOnError)) {
265
+                    $GLOBALS['log']->info("connected to db");
266
+        }
263 267
 
264 268
         $this->connectOptions = $configOptions;
265 269
 
@@ -284,8 +288,9 @@  discard block
 block discarded – undo
284 288
             return $this->queryArray($sql, $dieOnError, $msg, $suppress);
285 289
         }
286 290
         // Flag if there are odd number of single quotes
287
-        if ((substr_count($sql, "'") & 1))
288
-            $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
291
+        if ((substr_count($sql, "'") & 1)) {
292
+                    $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
293
+        }
289 294
 
290 295
 		$sql = $this->_appendN($sql);
291 296
 
@@ -308,14 +313,16 @@  discard block
 block discarded – undo
308 313
 			$sqlpos2 = strpos($sqlmsg, 'Warning:');
309 314
 			$sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
310 315
 
311
-			if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false)		// if sqlmsg has 'Changed database context to', just log it
316
+			if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false) {
317
+			    // if sqlmsg has 'Changed database context to', just log it
312 318
 				$GLOBALS['log']->debug($sqlmsg . ": " . $sql );
313
-			else {
319
+			} else {
314 320
 				$GLOBALS['log']->fatal($sqlmsg . ": " . $sql );
315
-				if($dieOnError)
316
-					sugar_die('SQL Error : ' . $sqlmsg);
317
-				else
318
-					echo 'SQL Error : ' . $sqlmsg;
321
+				if($dieOnError) {
322
+									sugar_die('SQL Error : ' . $sqlmsg);
323
+				} else {
324
+									echo 'SQL Error : ' . $sqlmsg;
325
+				}
319 326
 			}
320 327
         }
321 328
 
@@ -340,8 +347,9 @@  discard block
 block discarded – undo
340 347
     private function handleUnionLimitQuery($sql, $start, $count)
341 348
     {
342 349
         //set the start to 0, no negs
343
-        if ($start < 0)
344
-            $start=0;
350
+        if ($start < 0) {
351
+                    $start=0;
352
+        }
345 353
 
346 354
         $GLOBALS['log']->debug(print_r(func_get_args(),true));
347 355
 
@@ -390,8 +398,7 @@  discard block
 block discarded – undo
390 398
                 $rowNumOrderBy = 'id';
391 399
                 $unionOrderBy = "";
392 400
             }
393
-        }
394
-        else {
401
+        } else {
395 402
             //there are no order by elements, so just pass back string
396 403
             $unionsql = $sql;
397 404
             //with no guidance on what to use for required order by in rownumber function,
@@ -413,8 +420,7 @@  discard block
 block discarded – undo
413 420
         if ($count == 1 && $start == 0)
414 421
         {
415 422
             $limitUnionSQL = "SELECT TOP $count * FROM (" .$unionsql .") as top_count ".$unionOrderBy;
416
-        }
417
-        else
423
+        } else
418 424
         {
419 425
             $limitUnionSQL = "SELECT TOP $count * FROM( select ROW_NUMBER() OVER ( order by "
420 426
             .$rowNumOrderBy.") AS row_number, * FROM ("
@@ -436,11 +442,12 @@  discard block
 block discarded – undo
436 442
         $count = (int)$count;
437 443
         $newSQL = $sql;
438 444
         $distinctSQLARRAY = array();
439
-        if (strpos($sql, "UNION") && !preg_match("/(')(UNION).?(')/i", $sql))
440
-            $newSQL = $this->handleUnionLimitQuery($sql,$start,$count);
441
-        else {
442
-            if ($start < 0)
443
-                $start = 0;
445
+        if (strpos($sql, "UNION") && !preg_match("/(')(UNION).?(')/i", $sql)) {
446
+                    $newSQL = $this->handleUnionLimitQuery($sql,$start,$count);
447
+        } else {
448
+            if ($start < 0) {
449
+                            $start = 0;
450
+            }
444 451
             $GLOBALS['log']->debug(print_r(func_get_args(),true));
445 452
             $this->lastsql = $sql;
446 453
             $matches = array();
@@ -461,20 +468,17 @@  discard block
 block discarded – undo
461 468
                                     " . $selectPart[2] . $orderByMatch[1]. "
462 469
                                 ) AS a
463 470
                                 WHERE row_number > $start";
464
-                        }
465
-                        else {
471
+                        } else {
466 472
                             $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
467 473
                         }
468
-                    }
469
-                    else {
474
+                    } else {
470 475
                         $distinct_o = strpos($match_two, "distinct");
471 476
                         $up_to_distinct_str = substr($match_two, 0, $distinct_o);
472 477
                         //check to see if the distinct is within a function, if so, then proceed as normal
473 478
                         if (strpos($up_to_distinct_str,"(")) {
474 479
                             //proceed as normal
475 480
                             $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
476
-                        }
477
-                        else {
481
+                        } else {
478 482
                             //if distinct is not within a function, then parse
479 483
                             //string contains distinct clause, "TOP needs to come after Distinct"
480 484
                             //get position of distinct
@@ -556,8 +560,7 @@  discard block
 block discarded – undo
556 560
                                                 group by " . $grpByStr . "
557 561
                                         ) AS a
558 562
                                         WHERE row_number > $start";
559
-                        }
560
-                        else {
563
+                        } else {
561 564
                         $newSQL = "SELECT TOP $count * FROM
562 565
                                     (
563 566
                                         " . $matches[1] . " ROW_NUMBER()
@@ -566,7 +569,7 @@  discard block
 block discarded – undo
566 569
                                     ) AS a
567 570
                                     WHERE row_number > $start";
568 571
                         }
569
-                    }else{
572
+                    } else{
570 573
                         //if there is a distinct clause, form query with rownumber after distinct
571 574
                         if ($hasDistinct) {
572 575
                              $newSQL = "SELECT TOP $count * FROM
@@ -577,8 +580,7 @@  discard block
 block discarded – undo
577 580
                                             )
578 581
                                             AS a
579 582
                                             WHERE row_number > $start";
580
-                        }
581
-                        else {
583
+                        } else {
582 584
                              $newSQL = "SELECT TOP $count * FROM
583 585
                                            (
584 586
                                   " . $matches[1] . " ROW_NUMBER() OVER (ORDER BY " . $sqlArray['FROM'][0]['alias'] . ".id) AS row_number, " . $matches[2] . $matches[3]. "
@@ -617,8 +619,9 @@  discard block
 block discarded – undo
617 619
         //strip all single quotes out
618 620
         $count = substr_count ( $p_sql, $strip_beg);
619 621
         $increment = 1;
620
-        if ($strip_beg != $strip_end)
621
-            $increment = 2;
622
+        if ($strip_beg != $strip_end) {
623
+                    $increment = 2;
624
+        }
622 625
 
623 626
         $i=0;
624 627
         $offset = 0;
@@ -780,9 +783,10 @@  discard block
 block discarded – undo
780 783
     {
781 784
         $sql = strtolower($sql);
782 785
         $orig_order_match = trim($orig_order_match);
783
-        if (strpos($orig_order_match, ".") != 0)
784
-            //this has a tablename defined, pass in the order match
786
+        if (strpos($orig_order_match, ".") != 0) {
787
+                    //this has a tablename defined, pass in the order match
785 788
             return $orig_order_match;
789
+        }
786 790
 
787 791
         // If there is no ordering direction (ASC/DESC), use ASC by default
788 792
         if (strpos($orig_order_match, " ") === false) {
@@ -824,15 +828,15 @@  discard block
 block discarded – undo
824 828
             //break out of here, log this
825 829
             $GLOBALS['log']->debug("No match was found for order by, pass string back untouched as: $orig_order_match");
826 830
             return $orig_order_match;
827
-        }
828
-        else {
831
+        } else {
829 832
             //if found, then parse and return
830 833
             //grab string up to the aliased column
831 834
             $GLOBALS['log']->debug("order by found, process sql string");
832 835
 
833 836
             $psql = (trim($this->getAliasFromSQL($sql, $orderMatch )));
834
-            if (empty($psql))
835
-                $psql = trim(substr($sql, 0, $found_in_sql));
837
+            if (empty($psql)) {
838
+                            $psql = trim(substr($sql, 0, $found_in_sql));
839
+            }
836 840
 
837 841
             //grab the last comma before the alias
838 842
             preg_match('/\s+' . trim($orderMatch). '/', $psql, $match, PREG_OFFSET_CAPTURE);
@@ -845,8 +849,9 @@  discard block
 block discarded – undo
845 849
             //this is especially true for unified search from home screen
846 850
 
847 851
             $alias_beg_pos = 0;
848
-            if(strpos($psql, " as "))
849
-                $alias_beg_pos = strpos($psql, " as ");
852
+            if(strpos($psql, " as ")) {
853
+                            $alias_beg_pos = strpos($psql, " as ");
854
+            }
850 855
 
851 856
             // Bug # 44923 - This breaks the query and does not properly filter isnull
852 857
             // as there are other functions such as ltrim and rtrim.
@@ -883,8 +888,9 @@  discard block
 block discarded – undo
883 888
         //correct table name.
884 889
         if (($module_str != 'Reports' && $module_str != 'SavedReport') && isset($beanList[$module_str])  &&  isset($beanFiles[$beanList[$module_str]])){
885 890
             //if the class is not already loaded, then load files
886
-            if (!class_exists($beanList[$module_str]))
887
-                require_once($beanFiles[$beanList[$module_str]]);
891
+            if (!class_exists($beanList[$module_str])) {
892
+                            require_once($beanFiles[$beanList[$module_str]]);
893
+            }
888 894
 
889 895
             //instantiate new bean
890 896
             $module_bean = new $beanList[$module_str]();
@@ -897,8 +903,7 @@  discard block
 block discarded – undo
897 903
                 $GLOBALS['log']->debug("Could not find table name for module $module_str. ");
898 904
                 $tbl_name = $module_str;
899 905
             }
900
-        }
901
-        else {
906
+        } else {
902 907
             //since the module does NOT exist in beanlist, then we have to parse the string
903 908
             //and grab the table name from the passed in sql
904 909
             $GLOBALS['log']->debug("Could not find table name from module in request, retrieve from passed in sql");
@@ -919,8 +924,9 @@  discard block
 block discarded – undo
919 924
                 // MFH BUG #14009: Also check to see if there are any carriage returns before the next space so that we don't grab any arbitrary joins or other tables.
920 925
                 $carriage_ret = strpos($tableEnd,"\n");
921 926
                 $next_space = strpos($tableEnd," " );
922
-                if ($carriage_ret < $next_space)
923
-                    $next_space = $carriage_ret;
927
+                if ($carriage_ret < $next_space) {
928
+                                    $next_space = $carriage_ret;
929
+                }
924 930
                 if ($next_space > 0) {
925 931
                     $tbl_name= substr($tableEnd,0, $next_space);
926 932
                     if(empty($tbl_name)){
@@ -943,18 +949,17 @@  discard block
 block discarded – undo
943 949
                         || $alias_tbl_name == "outer"
944 950
                         || $alias_tbl_name == "right") {
945 951
                         //not aliased, do nothing
946
-                    }
947
-                    elseif ($alias_tbl_name == "as") {
952
+                    } elseif ($alias_tbl_name == "as") {
948 953
                             //the next word is the table name
949 954
                             $aliasTableEnd = trim(substr($aliasTableEnd, $alias_space));
950 955
                             $alias_space = strpos ($aliasTableEnd, " " );
951 956
                             if ($alias_space > 0) {
952 957
                                 $alias_tbl_name= trim(substr($aliasTableEnd,0, $alias_space));
953
-                                if (!empty($alias_tbl_name))
954
-                                    $tbl_name = $alias_tbl_name;
958
+                                if (!empty($alias_tbl_name)) {
959
+                                                                    $tbl_name = $alias_tbl_name;
960
+                                }
955 961
                             }
956
-                    }
957
-                    else {
962
+                    } else {
958 963
                         //this is table alias
959 964
                         $tbl_name = $alias_tbl_name;
960 965
                     }
@@ -974,16 +979,19 @@  discard block
 block discarded – undo
974 979
 	{
975 980
 		$field_array = array();
976 981
 
977
-		if(! isset($result) || empty($result))
978
-            return 0;
982
+		if(! isset($result) || empty($result)) {
983
+		            return 0;
984
+		}
979 985
 
980 986
         $i = 0;
981 987
         while ($i < mssql_num_fields($result)) {
982 988
             $meta = mssql_fetch_field($result, $i);
983
-            if (!$meta)
984
-                return 0;
985
-            if($make_lower_case==true)
986
-                $meta->name = strtolower($meta->name);
989
+            if (!$meta) {
990
+                            return 0;
991
+            }
992
+            if($make_lower_case==true) {
993
+                            $meta->name = strtolower($meta->name);
994
+            }
987 995
 
988 996
             $field_array[] = $meta->name;
989 997
 
@@ -1006,7 +1014,9 @@  discard block
 block discarded – undo
1006 1014
 	 */
1007 1015
 	public function fetchRow($result)
1008 1016
 	{
1009
-		if (empty($result))	return false;
1017
+		if (empty($result)) {
1018
+		    return false;
1019
+		}
1010 1020
 
1011 1021
         $row = mssql_fetch_assoc($result);
1012 1022
         //MSSQL returns a space " " when a varchar column is empty ("") and not null.
@@ -1088,8 +1098,9 @@  discard block
 block discarded – undo
1088 1098
             $tables = array();
1089 1099
             $r = $this->query('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES');
1090 1100
             if (is_resource($r)) {
1091
-                while ($a = $this->fetchByAssoc($r))
1092
-                    $tables[] = $a['TABLE_NAME'];
1101
+                while ($a = $this->fetchByAssoc($r)) {
1102
+                                    $tables[] = $a['TABLE_NAME'];
1103
+                }
1093 1104
 
1094 1105
                 return $tables;
1095 1106
             }
@@ -1246,12 +1257,14 @@  discard block
 block discarded – undo
1246 1257
      */
1247 1258
 	public function createTableSQLParams($tablename, $fieldDefs, $indices)
1248 1259
     {
1249
-        if (empty($tablename) || empty($fieldDefs))
1250
-            return '';
1260
+        if (empty($tablename) || empty($fieldDefs)) {
1261
+                    return '';
1262
+        }
1251 1263
 
1252 1264
         $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
1253
-        if (empty($columns))
1254
-            return '';
1265
+        if (empty($columns)) {
1266
+                    return '';
1267
+        }
1255 1268
 
1256 1269
         return "CREATE TABLE $tablename ($columns)";
1257 1270
     }
@@ -1263,7 +1276,9 @@  discard block
 block discarded – undo
1263 1276
     public function isTextType($type)
1264 1277
     {
1265 1278
         $type = strtolower($type);
1266
-        if(!isset($this->type_map[$type])) return false;
1279
+        if(!isset($this->type_map[$type])) {
1280
+            return false;
1281
+        }
1267 1282
         return in_array($this->type_map[$type], array('ntext','text','image', 'nvarchar(max)'));
1268 1283
     }
1269 1284
 
@@ -1316,8 +1331,9 @@  discard block
 block discarded – undo
1316 1331
             $f_def  = $this->oneColumnSQLRep($def, $ignoreRequired,$tablename, true);
1317 1332
             $f_stmt = "ALTER COLUMN ".$f_def['name'].' '.$f_def['colType'].' '.
1318 1333
                         $f_def['required'].' '.$f_def['auto_increment']."\n";
1319
-            if (!empty( $f_def['default']))
1320
-                $f_stmt .= " ALTER TABLE " . $tablename .  " ADD  ". $f_def['default'] . " FOR " . $def['name'];
1334
+            if (!empty( $f_def['default'])) {
1335
+                            $f_stmt .= " ALTER TABLE " . $tablename .  " ADD  ". $f_def['default'] . " FOR " . $def['name'];
1336
+            }
1321 1337
             return $f_stmt;
1322 1338
             break;
1323 1339
         default:
@@ -1355,8 +1371,7 @@  discard block
 block discarded – undo
1355 1371
 
1356 1372
           		$columns[] = $this->alterSQLRep($action, $def, $ignoreRequired,$tablename);
1357 1373
       		}
1358
-        }
1359
-        else {
1374
+        } else {
1360 1375
             //if the column is being modified drop the default value
1361 1376
       		//constraint if it exists. alterSQLRep will add the constraint back
1362 1377
       		if (!empty($constraints[$fieldDefs['name']])) {
@@ -1391,8 +1406,9 @@  discard block
 block discarded – undo
1391 1406
      */
1392 1407
     public function setAutoIncrementStart($table, $field_name, $start_value)
1393 1408
     {
1394
-        if($start_value > 1)
1395
-            $start_value -= 1;
1409
+        if($start_value > 1) {
1410
+                    $start_value -= 1;
1411
+        }
1396 1412
 		$this->query("DBCC CHECKIDENT ('$table', RESEED, $start_value) WITH NO_INFOMSGS");
1397 1413
         return true;
1398 1414
     }
@@ -1428,10 +1444,11 @@  discard block
 block discarded – undo
1428 1444
         $indices = array();
1429 1445
         while (($row=$this->fetchByAssoc($result)) != null) {
1430 1446
             $index_type = 'index';
1431
-            if ($row['is_primary_key'] == '1')
1432
-                $index_type = 'primary';
1433
-            elseif ($row['is_unique'] == 1 )
1434
-                $index_type = 'unique';
1447
+            if ($row['is_primary_key'] == '1') {
1448
+                            $index_type = 'primary';
1449
+            } elseif ($row['is_unique'] == 1 ) {
1450
+                            $index_type = 'unique';
1451
+            }
1435 1452
             $name = strtolower($row['index_name']);
1436 1453
             $indices[$name]['name']     = $name;
1437 1454
             $indices[$name]['type']     = $index_type;
@@ -1456,18 +1473,19 @@  discard block
 block discarded – undo
1456 1473
             if ( $row['TYPE_NAME'] == 'decimal' ) {
1457 1474
                 $columns[$column_name]['len']=strtolower($row['PRECISION']);
1458 1475
                 $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
1476
+            } elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) ) {
1477
+							$columns[$column_name]['len']=strtolower($row['PRECISION']);
1478
+			} elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) ) {
1479
+                            $columns[$column_name]['len']=strtolower($row['LENGTH']);
1459 1480
             }
1460
-			elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) )
1461
-				$columns[$column_name]['len']=strtolower($row['PRECISION']);
1462
-            elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) )
1463
-                $columns[$column_name]['len']=strtolower($row['LENGTH']);
1464 1481
             if ( stristr($row['TYPE_NAME'],'identity') ) {
1465 1482
                 $columns[$column_name]['auto_increment'] = '1';
1466 1483
                 $columns[$column_name]['type']=str_replace(' identity','',strtolower($row['TYPE_NAME']));
1467 1484
             }
1468 1485
 
1469
-            if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI')))
1470
-                $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
1486
+            if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI'))) {
1487
+                            $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
1488
+            }
1471 1489
 
1472 1490
             $column_def = 1;
1473 1491
             if ( strtolower($tablename) == 'relationships' ) {
@@ -1476,12 +1494,13 @@  discard block
 block discarded – undo
1476 1494
             if ( $column_def != 0 && ($row['COLUMN_DEF'] != null)) {	// NOTE Not using !empty as an empty string may be a viable default value.
1477 1495
                 $matches = array();
1478 1496
                 $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'],ENT_QUOTES);
1479
-                if ( preg_match('/\([\(|\'](.*)[\)|\']\)/i',$row['COLUMN_DEF'],$matches) )
1480
-                    $columns[$column_name]['default'] = $matches[1];
1481
-                elseif ( preg_match('/\(N\'(.*)\'\)/i',$row['COLUMN_DEF'],$matches) )
1482
-                    $columns[$column_name]['default'] = $matches[1];
1483
-                else
1484
-                    $columns[$column_name]['default'] = $row['COLUMN_DEF'];
1497
+                if ( preg_match('/\([\(|\'](.*)[\)|\']\)/i',$row['COLUMN_DEF'],$matches) ) {
1498
+                                    $columns[$column_name]['default'] = $matches[1];
1499
+                } elseif ( preg_match('/\(N\'(.*)\'\)/i',$row['COLUMN_DEF'],$matches) ) {
1500
+                                    $columns[$column_name]['default'] = $matches[1];
1501
+                } else {
1502
+                                    $columns[$column_name]['default'] = $row['COLUMN_DEF'];
1503
+                }
1485 1504
             }
1486 1505
         }
1487 1506
         return $columns;
@@ -1513,53 +1532,61 @@  discard block
 block discarded – undo
1513 1532
         // generic indices
1514 1533
         case 'index':
1515 1534
         case 'alternate_key':
1516
-            if ($drop)
1517
-                $sql = "DROP INDEX {$name} ON {$table}";
1518
-            else
1519
-                $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
1535
+            if ($drop) {
1536
+                            $sql = "DROP INDEX {$name} ON {$table}";
1537
+            } else {
1538
+                            $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
1539
+            }
1520 1540
             break;
1521 1541
         case 'clustered':
1522
-            if ($drop)
1523
-                $sql = "DROP INDEX {$name} ON {$table}";
1524
-            else
1525
-                $sql = "CREATE CLUSTERED INDEX $name ON $table ($fields)";
1542
+            if ($drop) {
1543
+                            $sql = "DROP INDEX {$name} ON {$table}";
1544
+            } else {
1545
+                            $sql = "CREATE CLUSTERED INDEX $name ON $table ($fields)";
1546
+            }
1526 1547
             break;
1527 1548
             // constraints as indices
1528 1549
         case 'unique':
1529
-            if ($drop)
1530
-                $sql = "ALTER TABLE {$table} DROP CONSTRAINT $name";
1531
-            else
1532
-                $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE ({$fields})";
1550
+            if ($drop) {
1551
+                            $sql = "ALTER TABLE {$table} DROP CONSTRAINT $name";
1552
+            } else {
1553
+                            $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE ({$fields})";
1554
+            }
1533 1555
             break;
1534 1556
         case 'primary':
1535
-            if ($drop)
1536
-                $sql = "ALTER TABLE {$table} DROP CONSTRAINT {$name}";
1537
-            else
1538
-                $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} PRIMARY KEY ({$fields})";
1557
+            if ($drop) {
1558
+                            $sql = "ALTER TABLE {$table} DROP CONSTRAINT {$name}";
1559
+            } else {
1560
+                            $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} PRIMARY KEY ({$fields})";
1561
+            }
1539 1562
             break;
1540 1563
         case 'foreign':
1541
-            if ($drop)
1542
-                $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
1543
-            else
1544
-                $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name}  FOREIGN KEY ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignFields']})";
1564
+            if ($drop) {
1565
+                            $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
1566
+            } else {
1567
+                            $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name}  FOREIGN KEY ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignFields']})";
1568
+            }
1545 1569
             break;
1546 1570
         case 'fulltext':
1547 1571
             if ($this->full_text_indexing_enabled() && $drop) {
1548 1572
                 $sql = "DROP FULLTEXT INDEX ON {$table}";
1549 1573
             } elseif ($this->full_text_indexing_enabled()) {
1550 1574
                 $catalog_name=$this->ftsCatalogName();
1551
-                if ( isset($definition['catalog_name']) && $definition['catalog_name'] != 'default')
1552
-                    $catalog_name = $definition['catalog_name'];
1575
+                if ( isset($definition['catalog_name']) && $definition['catalog_name'] != 'default') {
1576
+                                    $catalog_name = $definition['catalog_name'];
1577
+                }
1553 1578
 
1554 1579
                 $language = "Language 1033";
1555
-                if (isset($definition['language']) && !empty($definition['language']))
1556
-                    $language = "Language " . $definition['language'];
1580
+                if (isset($definition['language']) && !empty($definition['language'])) {
1581
+                                    $language = "Language " . $definition['language'];
1582
+                }
1557 1583
 
1558 1584
                 $key_index = $definition['key_index'];
1559 1585
 
1560 1586
                 $change_tracking = "auto";
1561
-                if (isset($definition['change_tracking']) && !empty($definition['change_tracking']))
1562
-                    $change_tracking = $definition['change_tracking'];
1587
+                if (isset($definition['change_tracking']) && !empty($definition['change_tracking'])) {
1588
+                                    $change_tracking = $definition['change_tracking'];
1589
+                }
1563 1590
 
1564 1591
                 $sql = " CREATE FULLTEXT INDEX ON $table ($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
1565 1592
             }
@@ -1585,12 +1612,14 @@  discard block
 block discarded – undo
1585 1612
     protected function full_text_indexing_enabled($dbname = null)
1586 1613
     {
1587 1614
         // check to see if we already have install setting in session
1588
-    	if(!isset($_SESSION['IsFulltextInstalled']))
1589
-            $_SESSION['IsFulltextInstalled'] = $this->full_text_indexing_installed();
1615
+    	if(!isset($_SESSION['IsFulltextInstalled'])) {
1616
+    	            $_SESSION['IsFulltextInstalled'] = $this->full_text_indexing_installed();
1617
+    	}
1590 1618
 
1591 1619
         // check to see if FTS Indexing service is installed
1592
-        if(empty($_SESSION['IsFulltextInstalled']))
1593
-            return false;
1620
+        if(empty($_SESSION['IsFulltextInstalled'])) {
1621
+                    return false;
1622
+        }
1594 1623
 
1595 1624
         // grab the dbname if it was not passed through
1596 1625
 		if (empty($dbname)) {
@@ -1639,8 +1668,9 @@  discard block
 block discarded – undo
1639 1668
     {
1640 1669
         static $results = array();
1641 1670
 
1642
-        if ( empty($column) && isset($results[$table]) )
1643
-            return $results[$table];
1671
+        if ( empty($column) && isset($results[$table]) ) {
1672
+                    return $results[$table];
1673
+        }
1644 1674
 
1645 1675
         $query = <<<EOQ
1646 1676
 select s.name, o.name, c.name dtrt, d.name ctrt
@@ -1653,18 +1683,20 @@  discard block
 block discarded – undo
1653 1683
             on s.schema_id = o.schema_id
1654 1684
     where o.name = '$table'
1655 1685
 EOQ;
1656
-        if ( !empty($column) )
1657
-            $query .= " and c.name = '$column'";
1686
+        if ( !empty($column) ) {
1687
+                    $query .= " and c.name = '$column'";
1688
+        }
1658 1689
         $res = $this->query($query);
1659 1690
         if ( !empty($column) ) {
1660 1691
             $row = $this->fetchByAssoc($res);
1661
-            if (!empty($row))
1662
-                return $row['ctrt'];
1663
-        }
1664
-        else {
1692
+            if (!empty($row)) {
1693
+                            return $row['ctrt'];
1694
+            }
1695
+        } else {
1665 1696
             $returnResult = array();
1666
-            while ( $row = $this->fetchByAssoc($res) )
1667
-                $returnResult[$row['dtrt']] = $row['ctrt'];
1697
+            while ( $row = $this->fetchByAssoc($res) ) {
1698
+                            $returnResult[$row['dtrt']] = $row['ctrt'];
1699
+            }
1668 1700
             $results[$table] = $returnResult;
1669 1701
             return $returnResult;
1670 1702
         }
@@ -1679,8 +1711,9 @@  discard block
 block discarded – undo
1679 1711
     {
1680 1712
         parent::massageFieldDef($fieldDef,$tablename);
1681 1713
 
1682
-        if ($fieldDef['type'] == 'int')
1683
-            $fieldDef['len'] = '4';
1714
+        if ($fieldDef['type'] == 'int') {
1715
+                    $fieldDef['len'] = '4';
1716
+        }
1684 1717
 
1685 1718
         if(empty($fieldDef['len']))
1686 1719
         {
@@ -1709,9 +1742,10 @@  discard block
 block discarded – undo
1709 1742
         {
1710 1743
             $fieldDef['default'] = '0';
1711 1744
         }
1712
-		if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']) )
1713
-			$fieldDef['default'] = '';
1714
-//        if ($fieldDef['type'] == 'bit' && empty($fieldDef['len']) )
1745
+		if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']) ) {
1746
+					$fieldDef['default'] = '';
1747
+		}
1748
+		//        if ($fieldDef['type'] == 'bit' && empty($fieldDef['len']) )
1715 1749
 //            $fieldDef['len'] = '1';
1716 1750
 //		if ($fieldDef['type'] == 'bool' && empty($fieldDef['len']) )
1717 1751
 //            $fieldDef['len'] = '1';
@@ -1755,13 +1789,15 @@  discard block
 block discarded – undo
1755 1789
 		$ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
1756 1790
 
1757 1791
 		// Bug 24307 - Don't add precision for float fields.
1758
-		if ( stristr($ref['colType'],'float') )
1759
-			$ref['colType'] = preg_replace('/(,\d+)/','',$ref['colType']);
1792
+		if ( stristr($ref['colType'],'float') ) {
1793
+					$ref['colType'] = preg_replace('/(,\d+)/','',$ref['colType']);
1794
+		}
1760 1795
 
1761
-        if ( $return_as_array )
1762
-            return $ref;
1763
-        else
1764
-            return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
1796
+        if ( $return_as_array ) {
1797
+                    return $ref;
1798
+        } else {
1799
+                    return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
1800
+        }
1765 1801
 	}
1766 1802
 
1767 1803
     /**
@@ -1799,8 +1835,9 @@  discard block
 block discarded – undo
1799 1835
      */
1800 1836
     protected function freeDbResult($dbResult)
1801 1837
     {
1802
-        if(!empty($dbResult))
1803
-            mssql_free_result($dbResult);
1838
+        if(!empty($dbResult)) {
1839
+                    mssql_free_result($dbResult);
1840
+        }
1804 1841
     }
1805 1842
 
1806 1843
 	/**
@@ -1810,7 +1847,9 @@  discard block
 block discarded – undo
1810 1847
     public function lastDbError()
1811 1848
     {
1812 1849
         $sqlmsg = mssql_get_last_message();
1813
-        if(empty($sqlmsg)) return false;
1850
+        if(empty($sqlmsg)) {
1851
+            return false;
1852
+        }
1814 1853
         global $app_strings;
1815 1854
         if (empty($app_strings)
1816 1855
 		    or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
@@ -1833,11 +1872,11 @@  discard block
 block discarded – undo
1833 1872
                 //only if connection if made before languge is set.
1834 1873
                 $GLOBALS['log']->debug("Ignoring this database message: " . $sqlmsg);
1835 1874
                 return false;
1836
-            }
1837
-            else {
1875
+            } else {
1838 1876
                 $sqlpos = strpos($sqlmsg, $app_strings['ERR_MSSQL_DB_CONTEXT']);
1839
-                if ( $sqlpos !== false )
1840
-                    return false;
1877
+                if ( $sqlpos !== false ) {
1878
+                                    return false;
1879
+                }
1841 1880
             }
1842 1881
         }
1843 1882
 
@@ -1882,8 +1921,9 @@  discard block
 block discarded – undo
1882 1921
     protected function _appendN($sql)
1883 1922
     {
1884 1923
         // If there are no single quotes, don't bother, will just assume there is no character data
1885
-        if (strpos($sql, "'") === false)
1886
-            return $sql;
1924
+        if (strpos($sql, "'") === false) {
1925
+                    return $sql;
1926
+        }
1887 1927
 
1888 1928
         // Flag if there are odd number of single quotes, just continue without trying to append N
1889 1929
         if ((substr_count($sql, "'") & 1)) {
@@ -1922,14 +1962,17 @@  discard block
 block discarded – undo
1922 1962
             }
1923 1963
         }
1924 1964
 
1925
-        if (!empty($replace))
1926
-            $sql = str_replace(array_keys($replace), $replace, $sql);
1965
+        if (!empty($replace)) {
1966
+                    $sql = str_replace(array_keys($replace), $replace, $sql);
1967
+        }
1927 1968
 
1928
-        if (!empty($pairs))
1929
-            $sql = str_replace(array_keys($pairs), $pairs, $sql);
1969
+        if (!empty($pairs)) {
1970
+                    $sql = str_replace(array_keys($pairs), $pairs, $sql);
1971
+        }
1930 1972
 
1931
-        if(strpos($sql, "<@#@#@PAIR@#@#@>"))
1932
-            $sql = str_replace(array('<@#@#@PAIR@#@#@>'), array("''"), $sql);
1973
+        if(strpos($sql, "<@#@#@PAIR@#@#@>")) {
1974
+                    $sql = str_replace(array('<@#@#@PAIR@#@#@>'), array("''"), $sql);
1975
+        }
1933 1976
 
1934 1977
         return $sql;
1935 1978
     }
Please login to merge, or discard this patch.
Spacing   +254 added lines, -254 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,11 +175,11 @@  discard block
 block discarded – undo
175 175
         ini_set('mssql.datetimeconvert', '0');
176 176
 
177 177
         //set the text size and textlimit to max number so that blob columns are not truncated
178
-        ini_set('mssql.textlimit','2147483647');
179
-        ini_set('mssql.textsize','2147483647');
180
-        ini_set('mssql.charset','UTF-8');
178
+        ini_set('mssql.textlimit', '2147483647');
179
+        ini_set('mssql.textsize', '2147483647');
180
+        ini_set('mssql.charset', 'UTF-8');
181 181
 
182
-        if(!empty($configOptions['db_host_instance'])) {
182
+        if (!empty($configOptions['db_host_instance'])) {
183 183
             $configOptions['db_host_instance'] = trim($configOptions['db_host_instance']);
184 184
         }
185 185
         //set the connections parameters
@@ -191,37 +191,37 @@  discard block
 block discarded – undo
191 191
 
192 192
         //create persistent connection
193 193
         if ($this->getOption('persistent')) {
194
-            $this->database =@mssql_pconnect(
195
-                $connect_param ,
194
+            $this->database = @mssql_pconnect(
195
+                $connect_param,
196 196
                 $configOptions['db_user_name'],
197 197
                 $configOptions['db_password']
198 198
                 );
199 199
         }
200 200
         //if no persistent connection created, then create regular connection
201
-        if(!$this->database){
201
+        if (!$this->database) {
202 202
             $this->database = mssql_connect(
203
-                    $connect_param ,
203
+                    $connect_param,
204 204
                     $configOptions['db_user_name'],
205 205
                     $configOptions['db_password']
206 206
                     );
207
-            if(!$this->database){
207
+            if (!$this->database) {
208 208
                 $GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name'].
209 209
                     " as ".$configOptions['db_user_name'].".");
210
-                if($dieOnError) {
210
+                if ($dieOnError) {
211 211
                     sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
212 212
                 } else {
213 213
                     return false;
214 214
                 }
215 215
             }
216
-            if($this->database && $this->getOption('persistent')){
216
+            if ($this->database && $this->getOption('persistent')) {
217 217
                 $_SESSION['administrator_error'] = "<B>Severe Performance Degradation: Persistent Database Connections "
218 218
                     . "not working.  Please set \$sugar_config['dbconfigoption']['persistent'] to false in your "
219 219
                     . "config.php file</B>";
220 220
             }
221 221
         }
222 222
         //make sure connection exists
223
-        if(!$this->database) {
224
-                if($dieOnError) {
223
+        if (!$this->database) {
224
+                if ($dieOnError) {
225 225
                     sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
226 226
                 } else {
227 227
                     return false;
@@ -235,19 +235,19 @@  discard block
 block discarded – undo
235 235
         //mssql db maximum number of 5 times at the interval of .2 second. If can not connect
236 236
         //it will throw an Unable to select database message.
237 237
 
238
-        if(!empty($configOptions['db_name']) && !@mssql_select_db($configOptions['db_name'], $this->database)){
238
+        if (!empty($configOptions['db_name']) && !@mssql_select_db($configOptions['db_name'], $this->database)) {
239 239
 			$connected = false;
240
-			for($i=0;$i<5;$i++){
240
+			for ($i = 0; $i < 5; $i++) {
241 241
 				usleep(200000);
242
-				if(@mssql_select_db($configOptions['db_name'], $this->database)){
242
+				if (@mssql_select_db($configOptions['db_name'], $this->database)) {
243 243
 					$connected = true;
244 244
 					break;
245 245
 				}
246 246
 			}
247
-			if(!$connected){
248
-			    $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}");
249
-                if($dieOnError) {
250
-                    if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
247
+			if (!$connected) {
248
+			    $GLOBALS['log']->fatal("Unable to select database {$configOptions['db_name']}");
249
+                if ($dieOnError) {
250
+                    if (isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
251 251
                         sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
252 252
                     } else {
253 253
                         sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 			}
259 259
          }
260 260
 
261
-        if(!$this->checkError('Could Not Connect', $dieOnError))
261
+        if (!$this->checkError('Could Not Connect', $dieOnError))
262 262
             $GLOBALS['log']->info("connected to db");
263 263
 
264 264
         $this->connectOptions = $configOptions;
@@ -280,16 +280,16 @@  discard block
 block discarded – undo
280 280
 	 */
281 281
 	public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
282 282
     {
283
-        if(is_array($sql)) {
283
+        if (is_array($sql)) {
284 284
             return $this->queryArray($sql, $dieOnError, $msg, $suppress);
285 285
         }
286 286
         // Flag if there are odd number of single quotes
287 287
         if ((substr_count($sql, "'") & 1))
288
-            $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
288
+            $GLOBALS['log']->error("SQL statement[".$sql."] has odd number of single quotes.");
289 289
 
290 290
 		$sql = $this->_appendN($sql);
291 291
 
292
-        $GLOBALS['log']->info('Query:' . $sql);
292
+        $GLOBALS['log']->info('Query:'.$sql);
293 293
         $this->checkConnection();
294 294
         $this->countQuery($sql);
295 295
         $this->query_time = microtime(true);
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
         // Bug 34892 - Clear out previous error message by checking the @@ERROR global variable
298 298
 		@mssql_query("SELECT @@ERROR", $this->database);
299 299
 
300
-        $result = $suppress?@mssql_query($sql, $this->database):mssql_query($sql, $this->database);
300
+        $result = $suppress ? @mssql_query($sql, $this->database) : mssql_query($sql, $this->database);
301 301
 
302 302
         if (!$result) {
303 303
             // awu Bug 10657: ignoring mssql error message 'Changed database context to' - an intermittent
@@ -309,13 +309,13 @@  discard block
 block discarded – undo
309 309
 			$sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
310 310
 
311 311
 			if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false)		// if sqlmsg has 'Changed database context to', just log it
312
-				$GLOBALS['log']->debug($sqlmsg . ": " . $sql );
312
+				$GLOBALS['log']->debug($sqlmsg.": ".$sql);
313 313
 			else {
314
-				$GLOBALS['log']->fatal($sqlmsg . ": " . $sql );
315
-				if($dieOnError)
316
-					sugar_die('SQL Error : ' . $sqlmsg);
314
+				$GLOBALS['log']->fatal($sqlmsg.": ".$sql);
315
+				if ($dieOnError)
316
+					sugar_die('SQL Error : '.$sqlmsg);
317 317
 				else
318
-					echo 'SQL Error : ' . $sqlmsg;
318
+					echo 'SQL Error : '.$sqlmsg;
319 319
 			}
320 320
         }
321 321
 
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
         $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
324 324
 
325 325
 
326
-        $this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
326
+        $this->checkError($msg.' Query Failed: '.$sql, $dieOnError);
327 327
 
328 328
         return $result;
329 329
     }
@@ -341,14 +341,14 @@  discard block
 block discarded – undo
341 341
     {
342 342
         //set the start to 0, no negs
343 343
         if ($start < 0)
344
-            $start=0;
344
+            $start = 0;
345 345
 
346
-        $GLOBALS['log']->debug(print_r(func_get_args(),true));
346
+        $GLOBALS['log']->debug(print_r(func_get_args(), true));
347 347
 
348 348
         $this->lastsql = $sql;
349 349
 
350 350
         //change the casing to lower for easier string comparison, and trim whitespaces
351
-        $sql = strtolower(trim($sql)) ;
351
+        $sql = strtolower(trim($sql));
352 352
 
353 353
         //set default sql
354 354
         $limitUnionSQL = $sql;
@@ -364,16 +364,16 @@  discard block
 block discarded – undo
364 364
         $arr_count = 0;
365 365
 
366 366
         //process if there are elements
367
-        if ($unionOrderByCount){
367
+        if ($unionOrderByCount) {
368 368
             //we really want the last order by, so reconstruct string
369 369
             //adding a 1 to count, as we dont wish to process the last element
370 370
             $unionsql = '';
371
-            while ($unionOrderByCount>$arr_count+1) {
371
+            while ($unionOrderByCount > $arr_count + 1) {
372 372
                 $unionsql .= $orderByArray[$arr_count];
373
-                $arr_count = $arr_count+1;
373
+                $arr_count = $arr_count + 1;
374 374
                 //add an "order by" string back if we are coming into loop again
375 375
                 //remember they were taken out when array was created
376
-                if ($unionOrderByCount>$arr_count+1) {
376
+                if ($unionOrderByCount > $arr_count + 1) {
377 377
                     $unionsql .= "order by";
378 378
                 }
379 379
             }
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
         //so we do not want to strip the alias like in other queries.  Just add the "order by" string and
404 404
         //pass column name as is
405 405
         if ($unionOrderBy != '') {
406
-            $unionOrderBy = ' order by ' . $unionOrderBy;
406
+            $unionOrderBy = ' order by '.$unionOrderBy;
407 407
         }
408 408
 
409 409
         //Bug 56560, use top query in conjunction with rownumber() function
@@ -412,13 +412,13 @@  discard block
 block discarded – undo
412 412
         //If not for paging, no need to use rownumber() function
413 413
         if ($count == 1 && $start == 0)
414 414
         {
415
-            $limitUnionSQL = "SELECT TOP $count * FROM (" .$unionsql .") as top_count ".$unionOrderBy;
415
+            $limitUnionSQL = "SELECT TOP $count * FROM (".$unionsql.") as top_count ".$unionOrderBy;
416 416
         }
417 417
         else
418 418
         {
419 419
             $limitUnionSQL = "SELECT TOP $count * FROM( select ROW_NUMBER() OVER ( order by "
420 420
             .$rowNumOrderBy.") AS row_number, * FROM ("
421
-            .$unionsql .") As numbered) "
421
+            .$unionsql.") As numbered) "
422 422
             . "As top_count_limit WHERE row_number > $start "
423 423
             .$unionOrderBy;
424 424
         }
@@ -437,64 +437,64 @@  discard block
 block discarded – undo
437 437
         $newSQL = $sql;
438 438
         $distinctSQLARRAY = array();
439 439
         if (strpos($sql, "UNION") && !preg_match("/(')(UNION).?(')/i", $sql))
440
-            $newSQL = $this->handleUnionLimitQuery($sql,$start,$count);
440
+            $newSQL = $this->handleUnionLimitQuery($sql, $start, $count);
441 441
         else {
442 442
             if ($start < 0)
443 443
                 $start = 0;
444
-            $GLOBALS['log']->debug(print_r(func_get_args(),true));
444
+            $GLOBALS['log']->debug(print_r(func_get_args(), true));
445 445
             $this->lastsql = $sql;
446 446
             $matches = array();
447
-            preg_match('/^(.*SELECT\b)(.*?\bFROM\b.*\bWHERE\b)(.*)$/isU',$sql, $matches);
447
+            preg_match('/^(.*SELECT\b)(.*?\bFROM\b.*\bWHERE\b)(.*)$/isU', $sql, $matches);
448 448
             if (!empty($matches[3])) {
449 449
                 if ($start == 0) {
450 450
                     $match_two = strtolower($matches[2]);
451
-                    if (!strpos($match_two, "distinct")> 0 && strpos($match_two, "distinct") !==0) {
451
+                    if (!strpos($match_two, "distinct") > 0 && strpos($match_two, "distinct") !== 0) {
452 452
                         $orderByMatch = array();
453
-                        preg_match('/^(.*)(\bORDER BY\b)(.*)$/is',$matches[3], $orderByMatch);
453
+                        preg_match('/^(.*)(\bORDER BY\b)(.*)$/is', $matches[3], $orderByMatch);
454 454
                         if (!empty($orderByMatch[3])) {
455 455
                             $selectPart = array();
456 456
                             preg_match('/^(.*)(\bFROM\b.*)$/isU', $matches[2], $selectPart);
457 457
                             $newSQL = "SELECT TOP $count * FROM
458 458
                                 (
459
-                                    " . $matches[1] . $selectPart[1] . ", ROW_NUMBER()
460
-                                    OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]) . ") AS row_number
461
-                                    " . $selectPart[2] . $orderByMatch[1]. "
459
+                                    ".$matches[1].$selectPart[1].", ROW_NUMBER()
460
+                                    OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]).") AS row_number
461
+                                    " . $selectPart[2].$orderByMatch[1]."
462 462
                                 ) AS a
463 463
                                 WHERE row_number > $start";
464 464
                         }
465 465
                         else {
466
-                            $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
466
+                            $newSQL = $matches[1]." TOP $count ".$matches[2].$matches[3];
467 467
                         }
468 468
                     }
469 469
                     else {
470 470
                         $distinct_o = strpos($match_two, "distinct");
471 471
                         $up_to_distinct_str = substr($match_two, 0, $distinct_o);
472 472
                         //check to see if the distinct is within a function, if so, then proceed as normal
473
-                        if (strpos($up_to_distinct_str,"(")) {
473
+                        if (strpos($up_to_distinct_str, "(")) {
474 474
                             //proceed as normal
475
-                            $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
475
+                            $newSQL = $matches[1]." TOP $count ".$matches[2].$matches[3];
476 476
                         }
477 477
                         else {
478 478
                             //if distinct is not within a function, then parse
479 479
                             //string contains distinct clause, "TOP needs to come after Distinct"
480 480
                             //get position of distinct
481 481
                             $match_zero = strtolower($matches[0]);
482
-                            $distinct_pos = strpos($match_zero , "distinct");
482
+                            $distinct_pos = strpos($match_zero, "distinct");
483 483
                             //get position of where
484 484
                             $where_pos = strpos($match_zero, "where");
485 485
                             //parse through string
486
-                            $beg = substr($matches[0], 0, $distinct_pos+9 );
487
-                            $mid = substr($matches[0], strlen($beg), ($where_pos+5) - (strlen($beg)));
488
-                            $end = substr($matches[0], strlen($beg) + strlen($mid) );
486
+                            $beg = substr($matches[0], 0, $distinct_pos + 9);
487
+                            $mid = substr($matches[0], strlen($beg), ($where_pos + 5) - (strlen($beg)));
488
+                            $end = substr($matches[0], strlen($beg) + strlen($mid));
489 489
                             //repopulate matches array
490 490
                             $matches[1] = $beg; $matches[2] = $mid; $matches[3] = $end;
491 491
 
492
-                            $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
492
+                            $newSQL = $matches[1]." TOP $count ".$matches[2].$matches[3];
493 493
                         }
494 494
                     }
495 495
                 } else {
496 496
                     $orderByMatch = array();
497
-                    preg_match('/^(.*)(\bORDER BY\b)(.*)$/is',$matches[3], $orderByMatch);
497
+                    preg_match('/^(.*)(\bORDER BY\b)(.*)$/is', $matches[3], $orderByMatch);
498 498
 
499 499
                     //if there is a distinct clause, parse sql string as we will have to insert the rownumber
500 500
                     //for paging, AFTER the distinct clause
@@ -512,8 +512,8 @@  discard block
 block discarded – undo
512 512
 
513 513
                         //take out the select and distinct from string so we can reuse in group by
514 514
                         $dist_str = 'distinct';
515
-                        preg_match('/\b' . $dist_str . '\b/simU', $matches_sql, $matchesPartSQL, PREG_OFFSET_CAPTURE);
516
-                        $matches_sql = trim(substr($matches_sql,$matchesPartSQL[0][1] + strlen($dist_str)));
515
+                        preg_match('/\b'.$dist_str.'\b/simU', $matches_sql, $matchesPartSQL, PREG_OFFSET_CAPTURE);
516
+                        $matches_sql = trim(substr($matches_sql, $matchesPartSQL[0][1] + strlen($dist_str)));
517 517
                         //get the position of where and from for further processing
518 518
                         preg_match('/\bfrom\b/simU', $matches_sql, $matchesPartSQL, PREG_OFFSET_CAPTURE);
519 519
                         $from_pos = $matchesPartSQL[0][1];
@@ -521,17 +521,17 @@  discard block
 block discarded – undo
521 521
                         $where_pos = $matchesPartSQL[0][1];
522 522
                         //split the sql into a string before and after the from clause
523 523
                         //we will use the columns being selected to construct the group by clause
524
-                        if ($from_pos>0 ) {
524
+                        if ($from_pos > 0) {
525 525
                             $distinctSQLARRAY[0] = substr($matches_sql, 0, $from_pos);
526 526
                             $distinctSQLARRAY[1] = substr($matches_sql, $from_pos);
527 527
                             //get position of order by (if it exists) so we can strip it from the string
528 528
                             $ob_pos = strpos($distinctSQLARRAY[1], "order by");
529 529
                             if ($ob_pos) {
530
-                                $distinctSQLARRAY[1] = substr($distinctSQLARRAY[1],0,$ob_pos);
530
+                                $distinctSQLARRAY[1] = substr($distinctSQLARRAY[1], 0, $ob_pos);
531 531
                             }
532 532
 
533 533
                             // strip off last closing parentheses from the where clause
534
-                            $distinctSQLARRAY[1] = preg_replace('/\)\s$/',' ',$distinctSQLARRAY[1]);
534
+                            $distinctSQLARRAY[1] = preg_replace('/\)\s$/', ' ', $distinctSQLARRAY[1]);
535 535
                         }
536 536
 
537 537
                         $grpByStr = array();
@@ -550,30 +550,30 @@  discard block
 block discarded – undo
550 550
                             $newSQL = "SELECT TOP $count * FROM
551 551
                                         (
552 552
                                             SELECT ROW_NUMBER()
553
-                                                OVER (ORDER BY " . preg_replace('/^' . $dist_str . '\s+/', '', $this->returnOrderBy($sql, $orderByMatch[3])) . ") AS row_number,
554
-                                                count(*) counter, " . $distinctSQLARRAY[0] . "
555
-                                                " . $distinctSQLARRAY[1] . "
556
-                                                group by " . $grpByStr . "
553
+                                                OVER (ORDER BY ".preg_replace('/^'.$dist_str.'\s+/', '', $this->returnOrderBy($sql, $orderByMatch[3])).") AS row_number,
554
+                                                count(*) counter, " . $distinctSQLARRAY[0]."
555
+                                                " . $distinctSQLARRAY[1]."
556
+                                                group by " . $grpByStr."
557 557
                                         ) AS a
558 558
                                         WHERE row_number > $start";
559 559
                         }
560 560
                         else {
561 561
                         $newSQL = "SELECT TOP $count * FROM
562 562
                                     (
563
-                                        " . $matches[1] . " ROW_NUMBER()
564
-                                        OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]) . ") AS row_number,
565
-                                        " . $matches[2] . $orderByMatch[1]. "
563
+                                        ".$matches[1]." ROW_NUMBER()
564
+                                        OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]).") AS row_number,
565
+                                        " . $matches[2].$orderByMatch[1]."
566 566
                                     ) AS a
567 567
                                     WHERE row_number > $start";
568 568
                         }
569
-                    }else{
569
+                    } else {
570 570
                         //if there is a distinct clause, form query with rownumber after distinct
571 571
                         if ($hasDistinct) {
572 572
                              $newSQL = "SELECT TOP $count * FROM
573 573
                                             (
574
-                            SELECT ROW_NUMBER() OVER (ORDER BY ".$grpByStr.") AS row_number, count(*) counter, " . $distinctSQLARRAY[0] . "
575
-                                                        " . $distinctSQLARRAY[1] . "
576
-                                                    group by " . $grpByStr . "
574
+                            SELECT ROW_NUMBER() OVER (ORDER BY ".$grpByStr.") AS row_number, count(*) counter, ".$distinctSQLARRAY[0]."
575
+                                                        " . $distinctSQLARRAY[1]."
576
+                                                    group by " . $grpByStr."
577 577
                                             )
578 578
                                             AS a
579 579
                                             WHERE row_number > $start";
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
                         else {
582 582
                              $newSQL = "SELECT TOP $count * FROM
583 583
                                            (
584
-                                  " . $matches[1] . " ROW_NUMBER() OVER (ORDER BY " . $sqlArray['FROM'][0]['alias'] . ".id) AS row_number, " . $matches[2] . $matches[3]. "
584
+                                  ".$matches[1]." ROW_NUMBER() OVER (ORDER BY ".$sqlArray['FROM'][0]['alias'].".id) AS row_number, ".$matches[2].$matches[3]."
585 585
                                            )
586 586
                                            AS a
587 587
                                            WHERE row_number > $start";
@@ -591,9 +591,9 @@  discard block
 block discarded – undo
591 591
             }
592 592
         }
593 593
 
594
-        $GLOBALS['log']->debug('Limit Query: ' . $newSQL);
595
-        if($execute) {
596
-            $result =  $this->query($newSQL, $dieOnError, $msg);
594
+        $GLOBALS['log']->debug('Limit Query: '.$newSQL);
595
+        if ($execute) {
596
+            $result = $this->query($newSQL, $dieOnError, $msg);
597 597
             $this->dump_slow_queries($newSQL);
598 598
             return $result;
599 599
         } else {
@@ -615,15 +615,15 @@  discard block
 block discarded – undo
615 615
     private function removePatternFromSQL($p_sql, $strip_beg, $strip_end, $patt = 'patt')
616 616
     {
617 617
         //strip all single quotes out
618
-        $count = substr_count ( $p_sql, $strip_beg);
618
+        $count = substr_count($p_sql, $strip_beg);
619 619
         $increment = 1;
620 620
         if ($strip_beg != $strip_end)
621 621
             $increment = 2;
622 622
 
623
-        $i=0;
623
+        $i = 0;
624 624
         $offset = 0;
625 625
         $strip_array = array();
626
-        while ($i<$count && $offset<strlen($p_sql)) {
626
+        while ($i < $count && $offset < strlen($p_sql)) {
627 627
             if ($offset > strlen($p_sql))
628 628
             {
629 629
 				break;
@@ -634,23 +634,23 @@  discard block
 block discarded – undo
634 634
             {
635 635
                 break;
636 636
             }
637
-            $sec_sin = strpos($p_sql, $strip_end, $beg_sin+1);
638
-            $strip_array[$patt.$i] = substr($p_sql, $beg_sin, $sec_sin - $beg_sin +1);
637
+            $sec_sin = strpos($p_sql, $strip_end, $beg_sin + 1);
638
+            $strip_array[$patt.$i] = substr($p_sql, $beg_sin, $sec_sin - $beg_sin + 1);
639 639
             if ($increment > 1) {
640 640
                 //we are in here because beginning and end patterns are not identical, so search for nesting
641
-                $exists = strpos($strip_array[$patt.$i], $strip_beg );
642
-                if ($exists>=0) {
643
-                    $nested_pos = (strrpos($strip_array[$patt.$i], $strip_beg ));
644
-                    $strip_array[$patt.$i] = substr($p_sql,$nested_pos+$beg_sin,$sec_sin - ($nested_pos+$beg_sin)+1);
645
-                    $p_sql = substr($p_sql, 0, $nested_pos+$beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
641
+                $exists = strpos($strip_array[$patt.$i], $strip_beg);
642
+                if ($exists >= 0) {
643
+                    $nested_pos = (strrpos($strip_array[$patt.$i], $strip_beg));
644
+                    $strip_array[$patt.$i] = substr($p_sql, $nested_pos + $beg_sin, $sec_sin - ($nested_pos + $beg_sin) + 1);
645
+                    $p_sql = substr($p_sql, 0, $nested_pos + $beg_sin)." ##".$patt.$i."## ".substr($p_sql, $sec_sin + 1);
646 646
                     $i = $i + 1;
647 647
                     continue;
648 648
                 }
649 649
             }
650
-            $p_len = strlen("##". $patt.$i."##");
651
-            $p_sql = substr($p_sql, 0, $beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
650
+            $p_len = strlen("##".$patt.$i."##");
651
+            $p_sql = substr($p_sql, 0, $beg_sin)." ##".$patt.$i."## ".substr($p_sql, $sec_sin + 1);
652 652
             //move the marker up
653
-            $offset = ($sec_sin-($sec_sin-$beg_sin))+$p_len+1; // Adjusting the starting point of the marker
653
+            $offset = ($sec_sin - ($sec_sin - $beg_sin)) + $p_len + 1; // Adjusting the starting point of the marker
654 654
 
655 655
             $i = $i + 1;
656 656
         }
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
         $pattern_array = array_reverse($pattern_array);
673 673
 
674 674
         foreach ($pattern_array as $key => $replace) {
675
-            $token = str_replace( " ##".$key."## ", $replace,$token);
675
+            $token = str_replace(" ##".$key."## ", $replace, $token);
676 676
         }
677 677
 
678 678
         return $token;
@@ -688,11 +688,11 @@  discard block
 block discarded – undo
688 688
 	private function getAliasFromSQL($sql, $alias)
689 689
     {
690 690
         $matches = array();
691
-        preg_match('/^(.*SELECT)(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
691
+        preg_match('/^(.*SELECT)(.*?FROM.*WHERE)(.*)$/isU', $sql, $matches);
692 692
         //parse all single and double  quotes out of array
693
-        $sin_array = $this->removePatternFromSQL($matches[2], "'", "'","sin_");
693
+        $sin_array = $this->removePatternFromSQL($matches[2], "'", "'", "sin_");
694 694
         $new_sql = array_pop($sin_array);
695
-        $dub_array = $this->removePatternFromSQL($new_sql, "\"", "\"","dub_");
695
+        $dub_array = $this->removePatternFromSQL($new_sql, "\"", "\"", "dub_");
696 696
         $new_sql = array_pop($dub_array);
697 697
 
698 698
         //search for parenthesis
@@ -701,7 +701,7 @@  discard block
 block discarded – undo
701 701
 
702 702
         //all functions should be removed now, so split the array on commas
703 703
         $mstr_sql_array = explode(",", $new_sql);
704
-        foreach($mstr_sql_array as $token ) {
704
+        foreach ($mstr_sql_array as $token) {
705 705
             if (strpos($token, $alias)) {
706 706
                 //found token, add back comments
707 707
                 $token = $this->addPatternToSQL($token, $paren_array);
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
         $found = $found_in_sql;
740 740
 
741 741
         //if still no match found, then we need to parse through the string
742
-        if (!$found_in_sql){
742
+        if (!$found_in_sql) {
743 743
             //get count of how many times the match exists in string
744 744
             $found_count = substr_count($sql, $orderMatch);
745 745
             $i = 0;
@@ -748,21 +748,21 @@  discard block
 block discarded – undo
748 748
             //loop through string as many times as there is a match
749 749
             while ($found_count > $i) {
750 750
                 //get the first match
751
-                $found_in_sql = strpos($sql, $orderMatch,$first_);
751
+                $found_in_sql = strpos($sql, $orderMatch, $first_);
752 752
                 //make sure there was a match
753
-                if($found_in_sql){
753
+                if ($found_in_sql) {
754 754
                     //grab the next 2 individual characters
755
-                    $str_plusone = substr($sql,$found_in_sql + $len,1);
756
-                    $str_plustwo = substr($sql,$found_in_sql + $len+1,1);
755
+                    $str_plusone = substr($sql, $found_in_sql + $len, 1);
756
+                    $str_plustwo = substr($sql, $found_in_sql + $len + 1, 1);
757 757
                     //if one of those characters is a comma, then we have our alias
758
-                    if ($str_plusone === "," || $str_plustwo === ","){
758
+                    if ($str_plusone === "," || $str_plustwo === ",") {
759 759
                         //keep track of this position
760 760
                         $found = $found_in_sql;
761 761
                     }
762 762
                 }
763 763
                 //set the offset and increase the iteration counter
764
-                $first_ = $found_in_sql+$len;
765
-                $i = $i+1;
764
+                $first_ = $found_in_sql + $len;
765
+                $i = $i + 1;
766 766
             }
767 767
         }
768 768
         //return $found, defaults have been set, so if no match was found it will be a negative number
@@ -794,8 +794,8 @@  discard block
 block discarded – undo
794 794
         $firstSpace = strpos($orig_order_match, " ");
795 795
 
796 796
         //split order by into column name and ascending/descending
797
-        $orderMatch = " " . strtolower(substr($orig_order_match, 0, $firstSpace));
798
-        $asc_desc = trim(substr($orig_order_match,$firstSpace));
797
+        $orderMatch = " ".strtolower(substr($orig_order_match, 0, $firstSpace));
798
+        $asc_desc = trim(substr($orig_order_match, $firstSpace));
799 799
 
800 800
         //look for column name as an alias in sql string
801 801
         $found_in_sql = $this->findColumnByAlias($sql, $orderMatch);
@@ -806,18 +806,18 @@  discard block
 block discarded – undo
806 806
             $colMatchPos = strpos($sql, $orderMatch);
807 807
             if ($colMatchPos !== false) {
808 808
                 //grab sub string up to column name
809
-                $containsColStr = substr($sql,0, $colMatchPos);
809
+                $containsColStr = substr($sql, 0, $colMatchPos);
810 810
                 //get position of first space, so we can grab table name
811 811
                 $lastSpacePos = strrpos($containsColStr, " ");
812 812
                 //use positions of column name, space before name, and length of column to find the correct column name
813
-                $col_name = substr($sql, $lastSpacePos, $colMatchPos-$lastSpacePos+strlen($orderMatch));
813
+                $col_name = substr($sql, $lastSpacePos, $colMatchPos - $lastSpacePos + strlen($orderMatch));
814 814
 				//bug 25485. When sorting by a custom field in Account List and then pressing NEXT >, system gives an error
815 815
 				$containsCommaPos = strpos($col_name, ",");
816
-				if($containsCommaPos !== false) {
817
-					$col_name = substr($col_name, $containsCommaPos+1);
816
+				if ($containsCommaPos !== false) {
817
+					$col_name = substr($col_name, $containsCommaPos + 1);
818 818
 				}
819 819
                 //add the "asc/desc" order back
820
-                $col_name = $col_name. " ". $asc_desc;
820
+                $col_name = $col_name." ".$asc_desc;
821 821
 
822 822
                 //return column name
823 823
                 return $col_name;
@@ -831,22 +831,22 @@  discard block
 block discarded – undo
831 831
             //grab string up to the aliased column
832 832
             $GLOBALS['log']->debug("order by found, process sql string");
833 833
 
834
-            $psql = (trim($this->getAliasFromSQL($sql, $orderMatch )));
834
+            $psql = (trim($this->getAliasFromSQL($sql, $orderMatch)));
835 835
             if (empty($psql))
836 836
                 $psql = trim(substr($sql, 0, $found_in_sql));
837 837
 
838 838
             //grab the last comma before the alias
839
-            preg_match('/\s+' . trim($orderMatch). '/', $psql, $match, PREG_OFFSET_CAPTURE);
839
+            preg_match('/\s+'.trim($orderMatch).'/', $psql, $match, PREG_OFFSET_CAPTURE);
840 840
             $comma_pos = $match[0][1];
841 841
             //substring between the comma and the alias to find the joined_table alias and column name
842
-            $col_name = substr($psql,0, $comma_pos);
842
+            $col_name = substr($psql, 0, $comma_pos);
843 843
 
844 844
             //make sure the string does not have an end parenthesis
845 845
             //and is not part of a function (i.e. "ISNULL(leads.last_name,'') as name"  )
846 846
             //this is especially true for unified search from home screen
847 847
 
848 848
             $alias_beg_pos = 0;
849
-            if(strpos($psql, " as "))
849
+            if (strpos($psql, " as "))
850 850
                 $alias_beg_pos = strpos($psql, " as ");
851 851
 
852 852
             // Bug # 44923 - This breaks the query and does not properly filter isnull
@@ -855,13 +855,13 @@  discard block
 block discarded – undo
855 855
                 $alias_beg_pos = strpos($psql, " "); */
856 856
 
857 857
             if ($alias_beg_pos > 0) {
858
-                $col_name = substr($psql,0, $alias_beg_pos );
858
+                $col_name = substr($psql, 0, $alias_beg_pos);
859 859
             }
860 860
             //add the "asc/desc" order back
861
-            $col_name = $col_name. " ". $asc_desc;
861
+            $col_name = $col_name." ".$asc_desc;
862 862
 
863 863
             //pass in new order by
864
-            $GLOBALS['log']->debug("order by being returned is " . $col_name);
864
+            $GLOBALS['log']->debug("order by being returned is ".$col_name);
865 865
             return $col_name;
866 866
         }
867 867
     }
@@ -877,12 +877,12 @@  discard block
 block discarded – undo
877 877
     {
878 878
 
879 879
         global $beanList, $beanFiles;
880
-        $GLOBALS['log']->debug("Module being processed is " . $module_str);
880
+        $GLOBALS['log']->debug("Module being processed is ".$module_str);
881 881
         //get the right module files
882 882
         //the module string exists in bean list, then process bean for correct table name
883 883
         //note that we exempt the reports module from this, as queries from reporting module should be parsed for
884 884
         //correct table name.
885
-        if (($module_str != 'Reports' && $module_str != 'SavedReport') && isset($beanList[$module_str])  &&  isset($beanFiles[$beanList[$module_str]])){
885
+        if (($module_str != 'Reports' && $module_str != 'SavedReport') && isset($beanList[$module_str]) && isset($beanFiles[$beanList[$module_str]])) {
886 886
             //if the class is not already loaded, then load files
887 887
             if (!class_exists($beanList[$module_str]))
888 888
                 require_once($beanFiles[$beanList[$module_str]]);
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
             //make sure table name is not just a blank space, or empty
895 895
             $tbl_name = trim($tbl_name);
896 896
 
897
-            if(empty($tbl_name)){
897
+            if (empty($tbl_name)) {
898 898
                 $GLOBALS['log']->debug("Could not find table name for module $module_str. ");
899 899
                 $tbl_name = $module_str;
900 900
             }
@@ -911,20 +911,20 @@  discard block
 block discarded – undo
911 911
             $sql = str_replace(array("\n", "\r"), " ", $sql);
912 912
 
913 913
             //look for the location of the "from" in sql string
914
-            $fromLoc = strpos($sql," from " );
915
-            if ($fromLoc>0){
914
+            $fromLoc = strpos($sql, " from ");
915
+            if ($fromLoc > 0) {
916 916
                 //found from, substring from the " FROM " string in sql to end
917
-                $tableEnd = substr($sql, $fromLoc+6);
917
+                $tableEnd = substr($sql, $fromLoc + 6);
918 918
                 //We know that tablename will be next parameter after from, so
919 919
                 //grab the next space after table name.
920 920
                 // MFH BUG #14009: Also check to see if there are any carriage returns before the next space so that we don't grab any arbitrary joins or other tables.
921
-                $carriage_ret = strpos($tableEnd,"\n");
922
-                $next_space = strpos($tableEnd," " );
921
+                $carriage_ret = strpos($tableEnd, "\n");
922
+                $next_space = strpos($tableEnd, " ");
923 923
                 if ($carriage_ret < $next_space)
924 924
                     $next_space = $carriage_ret;
925 925
                 if ($next_space > 0) {
926
-                    $tbl_name= substr($tableEnd,0, $next_space);
927
-                    if(empty($tbl_name)){
926
+                    $tbl_name = substr($tableEnd, 0, $next_space);
927
+                    if (empty($tbl_name)) {
928 928
                         $GLOBALS['log']->debug("Could not find table name sql either, return $module_str. ");
929 929
                         $tbl_name = $module_str;
930 930
                     }
@@ -932,11 +932,11 @@  discard block
 block discarded – undo
932 932
 
933 933
                 //grab the table, to see if it is aliased
934 934
                 $aliasTableEnd = trim(substr($tableEnd, $next_space));
935
-                $alias_space = strpos ($aliasTableEnd, " " );
936
-                if ($alias_space > 0){
937
-                    $alias_tbl_name= substr($aliasTableEnd,0, $alias_space);
935
+                $alias_space = strpos($aliasTableEnd, " ");
936
+                if ($alias_space > 0) {
937
+                    $alias_tbl_name = substr($aliasTableEnd, 0, $alias_space);
938 938
                     strtolower($alias_tbl_name);
939
-                    if(empty($alias_tbl_name)
939
+                    if (empty($alias_tbl_name)
940 940
                         || $alias_tbl_name == "where"
941 941
                         || $alias_tbl_name == "inner"
942 942
                         || $alias_tbl_name == "left"
@@ -948,9 +948,9 @@  discard block
 block discarded – undo
948 948
                     elseif ($alias_tbl_name == "as") {
949 949
                             //the next word is the table name
950 950
                             $aliasTableEnd = trim(substr($aliasTableEnd, $alias_space));
951
-                            $alias_space = strpos ($aliasTableEnd, " " );
951
+                            $alias_space = strpos($aliasTableEnd, " ");
952 952
                             if ($alias_space > 0) {
953
-                                $alias_tbl_name= trim(substr($aliasTableEnd,0, $alias_space));
953
+                                $alias_tbl_name = trim(substr($aliasTableEnd, 0, $alias_space));
954 954
                                 if (!empty($alias_tbl_name))
955 955
                                     $tbl_name = $alias_tbl_name;
956 956
                             }
@@ -975,7 +975,7 @@  discard block
 block discarded – undo
975 975
 	{
976 976
 		$field_array = array();
977 977
 
978
-		if(! isset($result) || empty($result))
978
+		if (!isset($result) || empty($result))
979 979
             return 0;
980 980
 
981 981
         $i = 0;
@@ -983,7 +983,7 @@  discard block
 block discarded – undo
983 983
             $meta = mssql_fetch_field($result, $i);
984 984
             if (!$meta)
985 985
                 return 0;
986
-            if($make_lower_case==true)
986
+            if ($make_lower_case == true)
987 987
                 $meta->name = strtolower($meta->name);
988 988
 
989 989
             $field_array[] = $meta->name;
@@ -1012,11 +1012,11 @@  discard block
 block discarded – undo
1012 1012
         $row = mssql_fetch_assoc($result);
1013 1013
         //MSSQL returns a space " " when a varchar column is empty ("") and not null.
1014 1014
         //We need to iterate through the returned row array and strip empty spaces
1015
-        if(!empty($row)){
1016
-            foreach($row as $key => $column) {
1015
+        if (!empty($row)) {
1016
+            foreach ($row as $key => $column) {
1017 1017
                //notice we only strip if one space is returned.  we do not want to strip
1018 1018
                //strings with intentional spaces (" foo ")
1019
-               if (!empty($column) && $column ==" ") {
1019
+               if (!empty($column) && $column == " ") {
1020 1020
                    $row[$key] = '';
1021 1021
                }
1022 1022
             }
@@ -1029,10 +1029,10 @@  discard block
 block discarded – undo
1029 1029
      */
1030 1030
     public function quote($string)
1031 1031
     {
1032
-        if(is_array($string)) {
1032
+        if (is_array($string)) {
1033 1033
             return $this->arrayQuote($string);
1034 1034
         }
1035
-        return str_replace("'","''", $this->quoteInternal($string));
1035
+        return str_replace("'", "''", $this->quoteInternal($string));
1036 1036
     }
1037 1037
 
1038 1038
     /**
@@ -1070,7 +1070,7 @@  discard block
 block discarded – undo
1070 1070
             if (!empty($r)) {
1071 1071
                 while ($a = $this->fetchByAssoc($r)) {
1072 1072
                     $row = array_values($a);
1073
-					$tables[]=$row[0];
1073
+					$tables[] = $row[0];
1074 1074
                 }
1075 1075
                 return $tables;
1076 1076
             }
@@ -1085,7 +1085,7 @@  discard block
 block discarded – undo
1085 1085
     {
1086 1086
         $GLOBALS['log']->debug('MSSQL fetching table list');
1087 1087
 
1088
-        if($this->getDatabase()) {
1088
+        if ($this->getDatabase()) {
1089 1089
             $tables = array();
1090 1090
             $r = $this->query('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES');
1091 1091
             if (is_resource($r)) {
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
     {
1110 1110
         $GLOBALS['log']->debug('MSSQL about to wakeup FTS');
1111 1111
 
1112
-        if($this->getDatabase()) {
1112
+        if ($this->getDatabase()) {
1113 1113
                 //create wakeup catalog
1114 1114
                 $FTSqry[] = "if not exists(  select * from sys.fulltext_catalogs where name ='wakeup_catalog' )
1115 1115
                 CREATE FULLTEXT CATALOG wakeup_catalog
@@ -1149,7 +1149,7 @@  discard block
 block discarded – undo
1149 1149
                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup START FULL POPULATION';
1150 1150
                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING AUTO';
1151 1151
 
1152
-                foreach($FTSqry as $q){
1152
+                foreach ($FTSqry as $q) {
1153 1153
                     sleep(3);
1154 1154
                     $this->query($q);
1155 1155
                 }
@@ -1172,12 +1172,12 @@  discard block
 block discarded – undo
1172 1172
     {
1173 1173
         // convert the parameters array into a comma delimited string
1174 1174
         if (!empty($additional_parameters)) {
1175
-            $additional_parameters_string = ','.implode(',',$additional_parameters);
1175
+            $additional_parameters_string = ','.implode(',', $additional_parameters);
1176 1176
         } else {
1177 1177
             $additional_parameters_string = '';
1178 1178
         }
1179 1179
         $all_parameters = $additional_parameters;
1180
-        if(is_array($string)) {
1180
+        if (is_array($string)) {
1181 1181
             $all_parameters = array_merge($string, $all_parameters);
1182 1182
         } elseif (!is_null($string)) {
1183 1183
             array_unshift($all_parameters, $string);
@@ -1189,22 +1189,22 @@  discard block
 block discarded – undo
1189 1189
             case 'left':
1190 1190
                 return "LEFT($string$additional_parameters_string)";
1191 1191
             case 'date_format':
1192
-                if(!empty($additional_parameters[0]) && $additional_parameters[0][0] == "'") {
1192
+                if (!empty($additional_parameters[0]) && $additional_parameters[0][0] == "'") {
1193 1193
                     $additional_parameters[0] = trim($additional_parameters[0], "'");
1194 1194
                 }
1195
-                if(!empty($additional_parameters) && isset($this->date_formats[$additional_parameters[0]])) {
1195
+                if (!empty($additional_parameters) && isset($this->date_formats[$additional_parameters[0]])) {
1196 1196
                     $len = $this->date_formats[$additional_parameters[0]];
1197
-                    return "LEFT(CONVERT(varchar($len),". $string . ",120),$len)";
1197
+                    return "LEFT(CONVERT(varchar($len),".$string.",120),$len)";
1198 1198
                 } else {
1199
-                   return "LEFT(CONVERT(varchar(10),". $string . ",120),10)";
1199
+                   return "LEFT(CONVERT(varchar(10),".$string.",120),10)";
1200 1200
                 }
1201 1201
             case 'ifnull':
1202
-                if(empty($additional_parameters_string)) {
1202
+                if (empty($additional_parameters_string)) {
1203 1203
                     $additional_parameters_string = ",''";
1204 1204
                 }
1205 1205
                 return "ISNULL($string$additional_parameters_string)";
1206 1206
             case 'concat':
1207
-                return implode("+",$all_parameters);
1207
+                return implode("+", $all_parameters);
1208 1208
             case 'text2char':
1209 1209
                 return "CAST($string AS varchar(8000))";
1210 1210
             case 'quarter':
@@ -1220,7 +1220,7 @@  discard block
 block discarded – undo
1220 1220
             case 'add_tz_offset' :
1221 1221
                 $getUserUTCOffset = $GLOBALS['timedate']->getUserUTCOffset();
1222 1222
                 $operation = $getUserUTCOffset < 0 ? '-' : '+';
1223
-                return 'DATEADD(minute, ' . $operation . abs($getUserUTCOffset) . ', ' . $string. ')';
1223
+                return 'DATEADD(minute, '.$operation.abs($getUserUTCOffset).', '.$string.')';
1224 1224
             case 'avg':
1225 1225
                 return "avg($string)";
1226 1226
         }
@@ -1233,9 +1233,9 @@  discard block
 block discarded – undo
1233 1233
      */
1234 1234
     public function fromConvert($string, $type)
1235 1235
     {
1236
-        switch($type) {
1236
+        switch ($type) {
1237 1237
             case 'datetimecombo':
1238
-            case 'datetime': return substr($string, 0,19);
1238
+            case 'datetime': return substr($string, 0, 19);
1239 1239
             case 'date': return substr($string, 0, 10);
1240 1240
             case 'time': return substr($string, 11);
1241 1241
 		}
@@ -1264,8 +1264,8 @@  discard block
 block discarded – undo
1264 1264
     public function isTextType($type)
1265 1265
     {
1266 1266
         $type = strtolower($type);
1267
-        if(!isset($this->type_map[$type])) return false;
1268
-        return in_array($this->type_map[$type], array('ntext','text','image', 'nvarchar(max)'));
1267
+        if (!isset($this->type_map[$type])) return false;
1268
+        return in_array($this->type_map[$type], array('ntext', 'text', 'image', 'nvarchar(max)'));
1269 1269
     }
1270 1270
 
1271 1271
     /**
@@ -1275,13 +1275,13 @@  discard block
 block discarded – undo
1275 1275
     public function emptyValue($type)
1276 1276
     {
1277 1277
         $ctype = $this->getColumnType($type);
1278
-        if($ctype == "datetime") {
1278
+        if ($ctype == "datetime") {
1279 1279
             return $this->convert($this->quoted("1970-01-01 00:00:00"), "datetime");
1280 1280
         }
1281
-        if($ctype == "date") {
1281
+        if ($ctype == "date") {
1282 1282
             return $this->convert($this->quoted("1970-01-01"), "datetime");
1283 1283
         }
1284
-        if($ctype == "time") {
1284
+        if ($ctype == "time") {
1285 1285
             return $this->convert($this->quoted("00:00:00"), "time");
1286 1286
         }
1287 1287
         return parent::emptyValue($type);
@@ -1304,21 +1304,21 @@  discard block
 block discarded – undo
1304 1304
      */
1305 1305
     protected function alterSQLRep($action, array $def, $ignoreRequired, $tablename)
1306 1306
     {
1307
-        switch($action){
1307
+        switch ($action) {
1308 1308
         case 'add':
1309
-             $f_def=$this->oneColumnSQLRep($def, $ignoreRequired,$tablename,false);
1310
-            return "ADD " . $f_def;
1309
+             $f_def = $this->oneColumnSQLRep($def, $ignoreRequired, $tablename, false);
1310
+            return "ADD ".$f_def;
1311 1311
             break;
1312 1312
         case 'drop':
1313
-            return "DROP COLUMN " . $def['name'];
1313
+            return "DROP COLUMN ".$def['name'];
1314 1314
             break;
1315 1315
         case 'modify':
1316 1316
             //You cannot specify a default value for a column for MSSQL
1317
-            $f_def  = $this->oneColumnSQLRep($def, $ignoreRequired,$tablename, true);
1317
+            $f_def  = $this->oneColumnSQLRep($def, $ignoreRequired, $tablename, true);
1318 1318
             $f_stmt = "ALTER COLUMN ".$f_def['name'].' '.$f_def['colType'].' '.
1319 1319
                         $f_def['required'].' '.$f_def['auto_increment']."\n";
1320
-            if (!empty( $f_def['default']))
1321
-                $f_stmt .= " ALTER TABLE " . $tablename .  " ADD  ". $f_def['default'] . " FOR " . $def['name'];
1320
+            if (!empty($f_def['default']))
1321
+                $f_stmt .= " ALTER TABLE ".$tablename." ADD  ".$f_def['default']." FOR ".$def['name'];
1322 1322
             return $f_stmt;
1323 1323
             break;
1324 1324
         default:
@@ -1334,7 +1334,7 @@  discard block
 block discarded – undo
1334 1334
      */
1335 1335
     protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
1336 1336
     {
1337
-        $sql=$sql2='';
1337
+        $sql = $sql2 = '';
1338 1338
         $constraints = $this->get_field_default_constraint_name($tablename);
1339 1339
         $columns = array();
1340 1340
         if ($this->isFieldArray($fieldDefs)) {
@@ -1343,41 +1343,41 @@  discard block
 block discarded – undo
1343 1343
           		//if the column is being modified drop the default value
1344 1344
           		//constraint if it exists. alterSQLRep will add the constraint back
1345 1345
           		if (!empty($constraints[$def['name']])) {
1346
-          			$sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$def['name']];
1346
+          			$sql .= " ALTER TABLE ".$tablename." DROP CONSTRAINT ".$constraints[$def['name']];
1347 1347
           		}
1348 1348
           		//check to see if we need to drop related indexes before the alter
1349 1349
           		$indices = $this->get_indices($tablename);
1350
-                foreach ( $indices as $index ) {
1351
-                    if ( in_array($def['name'],$index['fields']) ) {
1352
-                        $sql  .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
1353
-                        $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
1350
+                foreach ($indices as $index) {
1351
+                    if (in_array($def['name'], $index['fields'])) {
1352
+                        $sql  .= ' '.$this->add_drop_constraint($tablename, $index, true).' ';
1353
+                        $sql2 .= ' '.$this->add_drop_constraint($tablename, $index, false).' ';
1354 1354
                     }
1355 1355
                 }
1356 1356
 
1357
-          		$columns[] = $this->alterSQLRep($action, $def, $ignoreRequired,$tablename);
1357
+          		$columns[] = $this->alterSQLRep($action, $def, $ignoreRequired, $tablename);
1358 1358
       		}
1359 1359
         }
1360 1360
         else {
1361 1361
             //if the column is being modified drop the default value
1362 1362
       		//constraint if it exists. alterSQLRep will add the constraint back
1363 1363
       		if (!empty($constraints[$fieldDefs['name']])) {
1364
-      			$sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$fieldDefs['name']];
1364
+      			$sql .= " ALTER TABLE ".$tablename." DROP CONSTRAINT ".$constraints[$fieldDefs['name']];
1365 1365
       		}
1366 1366
       		//check to see if we need to drop related indexes before the alter
1367 1367
             $indices = $this->get_indices($tablename);
1368
-            foreach ( $indices as $index ) {
1369
-                if ( in_array($fieldDefs['name'],$index['fields']) ) {
1370
-                    $sql  .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
1371
-                    $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
1368
+            foreach ($indices as $index) {
1369
+                if (in_array($fieldDefs['name'], $index['fields'])) {
1370
+                    $sql  .= ' '.$this->add_drop_constraint($tablename, $index, true).' ';
1371
+                    $sql2 .= ' '.$this->add_drop_constraint($tablename, $index, false).' ';
1372 1372
                 }
1373 1373
             }
1374 1374
 
1375 1375
 
1376
-          	$columns[] = $this->alterSQLRep($action, $fieldDefs, $ignoreRequired,$tablename);
1376
+          	$columns[] = $this->alterSQLRep($action, $fieldDefs, $ignoreRequired, $tablename);
1377 1377
         }
1378 1378
 
1379 1379
         $columns = implode(", ", $columns);
1380
-        $sql .= " ALTER TABLE $tablename $columns " . $sql2;
1380
+        $sql .= " ALTER TABLE $tablename $columns ".$sql2;
1381 1381
 
1382 1382
         return $sql;
1383 1383
     }
@@ -1392,7 +1392,7 @@  discard block
 block discarded – undo
1392 1392
      */
1393 1393
     public function setAutoIncrementStart($table, $field_name, $start_value)
1394 1394
     {
1395
-        if($start_value > 1)
1395
+        if ($start_value > 1)
1396 1396
             $start_value -= 1;
1397 1397
 		$this->query("DBCC CHECKIDENT ('$table', RESEED, $start_value) WITH NO_INFOMSGS");
1398 1398
         return true;
@@ -1427,11 +1427,11 @@  discard block
 block discarded – undo
1427 1427
         $result = $this->query($query);
1428 1428
 
1429 1429
         $indices = array();
1430
-        while (($row=$this->fetchByAssoc($result)) != null) {
1430
+        while (($row = $this->fetchByAssoc($result)) != null) {
1431 1431
             $index_type = 'index';
1432 1432
             if ($row['is_primary_key'] == '1')
1433 1433
                 $index_type = 'primary';
1434
-            elseif ($row['is_unique'] == 1 )
1434
+            elseif ($row['is_unique'] == 1)
1435 1435
                 $index_type = 'unique';
1436 1436
             $name = strtolower($row['index_name']);
1437 1437
             $indices[$name]['name']     = $name;
@@ -1450,36 +1450,36 @@  discard block
 block discarded – undo
1450 1450
         $result = $this->query("sp_columns $tablename");
1451 1451
 
1452 1452
         $columns = array();
1453
-        while (($row=$this->fetchByAssoc($result)) !=null) {
1453
+        while (($row = $this->fetchByAssoc($result)) != null) {
1454 1454
             $column_name = strtolower($row['COLUMN_NAME']);
1455
-            $columns[$column_name]['name']=$column_name;
1456
-            $columns[$column_name]['type']=strtolower($row['TYPE_NAME']);
1457
-            if ( $row['TYPE_NAME'] == 'decimal' ) {
1458
-                $columns[$column_name]['len']=strtolower($row['PRECISION']);
1459
-                $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
1455
+            $columns[$column_name]['name'] = $column_name;
1456
+            $columns[$column_name]['type'] = strtolower($row['TYPE_NAME']);
1457
+            if ($row['TYPE_NAME'] == 'decimal') {
1458
+                $columns[$column_name]['len'] = strtolower($row['PRECISION']);
1459
+                $columns[$column_name]['len'] .= ','.strtolower($row['SCALE']);
1460 1460
             }
1461
-			elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) )
1462
-				$columns[$column_name]['len']=strtolower($row['PRECISION']);
1463
-            elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) )
1464
-                $columns[$column_name]['len']=strtolower($row['LENGTH']);
1465
-            if ( stristr($row['TYPE_NAME'],'identity') ) {
1461
+			elseif (in_array($row['TYPE_NAME'], array('nchar', 'nvarchar')))
1462
+				$columns[$column_name]['len'] = strtolower($row['PRECISION']);
1463
+            elseif (!in_array($row['TYPE_NAME'], array('datetime', 'text')))
1464
+                $columns[$column_name]['len'] = strtolower($row['LENGTH']);
1465
+            if (stristr($row['TYPE_NAME'], 'identity')) {
1466 1466
                 $columns[$column_name]['auto_increment'] = '1';
1467
-                $columns[$column_name]['type']=str_replace(' identity','',strtolower($row['TYPE_NAME']));
1467
+                $columns[$column_name]['type'] = str_replace(' identity', '', strtolower($row['TYPE_NAME']));
1468 1468
             }
1469 1469
 
1470
-            if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI')))
1470
+            if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'], 'PRI')))
1471 1471
                 $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
1472 1472
 
1473 1473
             $column_def = 1;
1474
-            if ( strtolower($tablename) == 'relationships' ) {
1474
+            if (strtolower($tablename) == 'relationships') {
1475 1475
                 $column_def = $this->getOne("select cdefault from syscolumns where id = object_id('relationships') and name = '$column_name'");
1476 1476
             }
1477
-            if ( $column_def != 0 && ($row['COLUMN_DEF'] != null)) {	// NOTE Not using !empty as an empty string may be a viable default value.
1477
+            if ($column_def != 0 && ($row['COLUMN_DEF'] != null)) {	// NOTE Not using !empty as an empty string may be a viable default value.
1478 1478
                 $matches = array();
1479
-                $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'],ENT_QUOTES);
1480
-                if ( preg_match('/\([\(|\'](.*)[\)|\']\)/i',$row['COLUMN_DEF'],$matches) )
1479
+                $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'], ENT_QUOTES);
1480
+                if (preg_match('/\([\(|\'](.*)[\)|\']\)/i', $row['COLUMN_DEF'], $matches))
1481 1481
                     $columns[$column_name]['default'] = $matches[1];
1482
-                elseif ( preg_match('/\(N\'(.*)\'\)/i',$row['COLUMN_DEF'],$matches) )
1482
+                elseif (preg_match('/\(N\'(.*)\'\)/i', $row['COLUMN_DEF'], $matches))
1483 1483
                     $columns[$column_name]['default'] = $matches[1];
1484 1484
                 else
1485 1485
                     $columns[$column_name]['default'] = $row['COLUMN_DEF'];
@@ -1494,7 +1494,7 @@  discard block
 block discarded – undo
1494 1494
      */
1495 1495
     protected function ftsCatalogName()
1496 1496
     {
1497
-        if(isset($this->connectOptions['db_name'])) {
1497
+        if (isset($this->connectOptions['db_name'])) {
1498 1498
             return $this->connectOptions['db_name']."_fts_catalog";
1499 1499
         }
1500 1500
         return 'sugar_fts_catalog';
@@ -1506,11 +1506,11 @@  discard block
 block discarded – undo
1506 1506
     public function add_drop_constraint($table, $definition, $drop = false)
1507 1507
     {
1508 1508
         $type         = $definition['type'];
1509
-        $fields       = is_array($definition['fields'])?implode(',',$definition['fields']):$definition['fields'];
1509
+        $fields       = is_array($definition['fields']) ?implode(',', $definition['fields']) : $definition['fields'];
1510 1510
         $name         = $definition['name'];
1511 1511
         $sql          = '';
1512 1512
 
1513
-        switch ($type){
1513
+        switch ($type) {
1514 1514
         // generic indices
1515 1515
         case 'index':
1516 1516
         case 'alternate_key':
@@ -1548,13 +1548,13 @@  discard block
 block discarded – undo
1548 1548
             if ($this->full_text_indexing_enabled() && $drop) {
1549 1549
                 $sql = "DROP FULLTEXT INDEX ON {$table}";
1550 1550
             } elseif ($this->full_text_indexing_enabled()) {
1551
-                $catalog_name=$this->ftsCatalogName();
1552
-                if ( isset($definition['catalog_name']) && $definition['catalog_name'] != 'default')
1551
+                $catalog_name = $this->ftsCatalogName();
1552
+                if (isset($definition['catalog_name']) && $definition['catalog_name'] != 'default')
1553 1553
                     $catalog_name = $definition['catalog_name'];
1554 1554
 
1555 1555
                 $language = "Language 1033";
1556 1556
                 if (isset($definition['language']) && !empty($definition['language']))
1557
-                    $language = "Language " . $definition['language'];
1557
+                    $language = "Language ".$definition['language'];
1558 1558
 
1559 1559
                 $key_index = $definition['key_index'];
1560 1560
 
@@ -1562,7 +1562,7 @@  discard block
 block discarded – undo
1562 1562
                 if (isset($definition['change_tracking']) && !empty($definition['change_tracking']))
1563 1563
                     $change_tracking = $definition['change_tracking'];
1564 1564
 
1565
-                $sql = " CREATE FULLTEXT INDEX ON $table ($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
1565
+                $sql = " CREATE FULLTEXT INDEX ON $table ($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking";
1566 1566
             }
1567 1567
             break;
1568 1568
         }
@@ -1586,11 +1586,11 @@  discard block
 block discarded – undo
1586 1586
     protected function full_text_indexing_enabled($dbname = null)
1587 1587
     {
1588 1588
         // check to see if we already have install setting in session
1589
-    	if(!isset($_SESSION['IsFulltextInstalled']))
1589
+    	if (!isset($_SESSION['IsFulltextInstalled']))
1590 1590
             $_SESSION['IsFulltextInstalled'] = $this->full_text_indexing_installed();
1591 1591
 
1592 1592
         // check to see if FTS Indexing service is installed
1593
-        if(empty($_SESSION['IsFulltextInstalled']))
1593
+        if (empty($_SESSION['IsFulltextInstalled']))
1594 1594
             return false;
1595 1595
 
1596 1596
         // grab the dbname if it was not passed through
@@ -1640,7 +1640,7 @@  discard block
 block discarded – undo
1640 1640
     {
1641 1641
         static $results = array();
1642 1642
 
1643
-        if ( empty($column) && isset($results[$table]) )
1643
+        if (empty($column) && isset($results[$table]))
1644 1644
             return $results[$table];
1645 1645
 
1646 1646
         $query = <<<EOQ
@@ -1654,17 +1654,17 @@  discard block
 block discarded – undo
1654 1654
             on s.schema_id = o.schema_id
1655 1655
     where o.name = '$table'
1656 1656
 EOQ;
1657
-        if ( !empty($column) )
1657
+        if (!empty($column))
1658 1658
             $query .= " and c.name = '$column'";
1659 1659
         $res = $this->query($query);
1660
-        if ( !empty($column) ) {
1660
+        if (!empty($column)) {
1661 1661
             $row = $this->fetchByAssoc($res);
1662 1662
             if (!empty($row))
1663 1663
                 return $row['ctrt'];
1664 1664
         }
1665 1665
         else {
1666 1666
             $returnResult = array();
1667
-            while ( $row = $this->fetchByAssoc($res) )
1667
+            while ($row = $this->fetchByAssoc($res))
1668 1668
                 $returnResult[$row['dtrt']] = $row['ctrt'];
1669 1669
             $results[$table] = $returnResult;
1670 1670
             return $returnResult;
@@ -1678,14 +1678,14 @@  discard block
 block discarded – undo
1678 1678
      */
1679 1679
     public function massageFieldDef(&$fieldDef, $tablename)
1680 1680
     {
1681
-        parent::massageFieldDef($fieldDef,$tablename);
1681
+        parent::massageFieldDef($fieldDef, $tablename);
1682 1682
 
1683 1683
         if ($fieldDef['type'] == 'int')
1684 1684
             $fieldDef['len'] = '4';
1685 1685
 
1686
-        if(empty($fieldDef['len']))
1686
+        if (empty($fieldDef['len']))
1687 1687
         {
1688
-            switch($fieldDef['type']) {
1688
+            switch ($fieldDef['type']) {
1689 1689
                 case 'bit'      :
1690 1690
                 case 'bool'     : $fieldDef['len'] = '1'; break;
1691 1691
                 case 'smallint' : $fieldDef['len'] = '2'; break;
@@ -1695,22 +1695,22 @@  discard block
 block discarded – undo
1695 1695
                                   $fieldDef['len'] = $this->isTextType($fieldDef['dbType']) ? 'max' : '255';
1696 1696
                                   break;
1697 1697
                 case 'image'    : $fieldDef['len'] = '2147483647'; break;
1698
-                case 'ntext'    : $fieldDef['len'] = '2147483646'; break;   // Note: this is from legacy code, don't know if this is correct
1698
+                case 'ntext'    : $fieldDef['len'] = '2147483646'; break; // Note: this is from legacy code, don't know if this is correct
1699 1699
             }
1700 1700
         }
1701
-        if($fieldDef['type'] == 'decimal'
1701
+        if ($fieldDef['type'] == 'decimal'
1702 1702
            && empty($fieldDef['precision'])
1703 1703
            && !strpos($fieldDef['len'], ','))
1704 1704
         {
1705 1705
              $fieldDef['len'] .= ',0'; // Adding 0 precision if it is not specified
1706 1706
         }
1707 1707
 
1708
-        if(empty($fieldDef['default'])
1709
-            && in_array($fieldDef['type'],array('bit','bool')))
1708
+        if (empty($fieldDef['default'])
1709
+            && in_array($fieldDef['type'], array('bit', 'bool')))
1710 1710
         {
1711 1711
             $fieldDef['default'] = '0';
1712 1712
         }
1713
-		if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']) )
1713
+		if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']))
1714 1714
 			$fieldDef['default'] = '';
1715 1715
 //        if ($fieldDef['type'] == 'bit' && empty($fieldDef['len']) )
1716 1716
 //            $fieldDef['len'] = '1';
@@ -1741,13 +1741,13 @@  discard block
 block discarded – undo
1741 1741
     protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
1742 1742
     {
1743 1743
     	//Bug 25814
1744
-		if(isset($fieldDef['name'])){
1744
+		if (isset($fieldDef['name'])) {
1745 1745
 		    $colType = $this->getFieldType($fieldDef);
1746
-        	if(stristr($this->getFieldType($fieldDef), 'decimal') && isset($fieldDef['len'])){
1747
-				$fieldDef['len'] = min($fieldDef['len'],38);
1746
+        	if (stristr($this->getFieldType($fieldDef), 'decimal') && isset($fieldDef['len'])) {
1747
+				$fieldDef['len'] = min($fieldDef['len'], 38);
1748 1748
 			}
1749 1749
 		    //bug: 39690 float(8) is interpreted as real and this generates a diff when doing repair
1750
-			if(stristr($colType, 'float') && isset($fieldDef['len']) && $fieldDef['len'] == 8){
1750
+			if (stristr($colType, 'float') && isset($fieldDef['len']) && $fieldDef['len'] == 8) {
1751 1751
 				unset($fieldDef['len']);
1752 1752
 			}
1753 1753
 		}
@@ -1756,10 +1756,10 @@  discard block
 block discarded – undo
1756 1756
 		$ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
1757 1757
 
1758 1758
 		// Bug 24307 - Don't add precision for float fields.
1759
-		if ( stristr($ref['colType'],'float') )
1760
-			$ref['colType'] = preg_replace('/(,\d+)/','',$ref['colType']);
1759
+		if (stristr($ref['colType'], 'float'))
1760
+			$ref['colType'] = preg_replace('/(,\d+)/', '', $ref['colType']);
1761 1761
 
1762
-        if ( $return_as_array )
1762
+        if ($return_as_array)
1763 1763
             return $ref;
1764 1764
         else
1765 1765
             return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
@@ -1774,10 +1774,10 @@  discard block
 block discarded – undo
1774 1774
     public function save_audit_records(SugarBean $bean, $changes)
1775 1775
 	{
1776 1776
 		//Bug 25078 fixed by Martin Hu: sqlserver haven't 'date' type, trim extra "00:00:00"
1777
-		if($changes['data_type'] == 'date'){
1778
-			$changes['before'] = str_replace(' 00:00:00','',$changes['before']);
1777
+		if ($changes['data_type'] == 'date') {
1778
+			$changes['before'] = str_replace(' 00:00:00', '', $changes['before']);
1779 1779
 		}
1780
-		parent::save_audit_records($bean,$changes);
1780
+		parent::save_audit_records($bean, $changes);
1781 1781
 	}
1782 1782
 
1783 1783
     /**
@@ -1788,7 +1788,7 @@  discard block
 block discarded – undo
1788 1788
     public function disconnect()
1789 1789
     {
1790 1790
     	$GLOBALS['log']->debug('Calling Mssql::disconnect()');
1791
-        if(!empty($this->database)){
1791
+        if (!empty($this->database)) {
1792 1792
             $this->freeResult();
1793 1793
             mssql_close($this->database);
1794 1794
             $this->database = null;
@@ -1800,7 +1800,7 @@  discard block
 block discarded – undo
1800 1800
      */
1801 1801
     protected function freeDbResult($dbResult)
1802 1802
     {
1803
-        if(!empty($dbResult))
1803
+        if (!empty($dbResult))
1804 1804
             mssql_free_result($dbResult);
1805 1805
     }
1806 1806
 
@@ -1811,11 +1811,11 @@  discard block
 block discarded – undo
1811 1811
     public function lastDbError()
1812 1812
     {
1813 1813
         $sqlmsg = mssql_get_last_message();
1814
-        if(empty($sqlmsg)) return false;
1814
+        if (empty($sqlmsg)) return false;
1815 1815
         global $app_strings;
1816 1816
         if (empty($app_strings)
1817 1817
 		    or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
1818
-			or !isset($app_strings['ERR_MSSQL_WARNING']) ) {
1818
+			or !isset($app_strings['ERR_MSSQL_WARNING'])) {
1819 1819
         //ignore the message from sql-server if $app_strings array is empty. This will happen
1820 1820
         //only if connection if made before language is set.
1821 1821
 		    return false;
@@ -1824,7 +1824,7 @@  discard block
 block discarded – undo
1824 1824
         $sqlpos = strpos($sqlmsg, 'Changed database context to');
1825 1825
         $sqlpos2 = strpos($sqlmsg, 'Warning:');
1826 1826
         $sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
1827
-        if ( $sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false ) {
1827
+        if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false) {
1828 1828
             return false;
1829 1829
         } else {
1830 1830
         	global $app_strings;
@@ -1832,18 +1832,18 @@  discard block
 block discarded – undo
1832 1832
             if (empty($app_strings) or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])) {
1833 1833
                 //ignore the message from sql-server if $app_strings array is empty. This will happen
1834 1834
                 //only if connection if made before languge is set.
1835
-                $GLOBALS['log']->debug("Ignoring this database message: " . $sqlmsg);
1835
+                $GLOBALS['log']->debug("Ignoring this database message: ".$sqlmsg);
1836 1836
                 return false;
1837 1837
             }
1838 1838
             else {
1839 1839
                 $sqlpos = strpos($sqlmsg, $app_strings['ERR_MSSQL_DB_CONTEXT']);
1840
-                if ( $sqlpos !== false )
1840
+                if ($sqlpos !== false)
1841 1841
                     return false;
1842 1842
             }
1843 1843
         }
1844 1844
 
1845
-        if ( strlen($sqlmsg) > 2 ) {
1846
-        	return "SQL Server error: " . $sqlmsg;
1845
+        if (strlen($sqlmsg) > 2) {
1846
+        	return "SQL Server error: ".$sqlmsg;
1847 1847
         }
1848 1848
 
1849 1849
         return false;
@@ -1864,7 +1864,7 @@  discard block
 block discarded – undo
1864 1864
      */
1865 1865
     public function validateQuery($query)
1866 1866
     {
1867
-        if(!$this->isSelect($query)) {
1867
+        if (!$this->isSelect($query)) {
1868 1868
             return false;
1869 1869
         }
1870 1870
         $this->query("SET SHOWPLAN_TEXT ON");
@@ -1888,7 +1888,7 @@  discard block
 block discarded – undo
1888 1888
 
1889 1889
         // Flag if there are odd number of single quotes, just continue without trying to append N
1890 1890
         if ((substr_count($sql, "'") & 1)) {
1891
-            $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
1891
+            $GLOBALS['log']->error("SQL statement[".$sql."] has odd number of single quotes.");
1892 1892
             return $sql;
1893 1893
         }
1894 1894
 
@@ -1918,7 +1918,7 @@  discard block
 block discarded – undo
1918 1918
                 // We are assuming that all nvarchar columns are no more than 200 characters in length
1919 1919
                 // One problem we face is the image column type in reports which cannot accept nvarchar data
1920 1920
                 if (!empty($value) && !is_numeric(trim(str_replace(array("'", ","), "", $value))) && !preg_match('/^\'[\,]\'$/', $value)) {
1921
-                    $replace[$value] = 'N' . trim($value, "N");
1921
+                    $replace[$value] = 'N'.trim($value, "N");
1922 1922
                 }
1923 1923
             }
1924 1924
         }
@@ -1929,7 +1929,7 @@  discard block
 block discarded – undo
1929 1929
         if (!empty($pairs))
1930 1930
             $sql = str_replace(array_keys($pairs), $pairs, $sql);
1931 1931
 
1932
-        if(strpos($sql, "<@#@#@PAIR@#@#@>"))
1932
+        if (strpos($sql, "<@#@#@PAIR@#@#@>"))
1933 1933
             $sql = str_replace(array('<@#@#@PAIR@#@#@>'), array("''"), $sql);
1934 1934
 
1935 1935
         return $sql;
@@ -1956,22 +1956,22 @@  discard block
 block discarded – undo
1956 1956
     public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1957 1957
     {
1958 1958
         $condition = $or_condition = array();
1959
-        foreach($must_terms as $term) {
1959
+        foreach ($must_terms as $term) {
1960 1960
             $condition[] = $this->quoteTerm($term);
1961 1961
         }
1962 1962
 
1963
-        foreach($terms as $term) {
1963
+        foreach ($terms as $term) {
1964 1964
             $or_condition[] = $this->quoteTerm($term);
1965 1965
         }
1966 1966
 
1967
-        if(!empty($or_condition)) {
1967
+        if (!empty($or_condition)) {
1968 1968
             $condition[] = "(".join(" | ", $or_condition).")";
1969 1969
         }
1970 1970
 
1971
-        foreach($exclude_terms as $term) {
1971
+        foreach ($exclude_terms as $term) {
1972 1972
             $condition[] = " NOT ".$this->quoteTerm($term);
1973 1973
         }
1974
-        $condition = $this->quoted(join(" AND ",$condition));
1974
+        $condition = $this->quoted(join(" AND ", $condition));
1975 1975
         return "CONTAINS($field, $condition)";
1976 1976
     }
1977 1977
 
@@ -2060,7 +2060,7 @@  discard block
 block discarded – undo
2060 2060
     public function isDatabaseNameValid($name)
2061 2061
     {
2062 2062
         // No funny chars, does not begin with number
2063
-        return preg_match('/^[0-9#@]+|[\"\'\*\/\\?\:\\<\>\-\ \&\!\(\)\[\]\{\}\;\,\.\`\~\|\\\\]+/', $name)==0;
2063
+        return preg_match('/^[0-9#@]+|[\"\'\*\/\\?\:\\<\>\-\ \&\!\(\)\[\]\{\}\;\,\.\`\~\|\\\\]+/', $name) == 0;
2064 2064
     }
2065 2065
 
2066 2066
     public function installConfig()
Please login to merge, or discard this patch.
include/database/MysqlManager.php 4 patches
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 $this->convert($this->quoted("0000-00-00 00:00:00"), "datetime");
1109
-		}
1110
-		if($ctype == "date") {
1111
-			return $this->convert($this->quoted("0000-00-00"), "date");
1112
-		}
1113
-		if($ctype == "time") {
1114
-			return $this->convert($this->quoted("00:00:00"), "time");
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 $this->convert($this->quoted("0000-00-00 00:00:00"), "datetime");
1109
+        }
1110
+        if($ctype == "date") {
1111
+            return $this->convert($this->quoted("0000-00-00"), "date");
1112
+        }
1113
+        if($ctype == "time") {
1114
+            return $this->convert($this->quoted("00:00:00"), "time");
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.
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.
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 $this->convert($this->quoted("0000-00-00 00:00:00"), "datetime");
1109 1109
 		}
1110
-		if($ctype == "date") {
1110
+		if ($ctype == "date") {
1111 1111
 			return $this->convert($this->quoted("0000-00-00"), "date");
1112 1112
 		}
1113
-		if($ctype == "time") {
1113
+		if ($ctype == "time") {
1114 1114
 			return $this->convert($this->quoted("00:00:00"), "time");
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.
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.
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/utils/sugar_file_utils.php 3 patches
Indentation   +153 added lines, -153 removed lines patch added patch discarded remove patch
@@ -54,44 +54,44 @@  discard block
 block discarded – undo
54 54
  * @return boolean - Returns true on success false on failure
55 55
  */
56 56
 function sugar_mkdir($pathname, $mode=null, $recursive=false, $context='') {
57
-	$mode = get_mode('dir_mode', $mode);
58
-
59
-	if ( sugar_is_dir($pathname,$mode) )
60
-	    return true;
61
-
62
-	$result = false;
63
-	if(empty($mode))
64
-		$mode = 0777;
65
-	if(empty($context)) {
66
-		$result = @mkdir($pathname, $mode, $recursive);
67
-	} else {
68
-		$result = @mkdir($pathname, $mode, $recursive, $context);
69
-	}
70
-
71
-	if($result){
72
-		if(!sugar_chmod($pathname, $mode)){
73
-			return false;
74
-		}
75
-		if(!empty($GLOBALS['sugar_config']['default_permissions']['user'])){
76
-			if(!sugar_chown($pathname)){
77
-				return false;
78
-			}
79
-		}
80
-		if(!empty($GLOBALS['sugar_config']['default_permissions']['group'])){
81
-   			if(!sugar_chgrp($pathname)) {
82
-   				return false;
83
-   			}
84
-		}
85
-	}
86
-	else {
87
-		$errorMessage = "Cannot create directory $pathname cannot be touched";
88
-		if(is_null($GLOBALS['log'])) {
89
-			throw new Exception("Error occurred but the system doesn't have logger. Error message: \"$errorMessage\"");
90
-		}
91
-		$GLOBALS['log']->error($errorMessage);
92
-	}
93
-
94
-	return $result;
57
+    $mode = get_mode('dir_mode', $mode);
58
+
59
+    if ( sugar_is_dir($pathname,$mode) )
60
+        return true;
61
+
62
+    $result = false;
63
+    if(empty($mode))
64
+        $mode = 0777;
65
+    if(empty($context)) {
66
+        $result = @mkdir($pathname, $mode, $recursive);
67
+    } else {
68
+        $result = @mkdir($pathname, $mode, $recursive, $context);
69
+    }
70
+
71
+    if($result){
72
+        if(!sugar_chmod($pathname, $mode)){
73
+            return false;
74
+        }
75
+        if(!empty($GLOBALS['sugar_config']['default_permissions']['user'])){
76
+            if(!sugar_chown($pathname)){
77
+                return false;
78
+            }
79
+        }
80
+        if(!empty($GLOBALS['sugar_config']['default_permissions']['group'])){
81
+                if(!sugar_chgrp($pathname)) {
82
+                    return false;
83
+                }
84
+        }
85
+    }
86
+    else {
87
+        $errorMessage = "Cannot create directory $pathname cannot be touched";
88
+        if(is_null($GLOBALS['log'])) {
89
+            throw new Exception("Error occurred but the system doesn't have logger. Error message: \"$errorMessage\"");
90
+        }
91
+        $GLOBALS['log']->error($errorMessage);
92
+    }
93
+
94
+    return $result;
95 95
 }
96 96
 
97 97
 /**
@@ -109,17 +109,17 @@  discard block
 block discarded – undo
109 109
  * @return boolean - Returns a file pointer on success, false otherwise
110 110
  */
111 111
 function sugar_fopen($filename, $mode, $use_include_path=false, $context=null){
112
-	//check to see if the file exists, if not then use touch to create it.
113
-	if(!file_exists($filename)){
114
-		sugar_touch($filename);
115
-	}
112
+    //check to see if the file exists, if not then use touch to create it.
113
+    if(!file_exists($filename)){
114
+        sugar_touch($filename);
115
+    }
116 116
 
117
-	if(empty($context)) {
117
+    if(empty($context)) {
118 118
 
119
-		return fopen($filename, $mode, $use_include_path);
120
-	} else {
121
-		return fopen($filename, $mode, $use_include_path, $context);
122
-	}
119
+        return fopen($filename, $mode, $use_include_path);
120
+    } else {
121
+        return fopen($filename, $mode, $use_include_path, $context);
122
+    }
123 123
 }
124 124
 
125 125
 /**
@@ -137,23 +137,23 @@  discard block
 block discarded – undo
137 137
  * @return int - Returns the number of bytes written to the file, false otherwise.
138 138
  */
139 139
 function sugar_file_put_contents($filename, $data, $flags=null, $context=null){
140
-	//check to see if the file exists, if not then use touch to create it.
141
-	if(!file_exists($filename)){
142
-		sugar_touch($filename);
143
-	}
144
-
145
-	if ( !is_writable($filename) ) {
146
-	    $GLOBALS['log']->error("File $filename cannot be written to");
147
-	    return false;
148
-	}
149
-
150
-	if(empty($flags)) {
151
-		return file_put_contents($filename, $data);
152
-	} elseif(empty($context)) {
153
-		return file_put_contents($filename, $data, $flags);
154
-	} else{
155
-		return file_put_contents($filename, $data, $flags, $context);
156
-	}
140
+    //check to see if the file exists, if not then use touch to create it.
141
+    if(!file_exists($filename)){
142
+        sugar_touch($filename);
143
+    }
144
+
145
+    if ( !is_writable($filename) ) {
146
+        $GLOBALS['log']->error("File $filename cannot be written to");
147
+        return false;
148
+    }
149
+
150
+    if(empty($flags)) {
151
+        return file_put_contents($filename, $data);
152
+    } elseif(empty($context)) {
153
+        return file_put_contents($filename, $data, $flags);
154
+    } else{
155
+        return file_put_contents($filename, $data, $flags, $context);
156
+    }
157 157
 }
158 158
 
159 159
 
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 
199 199
     if(file_exists($filename))
200 200
     {
201
-       return sugar_chmod($filename, 0755);
201
+        return sugar_chmod($filename, 0755);
202 202
     }
203 203
 
204 204
     return false;
@@ -215,21 +215,21 @@  discard block
 block discarded – undo
215 215
  * @return string|boolean - Returns a file data on success, false otherwise
216 216
  */
217 217
 function sugar_file_get_contents($filename, $use_include_path=false, $context=null){
218
-	//check to see if the file exists, if not then use touch to create it.
219
-	if(!file_exists($filename)){
220
-		sugar_touch($filename);
221
-	}
222
-
223
-	if ( !is_readable($filename) ) {
224
-	    $GLOBALS['log']->error("File $filename cannot be read");
225
-	    return false;
226
-	}
227
-
228
-	if(empty($context)) {
229
-		return file_get_contents($filename, $use_include_path);
230
-	} else {
231
-		return file_get_contents($filename, $use_include_path, $context);
232
-	}
218
+    //check to see if the file exists, if not then use touch to create it.
219
+    if(!file_exists($filename)){
220
+        sugar_touch($filename);
221
+    }
222
+
223
+    if ( !is_readable($filename) ) {
224
+        $GLOBALS['log']->error("File $filename cannot be read");
225
+        return false;
226
+    }
227
+
228
+    if(empty($context)) {
229
+        return file_get_contents($filename, $use_include_path);
230
+    } else {
231
+        return file_get_contents($filename, $use_include_path, $context);
232
+    }
233 233
 }
234 234
 
235 235
 /**
@@ -248,31 +248,31 @@  discard block
 block discarded – undo
248 248
  */
249 249
 function sugar_touch($filename, $time=null, $atime=null) {
250 250
 
251
-   $result = false;
252
-
253
-   if(!empty($atime) && !empty($time)) {
254
-   	  $result = @touch($filename, $time, $atime);
255
-   } else if(!empty($time)) {
256
-   	  $result = @touch($filename, $time);
257
-   } else {
258
-   	  $result = @touch($filename);
259
-   }
260
-
261
-   if(!$result) {
262
-       $GLOBALS['log']->error("File $filename cannot be touched");
263
-       return $result;
264
-   }
265
-	if(!empty($GLOBALS['sugar_config']['default_permissions']['file_mode'])){
266
-		sugar_chmod($filename, $GLOBALS['sugar_config']['default_permissions']['file_mode']);
267
-	}
268
-	if(!empty($GLOBALS['sugar_config']['default_permissions']['user'])){
269
-		sugar_chown($filename);
270
-	}
271
-	if(!empty($GLOBALS['sugar_config']['default_permissions']['group'])){
272
-		sugar_chgrp($filename);
273
-	}
274
-
275
-   return true;
251
+    $result = false;
252
+
253
+    if(!empty($atime) && !empty($time)) {
254
+            $result = @touch($filename, $time, $atime);
255
+    } else if(!empty($time)) {
256
+            $result = @touch($filename, $time);
257
+    } else {
258
+            $result = @touch($filename);
259
+    }
260
+
261
+    if(!$result) {
262
+        $GLOBALS['log']->error("File $filename cannot be touched");
263
+        return $result;
264
+    }
265
+    if(!empty($GLOBALS['sugar_config']['default_permissions']['file_mode'])){
266
+        sugar_chmod($filename, $GLOBALS['sugar_config']['default_permissions']['file_mode']);
267
+    }
268
+    if(!empty($GLOBALS['sugar_config']['default_permissions']['user'])){
269
+        sugar_chown($filename);
270
+    }
271
+    if(!empty($GLOBALS['sugar_config']['default_permissions']['group'])){
272
+        sugar_chgrp($filename);
273
+    }
274
+
275
+    return true;
276 276
 }
277 277
 
278 278
 /**
@@ -287,17 +287,17 @@  discard block
 block discarded – undo
287 287
 function sugar_chmod($filename, $mode=null) {
288 288
     if ( !is_int($mode) )
289 289
         $mode = (int) $mode;
290
-	if(!is_windows()){
291
-		if(!isset($mode)){
292
-			$mode = get_mode('file_mode', $mode);
293
-		}
290
+    if(!is_windows()){
291
+        if(!isset($mode)){
292
+            $mode = get_mode('file_mode', $mode);
293
+        }
294 294
         if(isset($mode) && $mode > 0){
295
-		   return @chmod($filename, $mode);
296
-		}else{
297
-	    	return false;
298
-		}
299
-	}
300
-	return true;
295
+            return @chmod($filename, $mode);
296
+        }else{
297
+            return false;
298
+        }
299
+    }
300
+    return true;
301 301
 }
302 302
 
303 303
 /**
@@ -310,19 +310,19 @@  discard block
 block discarded – undo
310 310
  * @return boolean - Returns TRUE on success or FALSE on failure.
311 311
  */
312 312
 function sugar_chown($filename, $user='') {
313
-	if(!is_windows()){
314
-		if(strlen($user)){
315
-			return chown($filename, $user);
316
-		}else{
317
-			if(strlen($GLOBALS['sugar_config']['default_permissions']['user'])){
318
-				$user = $GLOBALS['sugar_config']['default_permissions']['user'];
319
-				return chown($filename, $user);
320
-			}else{
321
-				return false;
322
-			}
323
-		}
324
-	}
325
-	return true;
313
+    if(!is_windows()){
314
+        if(strlen($user)){
315
+            return chown($filename, $user);
316
+        }else{
317
+            if(strlen($GLOBALS['sugar_config']['default_permissions']['user'])){
318
+                $user = $GLOBALS['sugar_config']['default_permissions']['user'];
319
+                return chown($filename, $user);
320
+            }else{
321
+                return false;
322
+            }
323
+        }
324
+    }
325
+    return true;
326 326
 }
327 327
 
328 328
 /**
@@ -335,19 +335,19 @@  discard block
 block discarded – undo
335 335
  * @return boolean - Returns TRUE on success or FALSE on failure.
336 336
  */
337 337
 function sugar_chgrp($filename, $group='') {
338
-	if(!is_windows()){
339
-		if(!empty($group)){
340
-			return chgrp($filename, $group);
341
-		}else{
342
-			if(!empty($GLOBALS['sugar_config']['default_permissions']['group'])){
343
-				$group = $GLOBALS['sugar_config']['default_permissions']['group'];
344
-				return chgrp($filename, $group);
345
-			}else{
346
-				return false;
347
-			}
348
-		}
349
-	}
350
-	return true;
338
+    if(!is_windows()){
339
+        if(!empty($group)){
340
+            return chgrp($filename, $group);
341
+        }else{
342
+            if(!empty($GLOBALS['sugar_config']['default_permissions']['group'])){
343
+                $group = $GLOBALS['sugar_config']['default_permissions']['group'];
344
+                return chgrp($filename, $group);
345
+            }else{
346
+                return false;
347
+            }
348
+        }
349
+    }
350
+    return true;
351 351
 }
352 352
 
353 353
 /**
@@ -361,26 +361,26 @@  discard block
 block discarded – undo
361 361
  * @return int - the mode either found in the config file or passed in via the input parameter
362 362
  */
363 363
 function get_mode($key = 'dir_mode', $mode=null) {
364
-	if ( !is_int($mode) )
364
+    if ( !is_int($mode) )
365 365
         $mode = (int) $mode;
366 366
     if(!class_exists('SugarConfig', true)) {
367
-		require 'include/SugarObjects/SugarConfig.php';
368
-	}
369
-	if(!is_windows()){
370
-		$conf_inst=SugarConfig::getInstance();
371
-		$mode = $conf_inst->get('default_permissions.'.$key, $mode);
372
-	}
373
-	return $mode;
367
+        require 'include/SugarObjects/SugarConfig.php';
368
+    }
369
+    if(!is_windows()){
370
+        $conf_inst=SugarConfig::getInstance();
371
+        $mode = $conf_inst->get('default_permissions.'.$key, $mode);
372
+    }
373
+    return $mode;
374 374
 }
375 375
 
376 376
 function sugar_is_dir($path, $mode='r'){
377
-		if(defined('TEMPLATE_URL'))return is_dir($path, $mode);
378
-		return is_dir($path);
377
+        if(defined('TEMPLATE_URL'))return is_dir($path, $mode);
378
+        return is_dir($path);
379 379
 }
380 380
 
381 381
 function sugar_is_file($path, $mode='r'){
382
-		if(defined('TEMPLATE_URL'))return is_file($path, $mode);
383
-		return is_file($path);
382
+        if(defined('TEMPLATE_URL'))return is_file($path, $mode);
383
+        return is_file($path);
384 384
 }
385 385
 
386 386
 /**
Please login to merge, or discard this patch.
Spacing   +66 added lines, -66 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.
@@ -53,39 +53,39 @@  discard block
 block discarded – undo
53 53
  * @param $context
54 54
  * @return boolean - Returns true on success false on failure
55 55
  */
56
-function sugar_mkdir($pathname, $mode=null, $recursive=false, $context='') {
56
+function sugar_mkdir($pathname, $mode = null, $recursive = false, $context = '') {
57 57
 	$mode = get_mode('dir_mode', $mode);
58 58
 
59
-	if ( sugar_is_dir($pathname,$mode) )
59
+	if (sugar_is_dir($pathname, $mode))
60 60
 	    return true;
61 61
 
62 62
 	$result = false;
63
-	if(empty($mode))
63
+	if (empty($mode))
64 64
 		$mode = 0777;
65
-	if(empty($context)) {
65
+	if (empty($context)) {
66 66
 		$result = @mkdir($pathname, $mode, $recursive);
67 67
 	} else {
68 68
 		$result = @mkdir($pathname, $mode, $recursive, $context);
69 69
 	}
70 70
 
71
-	if($result){
72
-		if(!sugar_chmod($pathname, $mode)){
71
+	if ($result) {
72
+		if (!sugar_chmod($pathname, $mode)) {
73 73
 			return false;
74 74
 		}
75
-		if(!empty($GLOBALS['sugar_config']['default_permissions']['user'])){
76
-			if(!sugar_chown($pathname)){
75
+		if (!empty($GLOBALS['sugar_config']['default_permissions']['user'])) {
76
+			if (!sugar_chown($pathname)) {
77 77
 				return false;
78 78
 			}
79 79
 		}
80
-		if(!empty($GLOBALS['sugar_config']['default_permissions']['group'])){
81
-   			if(!sugar_chgrp($pathname)) {
80
+		if (!empty($GLOBALS['sugar_config']['default_permissions']['group'])) {
81
+   			if (!sugar_chgrp($pathname)) {
82 82
    				return false;
83 83
    			}
84 84
 		}
85 85
 	}
86 86
 	else {
87 87
 		$errorMessage = "Cannot create directory $pathname cannot be touched";
88
-		if(is_null($GLOBALS['log'])) {
88
+		if (is_null($GLOBALS['log'])) {
89 89
 			throw new Exception("Error occurred but the system doesn't have logger. Error message: \"$errorMessage\"");
90 90
 		}
91 91
 		$GLOBALS['log']->error($errorMessage);
@@ -108,13 +108,13 @@  discard block
 block discarded – undo
108 108
  * @param $context
109 109
  * @return boolean - Returns a file pointer on success, false otherwise
110 110
  */
111
-function sugar_fopen($filename, $mode, $use_include_path=false, $context=null){
111
+function sugar_fopen($filename, $mode, $use_include_path = false, $context = null) {
112 112
 	//check to see if the file exists, if not then use touch to create it.
113
-	if(!file_exists($filename)){
113
+	if (!file_exists($filename)) {
114 114
 		sugar_touch($filename);
115 115
 	}
116 116
 
117
-	if(empty($context)) {
117
+	if (empty($context)) {
118 118
 
119 119
 		return fopen($filename, $mode, $use_include_path);
120 120
 	} else {
@@ -136,22 +136,22 @@  discard block
 block discarded – undo
136 136
  * @param $context
137 137
  * @return int - Returns the number of bytes written to the file, false otherwise.
138 138
  */
139
-function sugar_file_put_contents($filename, $data, $flags=null, $context=null){
139
+function sugar_file_put_contents($filename, $data, $flags = null, $context = null) {
140 140
 	//check to see if the file exists, if not then use touch to create it.
141
-	if(!file_exists($filename)){
141
+	if (!file_exists($filename)) {
142 142
 		sugar_touch($filename);
143 143
 	}
144 144
 
145
-	if ( !is_writable($filename) ) {
145
+	if (!is_writable($filename)) {
146 146
 	    $GLOBALS['log']->error("File $filename cannot be written to");
147 147
 	    return false;
148 148
 	}
149 149
 
150
-	if(empty($flags)) {
150
+	if (empty($flags)) {
151 151
 		return file_put_contents($filename, $data);
152
-	} elseif(empty($context)) {
152
+	} elseif (empty($context)) {
153 153
 		return file_put_contents($filename, $data, $flags);
154
-	} else{
154
+	} else {
155 155
 		return file_put_contents($filename, $data, $flags, $context);
156 156
 	}
157 157
 }
@@ -169,13 +169,13 @@  discard block
 block discarded – undo
169 169
  * @param context $context Context to pass into fopen operation
170 170
  * @return boolean - Returns true if $filename was created, false otherwise.
171 171
  */
172
-function sugar_file_put_contents_atomic($filename, $data, $mode='wb', $use_include_path=false, $context=null){
172
+function sugar_file_put_contents_atomic($filename, $data, $mode = 'wb', $use_include_path = false, $context = null) {
173 173
 
174 174
     $dir = dirname($filename);
175 175
     $temp = tempnam($dir, 'temp');
176 176
 
177 177
     if (!($f = @fopen($temp, $mode))) {
178
-        $temp =  $dir . DIRECTORY_SEPARATOR . uniqid('temp');
178
+        $temp = $dir.DIRECTORY_SEPARATOR.uniqid('temp');
179 179
         if (!($f = @fopen($temp, $mode))) {
180 180
             trigger_error("sugar_file_put_contents_atomic() : error writing temporary file '$temp'", E_USER_WARNING);
181 181
             return false;
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
         }
197 197
     }
198 198
 
199
-    if(file_exists($filename))
199
+    if (file_exists($filename))
200 200
     {
201 201
        return sugar_chmod($filename, 0755);
202 202
     }
@@ -214,18 +214,18 @@  discard block
 block discarded – undo
214 214
  * @param $context
215 215
  * @return string|boolean - Returns a file data on success, false otherwise
216 216
  */
217
-function sugar_file_get_contents($filename, $use_include_path=false, $context=null){
217
+function sugar_file_get_contents($filename, $use_include_path = false, $context = null) {
218 218
 	//check to see if the file exists, if not then use touch to create it.
219
-	if(!file_exists($filename)){
219
+	if (!file_exists($filename)) {
220 220
 		sugar_touch($filename);
221 221
 	}
222 222
 
223
-	if ( !is_readable($filename) ) {
223
+	if (!is_readable($filename)) {
224 224
 	    $GLOBALS['log']->error("File $filename cannot be read");
225 225
 	    return false;
226 226
 	}
227 227
 
228
-	if(empty($context)) {
228
+	if (empty($context)) {
229 229
 		return file_get_contents($filename, $use_include_path);
230 230
 	} else {
231 231
 		return file_get_contents($filename, $use_include_path, $context);
@@ -246,29 +246,29 @@  discard block
 block discarded – undo
246 246
  * @return boolean - Returns TRUE on success or FALSE on failure.
247 247
  *
248 248
  */
249
-function sugar_touch($filename, $time=null, $atime=null) {
249
+function sugar_touch($filename, $time = null, $atime = null) {
250 250
 
251 251
    $result = false;
252 252
 
253
-   if(!empty($atime) && !empty($time)) {
253
+   if (!empty($atime) && !empty($time)) {
254 254
    	  $result = @touch($filename, $time, $atime);
255
-   } else if(!empty($time)) {
255
+   } else if (!empty($time)) {
256 256
    	  $result = @touch($filename, $time);
257 257
    } else {
258 258
    	  $result = @touch($filename);
259 259
    }
260 260
 
261
-   if(!$result) {
261
+   if (!$result) {
262 262
        $GLOBALS['log']->error("File $filename cannot be touched");
263 263
        return $result;
264 264
    }
265
-	if(!empty($GLOBALS['sugar_config']['default_permissions']['file_mode'])){
265
+	if (!empty($GLOBALS['sugar_config']['default_permissions']['file_mode'])) {
266 266
 		sugar_chmod($filename, $GLOBALS['sugar_config']['default_permissions']['file_mode']);
267 267
 	}
268
-	if(!empty($GLOBALS['sugar_config']['default_permissions']['user'])){
268
+	if (!empty($GLOBALS['sugar_config']['default_permissions']['user'])) {
269 269
 		sugar_chown($filename);
270 270
 	}
271
-	if(!empty($GLOBALS['sugar_config']['default_permissions']['group'])){
271
+	if (!empty($GLOBALS['sugar_config']['default_permissions']['group'])) {
272 272
 		sugar_chgrp($filename);
273 273
 	}
274 274
 
@@ -284,16 +284,16 @@  discard block
 block discarded – undo
284 284
  * @param  int $mode The integer value of the permissions mode to set the created directory to
285 285
  * @return boolean   Returns TRUE on success or FALSE on failure.
286 286
  */
287
-function sugar_chmod($filename, $mode=null) {
288
-    if ( !is_int($mode) )
289
-        $mode = (int) $mode;
290
-	if(!is_windows()){
291
-		if(!isset($mode)){
287
+function sugar_chmod($filename, $mode = null) {
288
+    if (!is_int($mode))
289
+        $mode = (int)$mode;
290
+	if (!is_windows()) {
291
+		if (!isset($mode)) {
292 292
 			$mode = get_mode('file_mode', $mode);
293 293
 		}
294
-        if(isset($mode) && $mode > 0){
294
+        if (isset($mode) && $mode > 0) {
295 295
 		   return @chmod($filename, $mode);
296
-		}else{
296
+		} else {
297 297
 	    	return false;
298 298
 		}
299 299
 	}
@@ -309,15 +309,15 @@  discard block
 block discarded – undo
309 309
  * @param user - A user name or number
310 310
  * @return boolean - Returns TRUE on success or FALSE on failure.
311 311
  */
312
-function sugar_chown($filename, $user='') {
313
-	if(!is_windows()){
314
-		if(strlen($user)){
312
+function sugar_chown($filename, $user = '') {
313
+	if (!is_windows()) {
314
+		if (strlen($user)) {
315 315
 			return chown($filename, $user);
316
-		}else{
317
-			if(strlen($GLOBALS['sugar_config']['default_permissions']['user'])){
316
+		} else {
317
+			if (strlen($GLOBALS['sugar_config']['default_permissions']['user'])) {
318 318
 				$user = $GLOBALS['sugar_config']['default_permissions']['user'];
319 319
 				return chown($filename, $user);
320
-			}else{
320
+			} else {
321 321
 				return false;
322 322
 			}
323 323
 		}
@@ -334,15 +334,15 @@  discard block
 block discarded – undo
334 334
  * @param group - A group name or number
335 335
  * @return boolean - Returns TRUE on success or FALSE on failure.
336 336
  */
337
-function sugar_chgrp($filename, $group='') {
338
-	if(!is_windows()){
339
-		if(!empty($group)){
337
+function sugar_chgrp($filename, $group = '') {
338
+	if (!is_windows()) {
339
+		if (!empty($group)) {
340 340
 			return chgrp($filename, $group);
341
-		}else{
342
-			if(!empty($GLOBALS['sugar_config']['default_permissions']['group'])){
341
+		} else {
342
+			if (!empty($GLOBALS['sugar_config']['default_permissions']['group'])) {
343 343
 				$group = $GLOBALS['sugar_config']['default_permissions']['group'];
344 344
 				return chgrp($filename, $group);
345
-			}else{
345
+			} else {
346 346
 				return false;
347 347
 			}
348 348
 		}
@@ -360,26 +360,26 @@  discard block
 block discarded – undo
360 360
  * defined in the config file.
361 361
  * @return int - the mode either found in the config file or passed in via the input parameter
362 362
  */
363
-function get_mode($key = 'dir_mode', $mode=null) {
364
-	if ( !is_int($mode) )
365
-        $mode = (int) $mode;
366
-    if(!class_exists('SugarConfig', true)) {
363
+function get_mode($key = 'dir_mode', $mode = null) {
364
+	if (!is_int($mode))
365
+        $mode = (int)$mode;
366
+    if (!class_exists('SugarConfig', true)) {
367 367
 		require 'include/SugarObjects/SugarConfig.php';
368 368
 	}
369
-	if(!is_windows()){
370
-		$conf_inst=SugarConfig::getInstance();
369
+	if (!is_windows()) {
370
+		$conf_inst = SugarConfig::getInstance();
371 371
 		$mode = $conf_inst->get('default_permissions.'.$key, $mode);
372 372
 	}
373 373
 	return $mode;
374 374
 }
375 375
 
376
-function sugar_is_dir($path, $mode='r'){
377
-		if(defined('TEMPLATE_URL'))return is_dir($path, $mode);
376
+function sugar_is_dir($path, $mode = 'r') {
377
+		if (defined('TEMPLATE_URL'))return is_dir($path, $mode);
378 378
 		return is_dir($path);
379 379
 }
380 380
 
381
-function sugar_is_file($path, $mode='r'){
382
-		if(defined('TEMPLATE_URL'))return is_file($path, $mode);
381
+function sugar_is_file($path, $mode = 'r') {
382
+		if (defined('TEMPLATE_URL'))return is_file($path, $mode);
383 383
 		return is_file($path);
384 384
 }
385 385
 
@@ -391,10 +391,10 @@  discard block
 block discarded – undo
391 391
 function sugar_cached($file)
392 392
 {
393 393
     static $cdir = null;
394
-    if(empty($cdir) && !empty($GLOBALS['sugar_config']['cache_dir'])) {
394
+    if (empty($cdir) && !empty($GLOBALS['sugar_config']['cache_dir'])) {
395 395
         $cdir = rtrim($GLOBALS['sugar_config']['cache_dir'], '/\\');
396 396
     }
397
-    if(empty($cdir)) {
397
+    if (empty($cdir)) {
398 398
         $cdir = "cache";
399 399
     }
400 400
     return "$cdir/$file";
Please login to merge, or discard this patch.
Braces   +27 added lines, -18 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.
@@ -56,12 +58,14 @@  discard block
 block discarded – undo
56 58
 function sugar_mkdir($pathname, $mode=null, $recursive=false, $context='') {
57 59
 	$mode = get_mode('dir_mode', $mode);
58 60
 
59
-	if ( sugar_is_dir($pathname,$mode) )
60
-	    return true;
61
+	if ( sugar_is_dir($pathname,$mode) ) {
62
+		    return true;
63
+	}
61 64
 
62 65
 	$result = false;
63
-	if(empty($mode))
64
-		$mode = 0777;
66
+	if(empty($mode)) {
67
+			$mode = 0777;
68
+	}
65 69
 	if(empty($context)) {
66 70
 		$result = @mkdir($pathname, $mode, $recursive);
67 71
 	} else {
@@ -82,8 +86,7 @@  discard block
 block discarded – undo
82 86
    				return false;
83 87
    			}
84 88
 		}
85
-	}
86
-	else {
89
+	} else {
87 90
 		$errorMessage = "Cannot create directory $pathname cannot be touched";
88 91
 		if(is_null($GLOBALS['log'])) {
89 92
 			throw new Exception("Error occurred but the system doesn't have logger. Error message: \"$errorMessage\"");
@@ -285,15 +288,16 @@  discard block
 block discarded – undo
285 288
  * @return boolean   Returns TRUE on success or FALSE on failure.
286 289
  */
287 290
 function sugar_chmod($filename, $mode=null) {
288
-    if ( !is_int($mode) )
289
-        $mode = (int) $mode;
291
+    if ( !is_int($mode) ) {
292
+            $mode = (int) $mode;
293
+    }
290 294
 	if(!is_windows()){
291 295
 		if(!isset($mode)){
292 296
 			$mode = get_mode('file_mode', $mode);
293 297
 		}
294 298
         if(isset($mode) && $mode > 0){
295 299
 		   return @chmod($filename, $mode);
296
-		}else{
300
+		} else{
297 301
 	    	return false;
298 302
 		}
299 303
 	}
@@ -313,11 +317,11 @@  discard block
 block discarded – undo
313 317
 	if(!is_windows()){
314 318
 		if(strlen($user)){
315 319
 			return chown($filename, $user);
316
-		}else{
320
+		} else{
317 321
 			if(strlen($GLOBALS['sugar_config']['default_permissions']['user'])){
318 322
 				$user = $GLOBALS['sugar_config']['default_permissions']['user'];
319 323
 				return chown($filename, $user);
320
-			}else{
324
+			} else{
321 325
 				return false;
322 326
 			}
323 327
 		}
@@ -338,11 +342,11 @@  discard block
 block discarded – undo
338 342
 	if(!is_windows()){
339 343
 		if(!empty($group)){
340 344
 			return chgrp($filename, $group);
341
-		}else{
345
+		} else{
342 346
 			if(!empty($GLOBALS['sugar_config']['default_permissions']['group'])){
343 347
 				$group = $GLOBALS['sugar_config']['default_permissions']['group'];
344 348
 				return chgrp($filename, $group);
345
-			}else{
349
+			} else{
346 350
 				return false;
347 351
 			}
348 352
 		}
@@ -361,8 +365,9 @@  discard block
 block discarded – undo
361 365
  * @return int - the mode either found in the config file or passed in via the input parameter
362 366
  */
363 367
 function get_mode($key = 'dir_mode', $mode=null) {
364
-	if ( !is_int($mode) )
365
-        $mode = (int) $mode;
368
+	if ( !is_int($mode) ) {
369
+	        $mode = (int) $mode;
370
+	}
366 371
     if(!class_exists('SugarConfig', true)) {
367 372
 		require 'include/SugarObjects/SugarConfig.php';
368 373
 	}
@@ -374,12 +379,16 @@  discard block
 block discarded – undo
374 379
 }
375 380
 
376 381
 function sugar_is_dir($path, $mode='r'){
377
-		if(defined('TEMPLATE_URL'))return is_dir($path, $mode);
382
+		if(defined('TEMPLATE_URL')) {
383
+		    return is_dir($path, $mode);
384
+		}
378 385
 		return is_dir($path);
379 386
 }
380 387
 
381 388
 function sugar_is_file($path, $mode='r'){
382
-		if(defined('TEMPLATE_URL'))return is_file($path, $mode);
389
+		if(defined('TEMPLATE_URL')) {
390
+		    return is_file($path, $mode);
391
+		}
383 392
 		return is_file($path);
384 393
 }
385 394
 
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/View/SugarView.php 4 patches
Switch Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -1387,18 +1387,18 @@
 block discarded – undo
1387 1387
 		//$params = array();
1388 1388
         if (isset($this->action)){
1389 1389
             switch ($this->action) {
1390
-            case 'EditView':
1391
-                if(!empty($this->bean->id) && (empty($_REQUEST['isDuplicate']) || $_REQUEST['isDuplicate'] === 'false')) {
1392
-                    $params[] = "<a href='index.php?module={$this->module}&action=DetailView&record={$this->bean->id}'>".$this->bean->get_summary_text()."</a>";
1393
-                    $params[] = $GLOBALS['app_strings']['LBL_EDIT_BUTTON_LABEL'];
1394
-                }
1395
-                else
1396
-                    $params[] = $GLOBALS['app_strings']['LBL_CREATE_BUTTON_LABEL'];
1397
-                break;
1398
-            case 'DetailView':
1399
-                $beanName = $this->bean->get_summary_text();
1400
-                $params[] = $beanName;
1401
-                break;
1390
+                case 'EditView':
1391
+                    if(!empty($this->bean->id) && (empty($_REQUEST['isDuplicate']) || $_REQUEST['isDuplicate'] === 'false')) {
1392
+                        $params[] = "<a href='index.php?module={$this->module}&action=DetailView&record={$this->bean->id}'>".$this->bean->get_summary_text()."</a>";
1393
+                        $params[] = $GLOBALS['app_strings']['LBL_EDIT_BUTTON_LABEL'];
1394
+                    }
1395
+                    else
1396
+                        $params[] = $GLOBALS['app_strings']['LBL_CREATE_BUTTON_LABEL'];
1397
+                    break;
1398
+                case 'DetailView':
1399
+                    $beanName = $this->bean->get_summary_text();
1400
+                    $params[] = $beanName;
1401
+                    break;
1402 1402
             }
1403 1403
         }
1404 1404
 
Please login to merge, or discard this patch.
Indentation   +135 added lines, -135 removed lines patch added patch discarded remove patch
@@ -125,11 +125,11 @@  discard block
 block discarded – undo
125 125
 
126 126
         //For the ajaxUI, we need to use output buffering to return the page in an ajax friendly format
127 127
         if ($this->_getOption('json_output')){
128
-			ob_start();
129
-			if(!empty($_REQUEST['ajax_load']) && !empty($_REQUEST['loadLanguageJS'])) {
130
-				echo $this->_getModLanguageJS();
131
-			}
132
-		}
128
+            ob_start();
129
+            if(!empty($_REQUEST['ajax_load']) && !empty($_REQUEST['loadLanguageJS'])) {
130
+                echo $this->_getModLanguageJS();
131
+            }
132
+        }
133 133
 
134 134
         if ($this->_getOption('show_header')) {
135 135
             $this->displayHeader();
@@ -175,11 +175,11 @@  discard block
 block discarded – undo
175 175
             $module = $this->module;
176 176
             $ajax_ret = array(
177 177
                 'content' => mb_detect_encoding($content) == "UTF-8" ? $content : utf8_encode($content),
178
-                 'menu' => array(
179
-                     'module' => $module,
180
-                     'label' => translate($module),
181
-                     $this->getMenu($module),
182
-                 ),
178
+                    'menu' => array(
179
+                        'module' => $module,
180
+                        'label' => translate($module),
181
+                        $this->getMenu($module),
182
+                    ),
183 183
                 'title' => $this->getBrowserTitle(),
184 184
                 'action' => isset($_REQUEST['action']) ? $_REQUEST['action'] : "",
185 185
                 'record' => isset($_REQUEST['record']) ? $_REQUEST['record'] : "",
@@ -422,10 +422,10 @@  discard block
 block discarded – undo
422 422
                         "URL"   => current($attributevalue),
423 423
                         "SUBMENU" => array(),
424 424
                         );
425
-                   if(substr($gcls[$key]["URL"], 0, 11) == "javascript:") {
426
-                       $gcls[$key]["ONCLICK"] = substr($gcls[$key]["URL"],11);
427
-                       $gcls[$key]["URL"] = "javascript:void(0)";
428
-                   }
425
+                    if(substr($gcls[$key]["URL"], 0, 11) == "javascript:") {
426
+                        $gcls[$key]["ONCLICK"] = substr($gcls[$key]["URL"],11);
427
+                        $gcls[$key]["URL"] = "javascript:void(0)";
428
+                    }
429 429
                 }
430 430
                 // and now the sublinks
431 431
                 if ( $linkattribute == 'submenu' && is_array($attributevalue) ) {
@@ -434,10 +434,10 @@  discard block
 block discarded – undo
434 434
                             "LABEL" => key($submenulinkinfo),
435 435
                             "URL"   => current($submenulinkinfo),
436 436
                         );
437
-                       if(substr($gcls[$key]['SUBMENU'][$submenulinkkey]["URL"], 0, 11) == "javascript:") {
438
-                           $gcls[$key]['SUBMENU'][$submenulinkkey]["ONCLICK"] = substr($gcls[$key]['SUBMENU'][$submenulinkkey]["URL"],11);
439
-                           $gcls[$key]['SUBMENU'][$submenulinkkey]["URL"] = "javascript:void(0)";
440
-                       }
437
+                        if(substr($gcls[$key]['SUBMENU'][$submenulinkkey]["URL"], 0, 11) == "javascript:") {
438
+                            $gcls[$key]['SUBMENU'][$submenulinkkey]["ONCLICK"] = substr($gcls[$key]['SUBMENU'][$submenulinkkey]["URL"],11);
439
+                            $gcls[$key]['SUBMENU'][$submenulinkkey]["URL"] = "javascript:void(0)";
440
+                        }
441 441
                 }
442 442
             }
443 443
         }
@@ -665,14 +665,14 @@  discard block
 block discarded – undo
665 665
             $ss->assign("shortcutExtraMenu",$shortcutExtraMenu);
666 666
         }
667 667
 
668
-       if(!empty($current_user)){
669
-       	$ss->assign("max_tabs", $current_user->getPreference("max_tabs"));
670
-       }
668
+        if(!empty($current_user)){
669
+            $ss->assign("max_tabs", $current_user->getPreference("max_tabs"));
670
+        }
671 671
 
672 672
 
673 673
         $imageURL = SugarThemeRegistry::current()->getImageURL("dashboard.png");
674 674
         $homeImage = "<img src='$imageURL'>";
675
-		$ss->assign("homeImage",$homeImage);
675
+        $ss->assign("homeImage",$homeImage);
676 676
         global $mod_strings;
677 677
         $mod_strings = $bakModStrings;
678 678
         $headerTpl = $themeObject->getTemplate('header.tpl');
@@ -777,12 +777,12 @@  discard block
 block discarded – undo
777 777
         list ($num_grp_sep, $dec_sep) = get_number_seperators();
778 778
 
779 779
         $the_script = "<script type=\"text/javascript\">\n" . "\tvar time_reg_format = '" .
780
-             $timereg['format'] . "';\n" . "\tvar date_reg_format = '" .
781
-             $datereg['format'] . "';\n" . "\tvar date_reg_positions = { $date_pos };\n" .
782
-             "\tvar time_separator = '$time_separator';\n" .
783
-             "\tvar cal_date_format = '$cal_date_format';\n" .
784
-             "\tvar time_offset = $hour_offset;\n" . "\tvar num_grp_sep = '$num_grp_sep';\n" .
785
-             "\tvar dec_sep = '$dec_sep';\n" . "</script>";
780
+                $timereg['format'] . "';\n" . "\tvar date_reg_format = '" .
781
+                $datereg['format'] . "';\n" . "\tvar date_reg_positions = { $date_pos };\n" .
782
+                "\tvar time_separator = '$time_separator';\n" .
783
+                "\tvar cal_date_format = '$cal_date_format';\n" .
784
+                "\tvar time_offset = $hour_offset;\n" . "\tvar num_grp_sep = '$num_grp_sep';\n" .
785
+                "\tvar dec_sep = '$dec_sep';\n" . "</script>";
786 786
 
787 787
         return $the_script;
788 788
     }
@@ -847,7 +847,7 @@  discard block
 block discarded – undo
847 847
             }
848 848
             echo getVersionedScript('cache/jsLanguage/'. $GLOBALS['current_language'] . '.js', $GLOBALS['sugar_config']['js_lang_version']);
849 849
 
850
-			echo $this->_getModLanguageJS();
850
+            echo $this->_getModLanguageJS();
851 851
 
852 852
             if(isset( $sugar_config['disc_client']) && $sugar_config['disc_client'])
853 853
                 echo getVersionedScript('modules/Sync/headersync.js');
@@ -863,13 +863,13 @@  discard block
 block discarded – undo
863 863
         }
864 864
     }
865 865
 
866
-	protected function _getModLanguageJS(){
867
-		if (!is_file(sugar_cached('jsLanguage/') . $this->module . '/' . $GLOBALS['current_language'] . '.js')) {
868
-			require_once ('include/language/jsLanguage.php');
869
-			jsLanguage::createModuleStringsCache($this->module, $GLOBALS['current_language']);
870
-		}
871
-		return getVersionedScript("cache/jsLanguage/{$this->module}/". $GLOBALS['current_language'] . '.js', $GLOBALS['sugar_config']['js_lang_version']);
872
-	}
866
+    protected function _getModLanguageJS(){
867
+        if (!is_file(sugar_cached('jsLanguage/') . $this->module . '/' . $GLOBALS['current_language'] . '.js')) {
868
+            require_once ('include/language/jsLanguage.php');
869
+            jsLanguage::createModuleStringsCache($this->module, $GLOBALS['current_language']);
870
+        }
871
+        return getVersionedScript("cache/jsLanguage/{$this->module}/". $GLOBALS['current_language'] . '.js', $GLOBALS['sugar_config']['js_lang_version']);
872
+    }
873 873
 
874 874
     /**
875 875
      * Called from process(). This method will display the footer on the page.
@@ -882,7 +882,7 @@  discard block
 block discarded – undo
882 882
         global $sugar_config;
883 883
         global $app_strings;
884 884
         global $mod_strings;
885
-		$themeObject = SugarThemeRegistry::current();
885
+        $themeObject = SugarThemeRegistry::current();
886 886
         //decide whether or not to show themepicker, default is to show
887 887
         $showThemePicker = true;
888 888
         if (isset($sugar_config['showThemePicker'])) {
@@ -893,30 +893,30 @@  discard block
 block discarded – undo
893 893
         $ss->assign("AUTHENTICATED",isset($_SESSION["authenticated_user_id"]));
894 894
         $ss->assign('MOD',return_module_language($GLOBALS['current_language'], 'Users'));
895 895
 
896
-		$bottomLinkList = array();
897
-		 if (isset($this->action) && $this->action != "EditView") {
898
-			 $bottomLinkList['print'] = array($app_strings['LNK_PRINT'] => getPrintLink());
899
-		}
900
-		$bottomLinkList['backtotop'] = array($app_strings['LNK_BACKTOTOP'] => 'javascript:SUGAR.util.top();');
901
-
902
-		$bottomLinksStr = "";
903
-		foreach($bottomLinkList as $key => $value) {
904
-			foreach($value as $text => $link) {
905
-				   $href = $link;
906
-				   if(substr($link, 0, 11) == "javascript:") {
907
-                       $onclick = " onclick=\"".substr($link,11)."\"";
908
-                       $href = "javascript:void(0)";
909
-                   } else {
910
-                   		$onclick = "";
911
-                   	}
896
+        $bottomLinkList = array();
897
+            if (isset($this->action) && $this->action != "EditView") {
898
+                $bottomLinkList['print'] = array($app_strings['LNK_PRINT'] => getPrintLink());
899
+        }
900
+        $bottomLinkList['backtotop'] = array($app_strings['LNK_BACKTOTOP'] => 'javascript:SUGAR.util.top();');
901
+
902
+        $bottomLinksStr = "";
903
+        foreach($bottomLinkList as $key => $value) {
904
+            foreach($value as $text => $link) {
905
+                    $href = $link;
906
+                    if(substr($link, 0, 11) == "javascript:") {
907
+                        $onclick = " onclick=\"".substr($link,11)."\"";
908
+                        $href = "javascript:void(0)";
909
+                    } else {
910
+                            $onclick = "";
911
+                        }
912 912
                 $imageURL = SugarThemeRegistry::current()->getImageURL($key.'.gif');
913
-				$bottomLinksStr .= "<a href=\"{$href}\"";
914
-				$bottomLinksStr .= (isset($onclick)) ? $onclick : "";
915
-				$bottomLinksStr .= "><img src='{$imageURL}' alt=''>"; //keeping alt blank on purpose for 508 (text will be read instead)
916
-				$bottomLinksStr .= " ".$text."</a>";
917
-			}
918
-		}
919
-		$ss->assign("BOTTOMLINKS",$bottomLinksStr);
913
+                $bottomLinksStr .= "<a href=\"{$href}\"";
914
+                $bottomLinksStr .= (isset($onclick)) ? $onclick : "";
915
+                $bottomLinksStr .= "><img src='{$imageURL}' alt=''>"; //keeping alt blank on purpose for 508 (text will be read instead)
916
+                $bottomLinksStr .= " ".$text."</a>";
917
+            }
918
+        }
919
+        $ss->assign("BOTTOMLINKS",$bottomLinksStr);
920 920
         if (SugarConfig::getInstance()->get('calculate_response_time', false))
921 921
             $ss->assign('STATISTICS',$this->_getStatistics());
922 922
 
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
         $attribLinkImg = "<img style='margin-top: 2px' border='0' width='120' height='34' src='include/images/poweredby_sugarcrm_65.png' alt='Powered By SugarCRM'>\n";
947 947
 
948 948
 
949
-		// handle resizing of the company logo correctly on the fly
949
+        // handle resizing of the company logo correctly on the fly
950 950
         $companyLogoURL = $themeObject->getImageURL('company_logo.png');
951 951
         $companyLogoURL_arr = explode('?', $companyLogoURL);
952 952
         $companyLogoURL = $companyLogoURL_arr[0];
@@ -1069,7 +1069,7 @@  discard block
 block discarded – undo
1069 1069
 
1070 1070
 
1071 1071
         $trackerManager = TrackerManager::getInstance();
1072
-	    $trackerManager->save();
1072
+        $trackerManager->save();
1073 1073
 
1074 1074
     }
1075 1075
 
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
         $deltaTime = $endTime - $GLOBALS['startTime'];
1110 1110
         $response_time_string = $GLOBALS['app_strings']['LBL_SERVER_RESPONSE_TIME'] . ' ' . number_format(round($deltaTime, 2), 2) . ' ' . $GLOBALS['app_strings']['LBL_SERVER_RESPONSE_TIME_SECONDS'];
1111 1111
         $return = $response_time_string;
1112
-       // $return .= '<br />';
1112
+        // $return .= '<br />';
1113 1113
         if (!empty($GLOBALS['sugar_config']['show_page_resources'])) {
1114 1114
             // Print out the resources used in constructing the page.
1115 1115
             $included_files = get_included_files();
@@ -1170,8 +1170,8 @@  discard block
 block discarded – undo
1170 1170
             {
1171 1171
                 $data = array
1172 1172
                 (
1173
-                   !empty($this->module) ? $this->module : $GLOBALS['app_strings']['LBL_LINK_NONE'],
1174
-                   !empty($this->action) ? $this->action : $GLOBALS['app_strings']['LBL_LINK_NONE'],
1173
+                    !empty($this->module) ? $this->module : $GLOBALS['app_strings']['LBL_LINK_NONE'],
1174
+                    !empty($this->action) ? $this->action : $GLOBALS['app_strings']['LBL_LINK_NONE'],
1175 1175
                 );
1176 1176
 
1177 1177
                 $output = string_format($GLOBALS['app_strings']['LBL_SERVER_MEMORY_LOG_MESSAGE'], $data) . $newline;
@@ -1240,15 +1240,15 @@  discard block
 block discarded – undo
1240 1240
     }
1241 1241
 
1242 1242
     /**
1243
-    * Returns the module name which should be highlighted in the module menu
1243
+     * Returns the module name which should be highlighted in the module menu
1244 1244
      */
1245 1245
     protected function _getModuleTab()
1246 1246
     {
1247 1247
         global $app_list_strings, $moduleTabMap, $current_user;
1248 1248
 
1249
-		$userTabs = query_module_access_list($current_user);
1250
-		//If the home tab is in the user array use it as the default tab, otherwise use the first element in the tab array
1251
-		$defaultTab = (in_array("Home",$userTabs)) ? "Home" : key($userTabs);
1249
+        $userTabs = query_module_access_list($current_user);
1250
+        //If the home tab is in the user array use it as the default tab, otherwise use the first element in the tab array
1251
+        $defaultTab = (in_array("Home",$userTabs)) ? "Home" : key($userTabs);
1252 1252
 
1253 1253
         // Need to figure out what tab this module belongs to, most modules have their own tabs, but there are exceptions.
1254 1254
         if ( !empty($_REQUEST['module_tab']) )
@@ -1264,17 +1264,17 @@  discard block
 block discarded – undo
1264 1264
         elseif ( !isset($app_list_strings['moduleList'][$this->module]) )
1265 1265
             return $defaultTab;
1266 1266
         elseif ( isset($_REQUEST['action']) && $_REQUEST['action'] == "ajaxui" )
1267
-        	return $defaultTab;
1267
+            return $defaultTab;
1268 1268
         else
1269 1269
             return $this->module;
1270 1270
     }
1271 1271
 
1272
-   /**
1273
-    * Return the "breadcrumbs" to display at the top of the page
1274
-    *
1275
-    * @param  bool $show_help optional, true if we show the help links
1276
-    * @return HTML string containing breadcrumb title
1277
-    */
1272
+    /**
1273
+     * Return the "breadcrumbs" to display at the top of the page
1274
+     *
1275
+     * @param  bool $show_help optional, true if we show the help links
1276
+     * @return HTML string containing breadcrumb title
1277
+     */
1278 1278
     public function getModuleTitle(
1279 1279
         $show_help = true
1280 1280
         )
@@ -1288,13 +1288,13 @@  discard block
 block discarded – undo
1288 1288
         $params = $this->_getModuleTitleParams();
1289 1289
         $index = 0;
1290 1290
 
1291
-		if(SugarThemeRegistry::current()->directionality == "rtl") {
1292
-			$params = array_reverse($params);
1293
-		}
1294
-		if(count($params) > 1) {
1295
-			array_shift($params);
1296
-		}
1297
-		$count = count($params);
1291
+        if(SugarThemeRegistry::current()->directionality == "rtl") {
1292
+            $params = array_reverse($params);
1293
+        }
1294
+        if(count($params) > 1) {
1295
+            array_shift($params);
1296
+        }
1297
+        $count = count($params);
1298 1298
         $paramString = '';
1299 1299
         foreach($params as $parm){
1300 1300
             $index++;
@@ -1305,13 +1305,13 @@  discard block
 block discarded – undo
1305 1305
         }
1306 1306
 
1307 1307
         if(!empty($paramString)){
1308
-               $theTitle .= "<h2> $paramString </h2>";
1308
+                $theTitle .= "<h2> $paramString </h2>";
1309 1309
 
1310 1310
             if($this->type == "detail"){
1311 1311
                 $theTitle .= "<div class='favorite' record_id='" . $this->bean->id . "' module='" . $this->bean->module_dir . "'><div class='favorite_icon_outline'>" . SugarThemeRegistry::current()->getImage('favorite-star-outline','title="' . translate('LBL_DASHLET_EDIT', 'Home') . '" border="0"  align="absmiddle"', null,null,'.gif',translate('LBL_DASHLET_EDIT', 'Home')) . "</div>
1312 1312
                                                     <div class='favorite_icon_fill'>" . SugarThemeRegistry::current()->getImage('favorite-star','title="' . translate('LBL_DASHLET_EDIT', 'Home') . '" border="0"  align="absmiddle"', null,null,'.gif',translate('LBL_DASHLET_EDIT', 'Home')) . "</div></div>";
1313 1313
             }
1314
-           }
1314
+            }
1315 1315
 
1316 1316
         // bug 56131 - restore conditional so that link doesn't appear where it shouldn't
1317 1317
         if($show_help || $this->type == 'list') {
@@ -1384,7 +1384,7 @@  discard block
 block discarded – undo
1384 1384
     protected function _getModuleTitleParams($browserTitle = false)
1385 1385
     {
1386 1386
         $params = array($this->_getModuleTitleListParam($browserTitle));
1387
-		//$params = array();
1387
+        //$params = array();
1388 1388
         if (isset($this->action)){
1389 1389
             switch ($this->action) {
1390 1390
             case 'EditView':
@@ -1414,48 +1414,48 @@  discard block
 block discarded – undo
1414 1414
      */
1415 1415
     protected function _getModuleTitleListParam( $browserTitle = false )
1416 1416
     {
1417
-    	global $current_user;
1418
-    	global $app_strings;
1419
-
1420
-    	if(!empty($GLOBALS['app_list_strings']['moduleList'][$this->module]))
1421
-    		$firstParam = $GLOBALS['app_list_strings']['moduleList'][$this->module];
1422
-    	else
1423
-    		$firstParam = $this->module;
1424
-
1425
-    	$iconPath = $this->getModuleTitleIconPath($this->module);
1426
-    	if($this->action == "ListView" || $this->action == "index") {
1427
-    	    if (!empty($iconPath) && !$browserTitle) {
1428
-    	    	if (SugarThemeRegistry::current()->directionality == "ltr") {
1429
-    	    		return $app_strings['LBL_SEARCH']."&nbsp;"
1430
-    	    			 . "$firstParam";
1431
-
1432
-    	    	} else {
1433
-					return "$firstParam"
1434
-					     . "&nbsp;".$app_strings['LBL_SEARCH'];
1435
-    	    	}
1436
-			} else {
1437
-				return $firstParam;
1438
-			}
1439
-    	}
1440
-    	else {
1441
-		    if (!empty($iconPath) && !$browserTitle) {
1442
-				//return "<a href='index.php?module={$this->module}&action=index'>$this->module</a>";
1443
-			} else {
1444
-				return $firstParam;
1445
-			}
1446
-    	}
1417
+        global $current_user;
1418
+        global $app_strings;
1419
+
1420
+        if(!empty($GLOBALS['app_list_strings']['moduleList'][$this->module]))
1421
+            $firstParam = $GLOBALS['app_list_strings']['moduleList'][$this->module];
1422
+        else
1423
+            $firstParam = $this->module;
1424
+
1425
+        $iconPath = $this->getModuleTitleIconPath($this->module);
1426
+        if($this->action == "ListView" || $this->action == "index") {
1427
+            if (!empty($iconPath) && !$browserTitle) {
1428
+                if (SugarThemeRegistry::current()->directionality == "ltr") {
1429
+                    return $app_strings['LBL_SEARCH']."&nbsp;"
1430
+                            . "$firstParam";
1431
+
1432
+                } else {
1433
+                    return "$firstParam"
1434
+                            . "&nbsp;".$app_strings['LBL_SEARCH'];
1435
+                }
1436
+            } else {
1437
+                return $firstParam;
1438
+            }
1439
+        }
1440
+        else {
1441
+            if (!empty($iconPath) && !$browserTitle) {
1442
+                //return "<a href='index.php?module={$this->module}&action=index'>$this->module</a>";
1443
+            } else {
1444
+                return $firstParam;
1445
+            }
1446
+        }
1447 1447
     }
1448 1448
 
1449 1449
     protected function getModuleTitleIconPath($module)
1450 1450
     {
1451
-    	$iconPath = "";
1452
-    	if(is_file(SugarThemeRegistry::current()->getImageURL('icon_'.$module.'_32.png',false))) {
1453
-    		$iconPath = SugarThemeRegistry::current()->getImageURL('icon_'.$module.'_32.png');
1454
-    	}
1455
-    	else if (is_file(SugarThemeRegistry::current()->getImageURL('icon_'.ucfirst($module).'_32.png',false))) {
1456
-    		$iconPath = SugarThemeRegistry::current()->getImageURL('icon_'.ucfirst($module).'_32.png');
1457
-    	}
1458
-    	return $iconPath;
1451
+        $iconPath = "";
1452
+        if(is_file(SugarThemeRegistry::current()->getImageURL('icon_'.$module.'_32.png',false))) {
1453
+            $iconPath = SugarThemeRegistry::current()->getImageURL('icon_'.$module.'_32.png');
1454
+        }
1455
+        else if (is_file(SugarThemeRegistry::current()->getImageURL('icon_'.ucfirst($module).'_32.png',false))) {
1456
+            $iconPath = SugarThemeRegistry::current()->getImageURL('icon_'.ucfirst($module).'_32.png');
1457
+        }
1458
+        return $iconPath;
1459 1459
     }
1460 1460
 
1461 1461
     /**
@@ -1485,11 +1485,11 @@  discard block
 block discarded – undo
1485 1485
      */
1486 1486
     public function getBreadCrumbSymbol()
1487 1487
     {
1488
-    	if(SugarThemeRegistry::current()->directionality == "ltr") {
1489
-        	return "<span class='pointer'>&raquo;</span>";
1488
+        if(SugarThemeRegistry::current()->directionality == "ltr") {
1489
+            return "<span class='pointer'>&raquo;</span>";
1490 1490
         }
1491 1491
         else {
1492
-        	return "<span class='pointer'>&laquo;</span>";
1492
+            return "<span class='pointer'>&laquo;</span>";
1493 1493
         }
1494 1494
     }
1495 1495
 
@@ -1658,20 +1658,20 @@  discard block
 block discarded – undo
1658 1658
     }
1659 1659
 
1660 1660
     /**
1661
-	 * Determines whether the state of the post global array indicates there was an error uploading a
1661
+     * Determines whether the state of the post global array indicates there was an error uploading a
1662 1662
      * file that exceeds the post_max_size setting.  Such an error can be detected if:
1663 1663
      *  1. The Server['REQUEST_METHOD'] will still point to POST
1664 1664
      *  2. POST and FILES global arrays will be returned empty despite the request method
1665 1665
      * This also results in a redirect to the home page (due to lack of module and action in POST)
1666 1666
      *
1667
-	 * @return boolean indicating true or false
1668
-	 */
1667
+     * @return boolean indicating true or false
1668
+     */
1669 1669
     public function checkPostMaxSizeError(){
1670
-         //if the referrer is post, and the post array is empty, then an error has occurred, most likely
1671
-         //while uploading a file that exceeds the post_max_size.
1672
-         if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
1673
-             $GLOBALS['log']->fatal($GLOBALS['app_strings']['UPLOAD_ERROR_HOME_TEXT']);
1674
-             return true;
1670
+            //if the referrer is post, and the post array is empty, then an error has occurred, most likely
1671
+            //while uploading a file that exceeds the post_max_size.
1672
+            if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
1673
+                $GLOBALS['log']->fatal($GLOBALS['app_strings']['UPLOAD_ERROR_HOME_TEXT']);
1674
+                return true;
1675 1675
         }
1676 1676
         return false;
1677 1677
     }
Please login to merge, or discard this patch.
Braces   +132 added lines, -107 removed lines patch added patch discarded remove patch
@@ -102,8 +102,7 @@  discard block
 block discarded – undo
102 102
         $deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
103 103
         if(isset($GLOBALS['log'])) {
104 104
             $GLOBALS['log']->deprecated($deprecatedMessage);
105
-        }
106
-        else {
105
+        } else {
107 106
             trigger_error($deprecatedMessage, E_USER_DEPRECATED);
108 107
         }
109 108
         self::__construct($bean, $view_object_map);
@@ -178,13 +177,17 @@  discard block
 block discarded – undo
178 177
             echo $jsAlerts->getScript();
179 178
         }
180 179
 
181
-        if ($this->_getOption('show_subpanels') && !empty($_REQUEST['record'])) $this->_displaySubPanels();
180
+        if ($this->_getOption('show_subpanels') && !empty($_REQUEST['record'])) {
181
+            $this->_displaySubPanels();
182
+        }
182 183
 
183 184
         if ($this->action === 'Login') {
184 185
             //this is needed for a faster loading login page ie won't render unless the tables are closed
185 186
             ob_flush();
186 187
         }
187
-        if ($this->_getOption('show_footer')) $this->displayFooter();
188
+        if ($this->_getOption('show_footer')) {
189
+            $this->displayFooter();
190
+        }
188 191
         $GLOBALS['logic_hook']->call_custom_logic('', 'after_ui_footer');
189 192
         if ($this->_getOption('json_output'))
190 193
         {
@@ -203,11 +206,13 @@  discard block
 block discarded – undo
203 206
                 'favicon' => $this->getFavicon(),
204 207
             );
205 208
 
206
-            if(SugarThemeRegistry::current()->name == 'Classic' || SugarThemeRegistry::current()->classic)
207
-                $ajax_ret['moduleList'] = $this->displayHeader(true);
209
+            if(SugarThemeRegistry::current()->name == 'Classic' || SugarThemeRegistry::current()->classic) {
210
+                            $ajax_ret['moduleList'] = $this->displayHeader(true);
211
+            }
208 212
 
209
-            if(empty($this->responseTime))
210
-                $this->_calculateFooterMetrics();
213
+            if(empty($this->responseTime)) {
214
+                            $this->_calculateFooterMetrics();
215
+            }
211 216
             $ajax_ret['responseTime'] = $this->responseTime;
212 217
             $json = getJSONobj();
213 218
             echo $json->encode($ajax_ret);
@@ -231,8 +236,7 @@  discard block
 block discarded – undo
231 236
 
232 237
         if ( !$this->suppressDisplayErrors ) {
233 238
             echo $errors;
234
-        }
235
-        else {
239
+        } else {
236 240
             return $errors;
237 241
         }
238 242
     }
@@ -346,24 +350,26 @@  discard block
 block discarded – undo
346 350
         ob_end_clean();
347 351
 
348 352
         // get favicon
349
-        if(isset($GLOBALS['sugar_config']['default_module_favicon']))
350
-            $module_favicon = $GLOBALS['sugar_config']['default_module_favicon'];
351
-        else
352
-            $module_favicon = false;
353
+        if(isset($GLOBALS['sugar_config']['default_module_favicon'])) {
354
+                    $module_favicon = $GLOBALS['sugar_config']['default_module_favicon'];
355
+        } else {
356
+                    $module_favicon = false;
357
+        }
353 358
 
354 359
         $favicon = $this->getFavicon();
355 360
         $ss->assign('FAVICON_URL', $favicon['url']);
356 361
 
357 362
         // build the shortcut menu
358 363
         $shortcut_menu = array();
359
-        foreach ( $this->getMenu() as $key => $menu_item )
360
-            $shortcut_menu[$key] = array(
364
+        foreach ( $this->getMenu() as $key => $menu_item ) {
365
+                    $shortcut_menu[$key] = array(
361 366
                 "URL"         => $menu_item[0],
362 367
                 "LABEL"       => $menu_item[1],
363 368
                 "MODULE_NAME" => $menu_item[2],
364 369
                 "IMAGE"       => $themeObject
365 370
                     ->getImage($menu_item[2],"border='0' align='absmiddle'",null,null,'.gif',$menu_item[1]),
366 371
                 );
372
+        }
367 373
         $ss->assign("SHORTCUT_MENU",$shortcut_menu);
368 374
 
369 375
         // handle rtl text direction
@@ -387,8 +393,7 @@  discard block
 block discarded – undo
387 393
             $ss->assign("COMPANY_LOGO_MD5", $company_logo_attributes[0]);
388 394
             $ss->assign("COMPANY_LOGO_WIDTH", $company_logo_attributes[1]);
389 395
             $ss->assign("COMPANY_LOGO_HEIGHT", $company_logo_attributes[2]);
390
-        }
391
-        else {
396
+        } else {
392 397
             // Always need to md5 the file
393 398
             $ss->assign("COMPANY_LOGO_MD5", md5_file($companyLogoURL));
394 399
 
@@ -396,14 +401,14 @@  discard block
 block discarded – undo
396 401
             if ( $width > 212 || $height > 40 ) {
397 402
                 $resizePctWidth  = ($width - 212)/212;
398 403
                 $resizePctHeight = ($height - 40)/40;
399
-                if ( $resizePctWidth > $resizePctHeight )
400
-                    $resizeAmount = $width / 212;
401
-                else
402
-                    $resizeAmount = $height / 40;
404
+                if ( $resizePctWidth > $resizePctHeight ) {
405
+                                    $resizeAmount = $width / 212;
406
+                } else {
407
+                                    $resizeAmount = $height / 40;
408
+                }
403 409
                 $ss->assign("COMPANY_LOGO_WIDTH", round($width * (1/$resizeAmount)));
404 410
                 $ss->assign("COMPANY_LOGO_HEIGHT", round($height * (1/$resizeAmount)));
405
-            }
406
-            else {
411
+            } else {
407 412
                 $ss->assign("COMPANY_LOGO_WIDTH", $width);
408 413
                 $ss->assign("COMPANY_LOGO_HEIGHT", $height);
409 414
             }
@@ -446,11 +451,12 @@  discard block
 block discarded – undo
446 451
                 }
447 452
                 // and now the sublinks
448 453
                 if ( $linkattribute == 'submenu' && is_array($attributevalue) ) {
449
-                    foreach ($attributevalue as $submenulinkkey => $submenulinkinfo)
450
-                        $gcls[$key]['SUBMENU'][$submenulinkkey] = array(
454
+                    foreach ($attributevalue as $submenulinkkey => $submenulinkinfo) {
455
+                                            $gcls[$key]['SUBMENU'][$submenulinkkey] = array(
451 456
                             "LABEL" => key($submenulinkinfo),
452 457
                             "URL"   => current($submenulinkinfo),
453 458
                         );
459
+                    }
454 460
                        if(substr($gcls[$key]['SUBMENU'][$submenulinkkey]["URL"], 0, 11) == "javascript:") {
455 461
                            $gcls[$key]['SUBMENU'][$submenulinkkey]["ONCLICK"] = substr($gcls[$key]['SUBMENU'][$submenulinkkey]["URL"],11);
456 462
                            $gcls[$key]['SUBMENU'][$submenulinkkey]["URL"] = "javascript:void(0)";
@@ -462,8 +468,9 @@  discard block
 block discarded – undo
462 468
 
463 469
         $ss->assign("SEARCH", isset($_REQUEST['query_string']) ? $_REQUEST['query_string'] : '');
464 470
 
465
-        if ($this->action == "EditView" || $this->action == "Login")
466
-            $ss->assign("ONLOAD", 'onload="set_focus()"');
471
+        if ($this->action == "EditView" || $this->action == "Login") {
472
+                    $ss->assign("ONLOAD", 'onload="set_focus()"');
473
+        }
467 474
 
468 475
         $ss->assign("AUTHENTICATED",isset($_SESSION["authenticated_user_id"]));
469 476
 
@@ -523,8 +530,7 @@  discard block
 block discarded – undo
523 530
                 foreach($frames as $key => $values){
524 531
                         $fullModuleList[$key] = $values;
525 532
                 }
526
-            }
527
-            elseif (isset($fullModuleList['iFrames'])) {
533
+            } elseif (isset($fullModuleList['iFrames'])) {
528 534
                 unset($fullModuleList['iFrames']);
529 535
             }
530 536
 
@@ -540,8 +546,7 @@  discard block
 block discarded – undo
540 546
                     // We have a default value. Use it
541 547
                     if(isset($GLOBALS['sugar_config']['default_max_tabs'])){
542 548
                         $max_tabs = $GLOBALS['sugar_config']['default_max_tabs'];
543
-                    }
544
-                    else{
549
+                    } else{
545 550
                         $max_tabs = 8;
546 551
                     }
547 552
                 }
@@ -650,7 +655,9 @@  discard block
 block discarded – undo
650 655
                         );
651 656
                 }
652 657
             }
653
-            if(!empty($sugar_config['lock_homepage']) && $sugar_config['lock_homepage'] == true) $ss->assign('lock_homepage', true);
658
+            if(!empty($sugar_config['lock_homepage']) && $sugar_config['lock_homepage'] == true) {
659
+                $ss->assign('lock_homepage', true);
660
+            }
654 661
             $ss->assign("groupTabs",$groupTabs);
655 662
             $ss->assign("shortcutTopMenu",$shortcutTopMenu);
656 663
             $ss->assign('USE_GROUP_TABS',$usingGroupTabs);
@@ -693,8 +700,9 @@  discard block
 block discarded – undo
693 700
         global $mod_strings;
694 701
         $mod_strings = $bakModStrings;
695 702
         $headerTpl = $themeObject->getTemplate('header.tpl');
696
-        if (inDeveloperMode() )
697
-            $ss->clear_compiled_tpl($headerTpl);
703
+        if (inDeveloperMode() ) {
704
+                    $ss->clear_compiled_tpl($headerTpl);
705
+        }
698 706
 
699 707
         if ($retModTabs)
700 708
         {
@@ -733,8 +741,9 @@  discard block
 block discarded – undo
733 741
         global $gridline, $request_string, $modListHeader, $dashletData, $authController, $locale, $currentModule, $import_bean_map, $image_path, $license;
734 742
         global $user_unique_key, $server_unique_key, $barChartColors, $modules_exempt_from_availability_check, $dictionary, $current_language, $beanList, $beanFiles, $sugar_build, $sugar_codename;
735 743
         global $timedate, $login_error; // cn: bug 13855 - timedate not available to classic views.
736
-        if (!empty($this->module))
737
-            $currentModule = $this->module;
744
+        if (!empty($this->module)) {
745
+                    $currentModule = $this->module;
746
+        }
738 747
         require_once ($file);
739 748
     }
740 749
 
@@ -764,8 +773,9 @@  discard block
 block discarded – undo
764 773
             if ( typeof(SUGAR.themes) == 'undefined' ) SUGAR.themes = {};
765 774
         </script>
766 775
 EOQ;
767
-        if(isset( $sugar_config['disc_client']) && $sugar_config['disc_client'])
768
-            echo getVersionedScript('modules/Sync/headersync.js');
776
+        if(isset( $sugar_config['disc_client']) && $sugar_config['disc_client']) {
777
+                    echo getVersionedScript('modules/Sync/headersync.js');
778
+        }
769 779
     }
770 780
 
771 781
     /**
@@ -866,8 +876,9 @@  discard block
 block discarded – undo
866 876
 
867 877
 			echo $this->_getModLanguageJS();
868 878
 
869
-            if(isset( $sugar_config['disc_client']) && $sugar_config['disc_client'])
870
-                echo getVersionedScript('modules/Sync/headersync.js');
879
+            if(isset( $sugar_config['disc_client']) && $sugar_config['disc_client']) {
880
+                            echo getVersionedScript('modules/Sync/headersync.js');
881
+            }
871 882
 
872 883
 
873 884
             //echo out the $js_vars variables as javascript variables
@@ -934,8 +945,9 @@  discard block
 block discarded – undo
934 945
 			}
935 946
 		}
936 947
 		$ss->assign("BOTTOMLINKS",$bottomLinksStr);
937
-        if (SugarConfig::getInstance()->get('calculate_response_time', false))
938
-            $ss->assign('STATISTICS',$this->_getStatistics());
948
+        if (SugarConfig::getInstance()->get('calculate_response_time', false)) {
949
+                    $ss->assign('STATISTICS',$this->_getStatistics());
950
+        }
939 951
 
940 952
         // Under the License referenced above, you are required to leave in all copyright statements in both
941 953
         // the code and end-user application.
@@ -973,8 +985,7 @@  discard block
 block discarded – undo
973 985
             $ss->assign("COMPANY_LOGO_MD5", $company_logo_attributes[0]);
974 986
             $ss->assign("COMPANY_LOGO_WIDTH", $company_logo_attributes[1]);
975 987
             $ss->assign("COMPANY_LOGO_HEIGHT", $company_logo_attributes[2]);
976
-        }
977
-        else {
988
+        } else {
978 989
             // Always need to md5 the file
979 990
             $ss->assign("COMPANY_LOGO_MD5", md5_file($companyLogoURL));
980 991
 
@@ -982,14 +993,14 @@  discard block
 block discarded – undo
982 993
             if ( $width > 212 || $height > 40 ) {
983 994
                 $resizePctWidth  = ($width - 212)/212;
984 995
                 $resizePctHeight = ($height - 40)/40;
985
-                if ( $resizePctWidth > $resizePctHeight )
986
-                    $resizeAmount = $width / 212;
987
-                else
988
-                    $resizeAmount = $height / 40;
996
+                if ( $resizePctWidth > $resizePctHeight ) {
997
+                                    $resizeAmount = $width / 212;
998
+                } else {
999
+                                    $resizeAmount = $height / 40;
1000
+                }
989 1001
                 $ss->assign("COMPANY_LOGO_WIDTH", round($width * (1/$resizeAmount)));
990 1002
                 $ss->assign("COMPANY_LOGO_HEIGHT", round($height * (1/$resizeAmount)));
991
-            }
992
-            else {
1003
+            } else {
993 1004
                 $ss->assign("COMPANY_LOGO_WIDTH", $width);
994 1005
                 $ss->assign("COMPANY_LOGO_HEIGHT", $height);
995 1006
             }
@@ -1047,8 +1058,9 @@  discard block
 block discarded – undo
1047 1058
 
1048 1059
     protected function _buildModuleList()
1049 1060
     {
1050
-        if (!empty($GLOBALS['current_user']) && empty($GLOBALS['modListHeader']))
1051
-            $GLOBALS['modListHeader'] = query_module_access_list($GLOBALS['current_user']);
1061
+        if (!empty($GLOBALS['current_user']) && empty($GLOBALS['modListHeader'])) {
1062
+                    $GLOBALS['modListHeader'] = query_module_access_list($GLOBALS['current_user']);
1063
+        }
1052 1064
     }
1053 1065
 
1054 1066
     /**
@@ -1068,7 +1080,9 @@  discard block
 block discarded – undo
1068 1080
             return $this->options['show_all'];
1069 1081
         } elseif (!empty($this->options) && isset($this->options[$option])) {
1070 1082
             return $this->options[$option];
1071
-        } else return $default;
1083
+        } else {
1084
+            return $default;
1085
+        }
1072 1086
     }
1073 1087
 
1074 1088
     /**
@@ -1105,10 +1119,11 @@  discard block
 block discarded – undo
1105 1119
 
1106 1120
     public function renderJavascript()
1107 1121
     {
1108
-        if ($this->action !== 'Login')
1109
-            $this->_displayJavascript();
1110
-        else
1111
-            $this->_displayLoginJS();
1122
+        if ($this->action !== 'Login') {
1123
+                    $this->_displayJavascript();
1124
+        } else {
1125
+                    $this->_displayLoginJS();
1126
+        }
1112 1127
     }
1113 1128
 
1114 1129
     private function _calculateFooterMetrics()
@@ -1215,8 +1230,9 @@  discard block
 block discarded – undo
1215 1230
     {
1216 1231
         global $current_language, $current_user, $mod_strings, $app_strings, $module_menu;
1217 1232
 
1218
-        if ( empty($module) )
1219
-            $module = $this->module;
1233
+        if ( empty($module) ) {
1234
+                    $module = $this->module;
1235
+        }
1220 1236
 
1221 1237
         //Need to make sure the mod_strings match the requested module or Menus may fail
1222 1238
         $curr_mod_strings = $mod_strings;
@@ -1237,13 +1253,14 @@  discard block
 block discarded – undo
1237 1253
                 $GLOBALS['mod_strings']['LNK_NEW_RECORD'],"{$GLOBALS['app_strings']['LBL_CREATE_BUTTON_LABEL']}$module" ,$module );
1238 1254
             $module_menu[] = array("index.php?module=$module&action=index", $GLOBALS['mod_strings']['LNK_LIST'],
1239 1255
                 $module, $module);
1240
-            if ( ($this->bean instanceOf SugarBean) && !empty($this->bean->importable) )
1241
-                if ( !empty($mod_strings['LNK_IMPORT_'.strtoupper($module)]) )
1256
+            if ( ($this->bean instanceOf SugarBean) && !empty($this->bean->importable) ) {
1257
+                            if ( !empty($mod_strings['LNK_IMPORT_'.strtoupper($module)]) )
1242 1258
                     $module_menu[] = array("index.php?module=Import&action=Step1&import_module=$module&return_module=$module&return_action=index",
1243 1259
                         $mod_strings['LNK_IMPORT_'.strtoupper($module)], "Import", $module);
1244
-                else
1245
-                    $module_menu[] = array("index.php?module=Import&action=Step1&import_module=$module&return_module=$module&return_action=index",
1260
+            } else {
1261
+                                    $module_menu[] = array("index.php?module=Import&action=Step1&import_module=$module&return_module=$module&return_action=index",
1246 1262
                         $app_strings['LBL_IMPORT'], "Import", $module);
1263
+                }
1247 1264
         }
1248 1265
         if (file_exists('custom/application/Ext/Menus/menu.ext.php')) {
1249 1266
             require('custom/application/Ext/Menus/menu.ext.php');
@@ -1268,22 +1285,25 @@  discard block
 block discarded – undo
1268 1285
 		$defaultTab = (in_array("Home",$userTabs)) ? "Home" : key($userTabs);
1269 1286
 
1270 1287
         // Need to figure out what tab this module belongs to, most modules have their own tabs, but there are exceptions.
1271
-        if ( !empty($_REQUEST['module_tab']) )
1272
-            return $_REQUEST['module_tab'];
1273
-        elseif ( isset($moduleTabMap[$this->module]) )
1274
-            return $moduleTabMap[$this->module];
1288
+        if ( !empty($_REQUEST['module_tab']) ) {
1289
+                    return $_REQUEST['module_tab'];
1290
+        } elseif ( isset($moduleTabMap[$this->module]) ) {
1291
+                    return $moduleTabMap[$this->module];
1292
+        }
1275 1293
         // Special cases
1276
-        elseif ( $this->module == 'MergeRecords' )
1277
-            return !empty($_REQUEST['merge_module']) ? $_REQUEST['merge_module'] : $_REQUEST['return_module'];
1278
-        elseif ( $this->module == 'Users' && $this->action == 'SetTimezone' )
1279
-            return $defaultTab;
1294
+        elseif ( $this->module == 'MergeRecords' ) {
1295
+                    return !empty($_REQUEST['merge_module']) ? $_REQUEST['merge_module'] : $_REQUEST['return_module'];
1296
+        } elseif ( $this->module == 'Users' && $this->action == 'SetTimezone' ) {
1297
+                    return $defaultTab;
1298
+        }
1280 1299
         // Default anonymous pages to be under Home
1281
-        elseif ( !isset($app_list_strings['moduleList'][$this->module]) )
1282
-            return $defaultTab;
1283
-        elseif ( isset($_REQUEST['action']) && $_REQUEST['action'] == "ajaxui" )
1284
-        	return $defaultTab;
1285
-        else
1286
-            return $this->module;
1300
+        elseif ( !isset($app_list_strings['moduleList'][$this->module]) ) {
1301
+                    return $defaultTab;
1302
+        } elseif ( isset($_REQUEST['action']) && $_REQUEST['action'] == "ajaxui" ) {
1303
+                	return $defaultTab;
1304
+        } else {
1305
+                    return $this->module;
1306
+        }
1287 1307
     }
1288 1308
 
1289 1309
    /**
@@ -1334,7 +1354,10 @@  discard block
 block discarded – undo
1334 1354
         if($show_help || $this->type == 'list') {
1335 1355
             $theTitle .= "<span class='utils'>";
1336 1356
             $createImageURL = SugarThemeRegistry::current()->getImageURL('create-record.gif');
1337
-            if($this->type == 'list') $theTitle .= '<a href="#" class="btn btn-success showsearch"><span class=" glyphicon glyphicon-search" aria-hidden="true"></span></a>';$url = ajaxLink("index.php?module=$module&action=EditView&return_module=$module&return_action=DetailView");
1357
+            if($this->type == 'list') {
1358
+                $theTitle .= '<a href="#" class="btn btn-success showsearch"><span class=" glyphicon glyphicon-search" aria-hidden="true"></span></a>';
1359
+            }
1360
+            $url = ajaxLink("index.php?module=$module&action=EditView&return_module=$module&return_action=DetailView");
1338 1361
             if($show_help) {
1339 1362
                 $theTitle .= <<<EOHTML
1340 1363
 &nbsp;
@@ -1366,14 +1389,14 @@  discard block
 block discarded – undo
1366 1389
         if(file_exists('custom/' .$coreMetaPath )){
1367 1390
             $metadataFile = 'custom/' . $coreMetaPath;
1368 1391
             $foundViewDefs = true;
1369
-        }else{
1392
+        } else{
1370 1393
             if(file_exists('custom/modules/'.$this->module.'/metadata/metafiles.php')){
1371 1394
                 require_once('custom/modules/'.$this->module.'/metadata/metafiles.php');
1372 1395
                 if(!empty($metafiles[$this->module][$viewDef])){
1373 1396
                     $metadataFile = $metafiles[$this->module][$viewDef];
1374 1397
                     $foundViewDefs = true;
1375 1398
                 }
1376
-            }elseif(file_exists('modules/'.$this->module.'/metadata/metafiles.php')){
1399
+            } elseif(file_exists('modules/'.$this->module.'/metadata/metafiles.php')){
1377 1400
                 require_once('modules/'.$this->module.'/metadata/metafiles.php');
1378 1401
                 if(!empty($metafiles[$this->module][$viewDef])){
1379 1402
                     $metadataFile = $metafiles[$this->module][$viewDef];
@@ -1408,9 +1431,9 @@  discard block
 block discarded – undo
1408 1431
                 if(!empty($this->bean->id) && (empty($_REQUEST['isDuplicate']) || $_REQUEST['isDuplicate'] === 'false')) {
1409 1432
                     $params[] = "<a href='index.php?module={$this->module}&action=DetailView&record={$this->bean->id}'>".$this->bean->get_summary_text()."</a>";
1410 1433
                     $params[] = $GLOBALS['app_strings']['LBL_EDIT_BUTTON_LABEL'];
1434
+                } else {
1435
+                                    $params[] = $GLOBALS['app_strings']['LBL_CREATE_BUTTON_LABEL'];
1411 1436
                 }
1412
-                else
1413
-                    $params[] = $GLOBALS['app_strings']['LBL_CREATE_BUTTON_LABEL'];
1414 1437
                 break;
1415 1438
             case 'DetailView':
1416 1439
                 $beanName = $this->bean->get_summary_text();
@@ -1434,10 +1457,11 @@  discard block
 block discarded – undo
1434 1457
     	global $current_user;
1435 1458
     	global $app_strings;
1436 1459
 
1437
-    	if(!empty($GLOBALS['app_list_strings']['moduleList'][$this->module]))
1438
-    		$firstParam = $GLOBALS['app_list_strings']['moduleList'][$this->module];
1439
-    	else
1440
-    		$firstParam = $this->module;
1460
+    	if(!empty($GLOBALS['app_list_strings']['moduleList'][$this->module])) {
1461
+    	    		$firstParam = $GLOBALS['app_list_strings']['moduleList'][$this->module];
1462
+    	} else {
1463
+    	    		$firstParam = $this->module;
1464
+    	}
1441 1465
 
1442 1466
     	$iconPath = $this->getModuleTitleIconPath($this->module);
1443 1467
     	if($this->action == "ListView" || $this->action == "index") {
@@ -1453,8 +1477,7 @@  discard block
 block discarded – undo
1453 1477
 			} else {
1454 1478
 				return $firstParam;
1455 1479
 			}
1456
-    	}
1457
-    	else {
1480
+    	} else {
1458 1481
 		    if (!empty($iconPath) && !$browserTitle) {
1459 1482
 				//return "<a href='index.php?module={$this->module}&action=index'>$this->module</a>";
1460 1483
 			} else {
@@ -1468,8 +1491,7 @@  discard block
 block discarded – undo
1468 1491
     	$iconPath = "";
1469 1492
     	if(is_file(SugarThemeRegistry::current()->getImageURL('icon_'.$module.'_32.png',false))) {
1470 1493
     		$iconPath = SugarThemeRegistry::current()->getImageURL('icon_'.$module.'_32.png');
1471
-    	}
1472
-    	else if (is_file(SugarThemeRegistry::current()->getImageURL('icon_'.ucfirst($module).'_32.png',false))) {
1494
+    	} else if (is_file(SugarThemeRegistry::current()->getImageURL('icon_'.ucfirst($module).'_32.png',false))) {
1473 1495
     		$iconPath = SugarThemeRegistry::current()->getImageURL('icon_'.ucfirst($module).'_32.png');
1474 1496
     	}
1475 1497
     	return $iconPath;
@@ -1486,11 +1508,13 @@  discard block
 block discarded – undo
1486 1508
         global $app_strings;
1487 1509
 
1488 1510
         $browserTitle = $app_strings['LBL_BROWSER_TITLE'];
1489
-        if ( $this->module == 'Users' && ($this->action == 'SetTimezone' || $this->action == 'Login') )
1490
-            return $browserTitle;
1511
+        if ( $this->module == 'Users' && ($this->action == 'SetTimezone' || $this->action == 'Login') ) {
1512
+                    return $browserTitle;
1513
+        }
1491 1514
         $params = $this->_getModuleTitleParams(true);
1492
-        foreach ($params as $value )
1493
-            $browserTitle = strip_tags($value) . ' &raquo; ' . $browserTitle;
1515
+        foreach ($params as $value ) {
1516
+                    $browserTitle = strip_tags($value) . ' &raquo; ' . $browserTitle;
1517
+        }
1494 1518
 
1495 1519
         return $browserTitle;
1496 1520
     }
@@ -1504,8 +1528,7 @@  discard block
 block discarded – undo
1504 1528
     {
1505 1529
     	if(SugarThemeRegistry::current()->directionality == "ltr") {
1506 1530
         	return "<span class='pointer'>&raquo;</span>";
1507
-        }
1508
-        else {
1531
+        } else {
1509 1532
         	return "<span class='pointer'>&laquo;</span>";
1510 1533
         }
1511 1534
     }
@@ -1527,8 +1550,7 @@  discard block
 block discarded – undo
1527 1550
         }
1528 1551
         if ( empty($sugar_config['disableAjaxUI']) ) {
1529 1552
             $config_js[] = "SUGAR.config.disableAjaxUI = false;";
1530
-        }
1531
-        else{
1553
+        } else{
1532 1554
             $config_js[] = "SUGAR.config.disableAjaxUI = true;";
1533 1555
         }
1534 1556
         if ( !empty($sugar_config['addAjaxBannedModules']) ){
@@ -1598,18 +1620,21 @@  discard block
 block discarded – undo
1598 1620
     protected function getFavicon()
1599 1621
     {
1600 1622
         // get favicon
1601
-        if(isset($GLOBALS['sugar_config']['default_module_favicon']))
1602
-            $module_favicon = $GLOBALS['sugar_config']['default_module_favicon'];
1603
-        else
1604
-            $module_favicon = false;
1623
+        if(isset($GLOBALS['sugar_config']['default_module_favicon'])) {
1624
+                    $module_favicon = $GLOBALS['sugar_config']['default_module_favicon'];
1625
+        } else {
1626
+                    $module_favicon = false;
1627
+        }
1605 1628
 
1606 1629
         $themeObject = SugarThemeRegistry::current();
1607 1630
 
1608 1631
         $favicon = '';
1609
-        if ( $module_favicon )
1610
-            $favicon = $themeObject->getImageURL($this->module.'.gif',false);
1611
-        if ( !sugar_is_file($favicon) || !$module_favicon )
1612
-            $favicon = $themeObject->getImageURL('sugar_icon.ico',false);
1632
+        if ( $module_favicon ) {
1633
+                    $favicon = $themeObject->getImageURL($this->module.'.gif',false);
1634
+        }
1635
+        if ( !sugar_is_file($favicon) || !$module_favicon ) {
1636
+                    $favicon = $themeObject->getImageURL('sugar_icon.ico',false);
1637
+        }
1613 1638
 
1614 1639
         $extension = pathinfo($favicon, PATHINFO_EXTENSION);
1615 1640
         switch ($extension)
Please login to merge, or discard this patch.
Spacing   +230 added lines, -231 removed lines patch added patch discarded remove patch
@@ -98,9 +98,9 @@  discard block
 block discarded – undo
98 98
      */
99 99
     public function SugarView($bean = null,
100 100
         $view_object_map = array()
101
-        ){
101
+        ) {
102 102
         $deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
103
-        if(isset($GLOBALS['log'])) {
103
+        if (isset($GLOBALS['log'])) {
104 104
             $GLOBALS['log']->deprecated($deprecatedMessage);
105 105
         }
106 106
         else {
@@ -141,9 +141,9 @@  discard block
 block discarded – undo
141 141
         $this->_trackView();
142 142
 
143 143
         //For the ajaxUI, we need to use output buffering to return the page in an ajax friendly format
144
-        if ($this->_getOption('json_output')){
144
+        if ($this->_getOption('json_output')) {
145 145
 			ob_start();
146
-			if(!empty($_REQUEST['ajax_load']) && !empty($_REQUEST['loadLanguageJS'])) {
146
+			if (!empty($_REQUEST['ajax_load']) && !empty($_REQUEST['loadLanguageJS'])) {
147 147
 				echo $this->_getModLanguageJS();
148 148
 			}
149 149
 		}
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
         $this->preDisplay();
159 159
         $this->displayErrors();
160 160
         $this->display();
161
-        if ( !empty($this->module) ) {
161
+        if (!empty($this->module)) {
162 162
             $GLOBALS['logic_hook']->call_custom_logic($this->module, 'after_ui_frame');
163 163
         } else {
164 164
             $GLOBALS['logic_hook']->call_custom_logic('', 'after_ui_frame');
@@ -203,10 +203,10 @@  discard block
 block discarded – undo
203 203
                 'favicon' => $this->getFavicon(),
204 204
             );
205 205
 
206
-            if(SugarThemeRegistry::current()->name == 'Classic' || SugarThemeRegistry::current()->classic)
206
+            if (SugarThemeRegistry::current()->name == 'Classic' || SugarThemeRegistry::current()->classic)
207 207
                 $ajax_ret['moduleList'] = $this->displayHeader(true);
208 208
 
209
-            if(empty($this->responseTime))
209
+            if (empty($this->responseTime))
210 210
                 $this->_calculateFooterMetrics();
211 211
             $ajax_ret['responseTime'] = $this->responseTime;
212 212
             $json = getJSONobj();
@@ -225,11 +225,11 @@  discard block
 block discarded – undo
225 225
     {
226 226
         $errors = '';
227 227
 
228
-        foreach($this->errors as $error) {
229
-            $errors .= '<span class="error">' . $error . '</span><br>';
228
+        foreach ($this->errors as $error) {
229
+            $errors .= '<span class="error">'.$error.'</span><br>';
230 230
         }
231 231
 
232
-        if ( !$this->suppressDisplayErrors ) {
232
+        if (!$this->suppressDisplayErrors) {
233 233
             echo $errors;
234 234
         }
235 235
         else {
@@ -266,14 +266,14 @@  discard block
 block discarded – undo
266 266
     {
267 267
         $action = strtolower($this->action);
268 268
         //Skip save, tracked in SugarBean instead
269
-        if($action == 'save') {
269
+        if ($action == 'save') {
270 270
         return;
271 271
         }
272 272
 
273 273
 
274 274
         $trackerManager = TrackerManager::getInstance();
275 275
         $timeStamp = TimeDate::getInstance()->nowDb();
276
-        if($monitor = $trackerManager->getMonitor('tracker')){
276
+        if ($monitor = $trackerManager->getMonitor('tracker')) {
277 277
             $monitor->setValue('action', $action);
278 278
             $monitor->setValue('user_id', $GLOBALS['current_user']->id);
279 279
             $monitor->setValue('module_name', $this->module);
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 
289 289
             //If visible is true, but there is no bean, do not track (invalid/unauthorized reference)
290 290
             //Also, do not track save actions where there is no bean id
291
-            if($monitor->visible && empty($this->bean->id)) {
291
+            if ($monitor->visible && empty($this->bean->id)) {
292 292
             $trackerManager->unsetMonitor($monitor);
293 293
             return;
294 294
             }
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
     /**
301 301
      * Displays the header on section of the page; basically everything before the content
302 302
      */
303
-    public function displayHeader($retModTabs=false)
303
+    public function displayHeader($retModTabs = false)
304 304
     {
305 305
         global $theme;
306 306
         global $max_tabs;
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
         $ss->assign("APP", $app_strings);
321 321
         $ss->assign("THEME", $theme);
322 322
         $ss->assign("THEME_CONFIG", $themeObject->getConfig());
323
-        $ss->assign("THEME_IE6COMPAT", $themeObject->ie6compat ? 'true':'false');
323
+        $ss->assign("THEME_IE6COMPAT", $themeObject->ie6compat ? 'true' : 'false');
324 324
         $ss->assign("MODULE_NAME", $this->module);
325 325
         $ss->assign("langHeader", get_language_header());
326 326
 
@@ -336,17 +336,17 @@  discard block
 block discarded – undo
336 336
         if ($this->_getOption('view_print')) {
337 337
             $css .= '<link rel="stylesheet" type="text/css" href="'.$themeObject->getCSSURL('print.css').'" media="all" />';
338 338
         }
339
-        $ss->assign("SUGAR_CSS",$css);
339
+        $ss->assign("SUGAR_CSS", $css);
340 340
 
341 341
         // get javascript
342 342
         ob_start();
343 343
         $this->renderJavascript();
344 344
 
345
-        $ss->assign("SUGAR_JS",ob_get_contents().$themeObject->getJS());
345
+        $ss->assign("SUGAR_JS", ob_get_contents().$themeObject->getJS());
346 346
         ob_end_clean();
347 347
 
348 348
         // get favicon
349
-        if(isset($GLOBALS['sugar_config']['default_module_favicon']))
349
+        if (isset($GLOBALS['sugar_config']['default_module_favicon']))
350 350
             $module_favicon = $GLOBALS['sugar_config']['default_module_favicon'];
351 351
         else
352 352
             $module_favicon = false;
@@ -356,24 +356,24 @@  discard block
 block discarded – undo
356 356
 
357 357
         // build the shortcut menu
358 358
         $shortcut_menu = array();
359
-        foreach ( $this->getMenu() as $key => $menu_item )
359
+        foreach ($this->getMenu() as $key => $menu_item)
360 360
             $shortcut_menu[$key] = array(
361 361
                 "URL"         => $menu_item[0],
362 362
                 "LABEL"       => $menu_item[1],
363 363
                 "MODULE_NAME" => $menu_item[2],
364 364
                 "IMAGE"       => $themeObject
365
-                    ->getImage($menu_item[2],"border='0' align='absmiddle'",null,null,'.gif',$menu_item[1]),
365
+                    ->getImage($menu_item[2], "border='0' align='absmiddle'", null, null, '.gif', $menu_item[1]),
366 366
                 );
367
-        $ss->assign("SHORTCUT_MENU",$shortcut_menu);
367
+        $ss->assign("SHORTCUT_MENU", $shortcut_menu);
368 368
 
369 369
         // handle rtl text direction
370
-        if(isset($_REQUEST['RTL']) && $_REQUEST['RTL'] == 'RTL'){
370
+        if (isset($_REQUEST['RTL']) && $_REQUEST['RTL'] == 'RTL') {
371 371
             $_SESSION['RTL'] = true;
372 372
         }
373
-        if(isset($_REQUEST['LTR']) && $_REQUEST['LTR'] == 'LTR'){
373
+        if (isset($_REQUEST['LTR']) && $_REQUEST['LTR'] == 'LTR') {
374 374
             unset($_SESSION['RTL']);
375 375
         }
376
-        if(isset($_SESSION['RTL']) && $_SESSION['RTL']){
376
+        if (isset($_SESSION['RTL']) && $_SESSION['RTL']) {
377 377
             $ss->assign("DIR", 'dir="RTL"');
378 378
         }
379 379
 
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
         $companyLogoURL = $companyLogoURL_arr[0];
384 384
 
385 385
         $company_logo_attributes = sugar_cache_retrieve('company_logo_attributes');
386
-        if(!empty($company_logo_attributes)) {
386
+        if (!empty($company_logo_attributes)) {
387 387
             $ss->assign("COMPANY_LOGO_MD5", $company_logo_attributes[0]);
388 388
             $ss->assign("COMPANY_LOGO_WIDTH", $company_logo_attributes[1]);
389 389
             $ss->assign("COMPANY_LOGO_HEIGHT", $company_logo_attributes[2]);
@@ -392,16 +392,16 @@  discard block
 block discarded – undo
392 392
             // Always need to md5 the file
393 393
             $ss->assign("COMPANY_LOGO_MD5", md5_file($companyLogoURL));
394 394
 
395
-            list($width,$height) = getimagesize($companyLogoURL);
396
-            if ( $width > 212 || $height > 40 ) {
397
-                $resizePctWidth  = ($width - 212)/212;
398
-                $resizePctHeight = ($height - 40)/40;
399
-                if ( $resizePctWidth > $resizePctHeight )
395
+            list($width, $height) = getimagesize($companyLogoURL);
396
+            if ($width > 212 || $height > 40) {
397
+                $resizePctWidth  = ($width - 212) / 212;
398
+                $resizePctHeight = ($height - 40) / 40;
399
+                if ($resizePctWidth > $resizePctHeight)
400 400
                     $resizeAmount = $width / 212;
401 401
                 else
402 402
                     $resizeAmount = $height / 40;
403
-                $ss->assign("COMPANY_LOGO_WIDTH", round($width * (1/$resizeAmount)));
404
-                $ss->assign("COMPANY_LOGO_HEIGHT", round($height * (1/$resizeAmount)));
403
+                $ss->assign("COMPANY_LOGO_WIDTH", round($width * (1 / $resizeAmount)));
404
+                $ss->assign("COMPANY_LOGO_HEIGHT", round($height * (1 / $resizeAmount)));
405 405
             }
406 406
             else {
407 407
                 $ss->assign("COMPANY_LOGO_WIDTH", $width);
@@ -417,110 +417,110 @@  discard block
 block discarded – undo
417 417
                                 )
418 418
             );
419 419
         }
420
-        $ss->assign("COMPANY_LOGO_URL",getJSPath($companyLogoURL)."&logo_md5=".$ss->get_template_vars("COMPANY_LOGO_MD5"));
420
+        $ss->assign("COMPANY_LOGO_URL", getJSPath($companyLogoURL)."&logo_md5=".$ss->get_template_vars("COMPANY_LOGO_MD5"));
421 421
 
422 422
         // get the global links
423 423
         $gcls = array();
424 424
         $global_control_links = array();
425 425
         require("include/globalControlLinks.php");
426 426
 
427
-        foreach($global_control_links as $key => $value) {
428
-            if ($key == 'users')  {   //represents logout link.
427
+        foreach ($global_control_links as $key => $value) {
428
+            if ($key == 'users') {   //represents logout link.
429 429
                 $ss->assign("LOGOUT_LINK", $value['linkinfo'][key($value['linkinfo'])]);
430
-                $ss->assign("LOGOUT_LABEL", key($value['linkinfo']));//key value for first element.
430
+                $ss->assign("LOGOUT_LABEL", key($value['linkinfo'])); //key value for first element.
431 431
                 continue;
432 432
             }
433 433
 
434 434
             foreach ($value as $linkattribute => $attributevalue) {
435 435
                 // get the main link info
436
-                if ( $linkattribute == 'linkinfo' ) {
436
+                if ($linkattribute == 'linkinfo') {
437 437
                     $gcls[$key] = array(
438 438
                         "LABEL" => key($attributevalue),
439 439
                         "URL"   => current($attributevalue),
440 440
                         "SUBMENU" => array(),
441 441
                         );
442
-                   if(substr($gcls[$key]["URL"], 0, 11) == "javascript:") {
443
-                       $gcls[$key]["ONCLICK"] = substr($gcls[$key]["URL"],11);
442
+                   if (substr($gcls[$key]["URL"], 0, 11) == "javascript:") {
443
+                       $gcls[$key]["ONCLICK"] = substr($gcls[$key]["URL"], 11);
444 444
                        $gcls[$key]["URL"] = "javascript:void(0)";
445 445
                    }
446 446
                 }
447 447
                 // and now the sublinks
448
-                if ( $linkattribute == 'submenu' && is_array($attributevalue) ) {
448
+                if ($linkattribute == 'submenu' && is_array($attributevalue)) {
449 449
                     foreach ($attributevalue as $submenulinkkey => $submenulinkinfo)
450 450
                         $gcls[$key]['SUBMENU'][$submenulinkkey] = array(
451 451
                             "LABEL" => key($submenulinkinfo),
452 452
                             "URL"   => current($submenulinkinfo),
453 453
                         );
454
-                       if(substr($gcls[$key]['SUBMENU'][$submenulinkkey]["URL"], 0, 11) == "javascript:") {
455
-                           $gcls[$key]['SUBMENU'][$submenulinkkey]["ONCLICK"] = substr($gcls[$key]['SUBMENU'][$submenulinkkey]["URL"],11);
454
+                       if (substr($gcls[$key]['SUBMENU'][$submenulinkkey]["URL"], 0, 11) == "javascript:") {
455
+                           $gcls[$key]['SUBMENU'][$submenulinkkey]["ONCLICK"] = substr($gcls[$key]['SUBMENU'][$submenulinkkey]["URL"], 11);
456 456
                            $gcls[$key]['SUBMENU'][$submenulinkkey]["URL"] = "javascript:void(0)";
457 457
                        }
458 458
                 }
459 459
             }
460 460
         }
461
-        $ss->assign("GCLS",$gcls);
461
+        $ss->assign("GCLS", $gcls);
462 462
 
463 463
         $ss->assign("SEARCH", isset($_REQUEST['query_string']) ? $_REQUEST['query_string'] : '');
464 464
 
465 465
         if ($this->action == "EditView" || $this->action == "Login")
466 466
             $ss->assign("ONLOAD", 'onload="set_focus()"');
467 467
 
468
-        $ss->assign("AUTHENTICATED",isset($_SESSION["authenticated_user_id"]));
468
+        $ss->assign("AUTHENTICATED", isset($_SESSION["authenticated_user_id"]));
469 469
 
470 470
         // get other things needed for page style popup
471 471
         if (isset($_SESSION["authenticated_user_id"])) {
472 472
             // get the current user name and id
473 473
             $ss->assign("CURRENT_USER", $current_user->full_name == '' || !showFullName()
474
-                ? $current_user->user_name : $current_user->full_name );
474
+                ? $current_user->user_name : $current_user->full_name);
475 475
             $ss->assign("CURRENT_USER_ID", $current_user->id);
476 476
 
477 477
             // get the last viewed records
478 478
             require_once("modules/Favorites/Favorites.php");
479 479
             $favorites = new Favorites();
480 480
             $favorite_records = $favorites->getCurrentUserSidebarFavorites();
481
-            $ss->assign("favoriteRecords",$favorite_records);
481
+            $ss->assign("favoriteRecords", $favorite_records);
482 482
 
483 483
             $tracker = new Tracker();
484 484
             $history = $tracker->get_recently_viewed($current_user->id);
485
-            $ss->assign("recentRecords",$this->processRecentRecords($history));
485
+            $ss->assign("recentRecords", $this->processRecentRecords($history));
486 486
         }
487 487
 
488 488
         $bakModStrings = $mod_strings;
489
-        if (isset($_SESSION["authenticated_user_id"]) ) {
489
+        if (isset($_SESSION["authenticated_user_id"])) {
490 490
             // get the module list
491 491
             $moduleTopMenu = array();
492 492
 
493 493
             $max_tabs = $current_user->getPreference('max_tabs');
494 494
             // Attempt to correct if max tabs count is extremely high.
495
-            if ( !isset($max_tabs) || $max_tabs <= 0 || $max_tabs > 10 ) {
495
+            if (!isset($max_tabs) || $max_tabs <= 0 || $max_tabs > 10) {
496 496
                 $max_tabs = $GLOBALS['sugar_config']['default_max_tabs'];
497 497
                 $current_user->setPreference('max_tabs', $max_tabs, 0, 'global');
498 498
             }
499 499
 
500 500
             $moduleTab = $this->_getModuleTab();
501
-            $ss->assign('MODULE_TAB',$moduleTab);
501
+            $ss->assign('MODULE_TAB', $moduleTab);
502 502
 
503 503
 
504 504
             // See if they are using grouped tabs or not (removed in 6.0, returned in 6.1)
505 505
             $user_navigation_paradigm = $current_user->getPreference('navigation_paradigm');
506
-            if ( !isset($user_navigation_paradigm) ) {
506
+            if (!isset($user_navigation_paradigm)) {
507 507
                 $user_navigation_paradigm = $GLOBALS['sugar_config']['default_navigation_paradigm'];
508 508
             }
509 509
 
510 510
 
511 511
             // Get the full module list for later use
512
-            foreach ( query_module_access_list($current_user) as $module ) {
512
+            foreach (query_module_access_list($current_user) as $module) {
513 513
                 // Bug 25948 - Check for the module being in the moduleList
514
-                if ( isset($app_list_strings['moduleList'][$module]) ) {
514
+                if (isset($app_list_strings['moduleList'][$module])) {
515 515
                     $fullModuleList[$module] = $app_list_strings['moduleList'][$module];
516 516
                 }
517 517
             }
518 518
 
519 519
 
520
-            if(!should_hide_iframes()) {
520
+            if (!should_hide_iframes()) {
521 521
                 $iFrame = new iFrame();
522 522
                 $frames = $iFrame->lookup_frames('tab');
523
-                foreach($frames as $key => $values){
523
+                foreach ($frames as $key => $values) {
524 524
                         $fullModuleList[$key] = $values;
525 525
                 }
526 526
             }
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
                 unset($fullModuleList['iFrames']);
529 529
             }
530 530
 
531
-            if ( $user_navigation_paradigm == 'gm' && isset($themeObject->group_tabs) && $themeObject->group_tabs) {
531
+            if ($user_navigation_paradigm == 'gm' && isset($themeObject->group_tabs) && $themeObject->group_tabs) {
532 532
                 // We are using grouped tabs
533 533
                 require_once('include/GroupedTabs/GroupedTabStructure.php');
534 534
                 $groupedTabsClass = new GroupedTabStructure();
@@ -536,12 +536,12 @@  discard block
 block discarded – undo
536 536
                 //handle with submoremodules
537 537
                 $max_tabs = $current_user->getPreference('max_tabs');
538 538
                 // If the max_tabs isn't set incorrectly, set it within the range, to the default max sub tabs size
539
-                if ( !isset($max_tabs) || $max_tabs <= 0 || $max_tabs > 10){
539
+                if (!isset($max_tabs) || $max_tabs <= 0 || $max_tabs > 10) {
540 540
                     // We have a default value. Use it
541
-                    if(isset($GLOBALS['sugar_config']['default_max_tabs'])){
541
+                    if (isset($GLOBALS['sugar_config']['default_max_tabs'])) {
542 542
                         $max_tabs = $GLOBALS['sugar_config']['default_max_tabs'];
543 543
                     }
544
-                    else{
544
+                    else {
545 545
                         $max_tabs = 8;
546 546
                     }
547 547
                 }
@@ -554,22 +554,22 @@  discard block
 block discarded – undo
554 554
 
555 555
                 // Setup the default group tab.
556 556
                 $allGroup = $app_strings['LBL_TABGROUP_ALL'];
557
-                $ss->assign('currentGroupTab',$allGroup);
557
+                $ss->assign('currentGroupTab', $allGroup);
558 558
                 $currentGroupTab = $allGroup;
559 559
                 $usersGroup = $current_user->getPreference('theme_current_group');
560 560
                 // Figure out which tab they currently have selected (stored as a user preference)
561
-                if ( !empty($usersGroup) && isset($groupTabs[$usersGroup]) ) {
561
+                if (!empty($usersGroup) && isset($groupTabs[$usersGroup])) {
562 562
                     $currentGroupTab = $usersGroup;
563 563
                 } else {
564
-                    $current_user->setPreference('theme_current_group',$currentGroupTab);
564
+                    $current_user->setPreference('theme_current_group', $currentGroupTab);
565 565
                 }
566 566
 
567
-                $ss->assign('currentGroupTab',$currentGroupTab);
567
+                $ss->assign('currentGroupTab', $currentGroupTab);
568 568
                 $usingGroupTabs = true;
569 569
 
570 570
             } else {
571 571
                 // Setup the default group tab.
572
-                $ss->assign('currentGroupTab',$app_strings['LBL_TABGROUP_ALL']);
572
+                $ss->assign('currentGroupTab', $app_strings['LBL_TABGROUP_ALL']);
573 573
 
574 574
                 $usingGroupTabs = false;
575 575
 
@@ -581,31 +581,31 @@  discard block
 block discarded – undo
581 581
             $topTabList = array();
582 582
 
583 583
             // Now time to go through each of the tab sets and fix them up.
584
-            foreach ( $groupTabs as $tabIdx => $tabData ) {
584
+            foreach ($groupTabs as $tabIdx => $tabData) {
585 585
                 $topTabs = $tabData['modules'];
586
-                if ( ! is_array($topTabs) ) {
586
+                if (!is_array($topTabs)) {
587 587
                     $topTabs = array();
588 588
                 }
589 589
                 $extraTabs = array();
590 590
 
591 591
                 // Split it in to the tabs that go across the top, and the ones that are on the extra menu.
592
-                if ( count($topTabs) > $max_tabs ) {
593
-                    $extraTabs = array_splice($topTabs,$max_tabs);
592
+                if (count($topTabs) > $max_tabs) {
593
+                    $extraTabs = array_splice($topTabs, $max_tabs);
594 594
                 }
595 595
                 // Make sure the current module is accessable through one of the top tabs
596
-                if ( !isset($topTabs[$moduleTab]) ) {
596
+                if (!isset($topTabs[$moduleTab])) {
597 597
                     // Nope, we need to add it.
598 598
                     // First, take it out of the extra menu, if it's there
599
-                    if ( isset($extraTabs[$moduleTab]) ) {
599
+                    if (isset($extraTabs[$moduleTab])) {
600 600
                         unset($extraTabs[$moduleTab]);
601 601
                     }
602
-                    if ( count($topTabs) >= $max_tabs - 1 ) {
602
+                    if (count($topTabs) >= $max_tabs - 1) {
603 603
                         // We already have the maximum number of tabs, so we need to shuffle the last one
604 604
                         // from the top to the first one of the extras
605
-                        $lastElem = array_splice($topTabs,$max_tabs-1);
605
+                        $lastElem = array_splice($topTabs, $max_tabs - 1);
606 606
                         $extraTabs = $lastElem + $extraTabs;
607 607
                     }
608
-                    if ( !empty($moduleTab) ) {
608
+                    if (!empty($moduleTab)) {
609 609
                         $topTabs[$moduleTab] = $app_list_strings['moduleList'][$moduleTab];
610 610
                     }
611 611
                 }
@@ -624,7 +624,7 @@  discard block
 block discarded – undo
624 624
                 */
625 625
 
626 626
                 // Get a unique list of the top tabs so we can build the popup menus for them
627
-                foreach ( $topTabs as $moduleKey => $module ) {
627
+                foreach ($topTabs as $moduleKey => $module) {
628 628
                     $topTabList[$moduleKey] = $module;
629 629
                 }
630 630
 
@@ -633,67 +633,67 @@  discard block
 block discarded – undo
633 633
             }
634 634
         }
635 635
 
636
-        if ( isset($topTabList) && is_array($topTabList) ) {
636
+        if (isset($topTabList) && is_array($topTabList)) {
637 637
             // Adding shortcuts array to menu array for displaying shortcuts associated with each module
638 638
             $shortcutTopMenu = array();
639
-            foreach($topTabList as $module_key => $label) {
639
+            foreach ($topTabList as $module_key => $label) {
640 640
                 global $mod_strings;
641 641
                 $mod_strings = return_module_language($current_language, $module_key);
642
-                foreach ( $this->getMenu($module_key) as $key => $menu_item ) {
642
+                foreach ($this->getMenu($module_key) as $key => $menu_item) {
643 643
                     $shortcutTopMenu[$module_key][$key] = array(
644 644
                         "URL"         => $menu_item[0],
645 645
                         "LABEL"       => $menu_item[1],
646 646
                         "MODULE_NAME" => $menu_item[2],
647 647
                         "IMAGE"       => $themeObject
648
-                        ->getImage($menu_item[2],"border='0' align='absmiddle'",null,null,'.gif',$menu_item[1]),
648
+                        ->getImage($menu_item[2], "border='0' align='absmiddle'", null, null, '.gif', $menu_item[1]),
649 649
                         "ID"          => $menu_item[2]."_link",
650 650
                         );
651 651
                 }
652 652
             }
653
-            if(!empty($sugar_config['lock_homepage']) && $sugar_config['lock_homepage'] == true) $ss->assign('lock_homepage', true);
654
-            $ss->assign("groupTabs",$groupTabs);
655
-            $ss->assign("shortcutTopMenu",$shortcutTopMenu);
656
-            $ss->assign('USE_GROUP_TABS',$usingGroupTabs);
653
+            if (!empty($sugar_config['lock_homepage']) && $sugar_config['lock_homepage'] == true) $ss->assign('lock_homepage', true);
654
+            $ss->assign("groupTabs", $groupTabs);
655
+            $ss->assign("shortcutTopMenu", $shortcutTopMenu);
656
+            $ss->assign('USE_GROUP_TABS', $usingGroupTabs);
657 657
 
658 658
             // This is here for backwards compatibility, someday, somewhere, it will be able to be removed
659
-            $ss->assign("moduleTopMenu",$groupTabs[$app_strings['LBL_TABGROUP_ALL']]['modules']);
660
-            $ss->assign("moduleExtraMenu",$groupTabs[$app_strings['LBL_TABGROUP_ALL']]['extra']);
659
+            $ss->assign("moduleTopMenu", $groupTabs[$app_strings['LBL_TABGROUP_ALL']]['modules']);
660
+            $ss->assign("moduleExtraMenu", $groupTabs[$app_strings['LBL_TABGROUP_ALL']]['extra']);
661 661
 
662 662
 
663 663
         }
664 664
 
665
-        if ( isset($extraTabs) && is_array($extraTabs) ) {
665
+        if (isset($extraTabs) && is_array($extraTabs)) {
666 666
             // Adding shortcuts array to extra menu array for displaying shortcuts associated with each module
667 667
             $shortcutExtraMenu = array();
668
-            foreach($extraTabs as $module_key => $label) {
668
+            foreach ($extraTabs as $module_key => $label) {
669 669
                 global $mod_strings;
670 670
                 $mod_strings = return_module_language($current_language, $module_key);
671
-                foreach ( $this->getMenu($module_key) as $key => $menu_item ) {
671
+                foreach ($this->getMenu($module_key) as $key => $menu_item) {
672 672
                     $shortcutExtraMenu[$module_key][$key] = array(
673 673
                         "URL"         => $menu_item[0],
674 674
                         "LABEL"       => $menu_item[1],
675 675
                         "MODULE_NAME" => $menu_item[2],
676 676
                         "IMAGE"       => $themeObject
677
-                        ->getImage($menu_item[2],"border='0' align='absmiddle'",null,null,'.gif',$menu_item[1]),
677
+                        ->getImage($menu_item[2], "border='0' align='absmiddle'", null, null, '.gif', $menu_item[1]),
678 678
                         "ID"          => $menu_item[2]."_link",
679 679
                         );
680 680
                 }
681 681
             }
682
-            $ss->assign("shortcutExtraMenu",$shortcutExtraMenu);
682
+            $ss->assign("shortcutExtraMenu", $shortcutExtraMenu);
683 683
         }
684 684
 
685
-       if(!empty($current_user)){
685
+       if (!empty($current_user)) {
686 686
        	$ss->assign("max_tabs", $current_user->getPreference("max_tabs"));
687 687
        }
688 688
 
689 689
 
690 690
         $imageURL = SugarThemeRegistry::current()->getImageURL("dashboard.png");
691 691
         $homeImage = "<img src='$imageURL'>";
692
-		$ss->assign("homeImage",$homeImage);
692
+		$ss->assign("homeImage", $homeImage);
693 693
         global $mod_strings;
694 694
         $mod_strings = $bakModStrings;
695 695
         $headerTpl = $themeObject->getTemplate('header.tpl');
696
-        if (inDeveloperMode() )
696
+        if (inDeveloperMode())
697 697
             $ss->clear_compiled_tpl($headerTpl);
698 698
 
699 699
         if ($retModTabs)
@@ -705,9 +705,9 @@  discard block
 block discarded – undo
705 705
             $this->includeClassicFile('modules/Administration/DisplayWarnings.php');
706 706
 
707 707
             $errorMessages = SugarApplication::getErrorMessages();
708
-            if ( !empty($errorMessages)) {
709
-                foreach ( $errorMessages as $error_message ) {
710
-                    echo('<p class="error">' . $error_message.'</p>');
708
+            if (!empty($errorMessages)) {
709
+                foreach ($errorMessages as $error_message) {
710
+                    echo('<p class="error">'.$error_message.'</p>');
711 711
                 }
712 712
             }
713 713
         }
@@ -742,13 +742,13 @@  discard block
 block discarded – undo
742 742
     {
743 743
         global $sugar_config, $timedate;
744 744
 
745
-        if(isset($this->bean->module_dir)){
745
+        if (isset($this->bean->module_dir)) {
746 746
             echo "<script>var module_sugar_grp1 = '{$this->bean->module_dir}';</script>";
747 747
         }
748
-        if(isset($_REQUEST['action'])){
748
+        if (isset($_REQUEST['action'])) {
749 749
             echo "<script>var action_sugar_grp1 = '{$_REQUEST['action']}';</script>";
750 750
         }
751
-        echo '<script>jscal_today = 1000*' . $timedate->asUserTs($timedate->getNow()) . '; if(typeof app_strings == "undefined") app_strings = new Array();</script>';
751
+        echo '<script>jscal_today = 1000*'.$timedate->asUserTs($timedate->getNow()).'; if(typeof app_strings == "undefined") app_strings = new Array();</script>';
752 752
         if (!is_file(sugar_cached("include/javascript/sugar_grp1.js"))) {
753 753
             $_REQUEST['root_directory'] = ".";
754 754
             require_once("jssource/minify_utils.php");
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
             if ( typeof(SUGAR.themes) == 'undefined' ) SUGAR.themes = {};
765 765
         </script>
766 766
 EOQ;
767
-        if(isset( $sugar_config['disc_client']) && $sugar_config['disc_client'])
767
+        if (isset($sugar_config['disc_client']) && $sugar_config['disc_client'])
768 768
             echo getVersionedScript('modules/Sync/headersync.js');
769 769
     }
770 770
 
@@ -793,13 +793,13 @@  discard block
 block discarded – undo
793 793
         require_once ('modules/Currencies/Currency.php');
794 794
         list ($num_grp_sep, $dec_sep) = get_number_seperators();
795 795
 
796
-        $the_script = "<script type=\"text/javascript\">\n" . "\tvar time_reg_format = '" .
797
-             $timereg['format'] . "';\n" . "\tvar date_reg_format = '" .
798
-             $datereg['format'] . "';\n" . "\tvar date_reg_positions = { $date_pos };\n" .
799
-             "\tvar time_separator = '$time_separator';\n" .
800
-             "\tvar cal_date_format = '$cal_date_format';\n" .
801
-             "\tvar time_offset = $hour_offset;\n" . "\tvar num_grp_sep = '$num_grp_sep';\n" .
802
-             "\tvar dec_sep = '$dec_sep';\n" . "</script>";
796
+        $the_script = "<script type=\"text/javascript\">\n"."\tvar time_reg_format = '".
797
+             $timereg['format']."';\n"."\tvar date_reg_format = '".
798
+             $datereg['format']."';\n"."\tvar date_reg_positions = { $date_pos };\n".
799
+             "\tvar time_separator = '$time_separator';\n".
800
+             "\tvar cal_date_format = '$cal_date_format';\n".
801
+             "\tvar time_offset = $hour_offset;\n"."\tvar num_grp_sep = '$num_grp_sep';\n".
802
+             "\tvar dec_sep = '$dec_sep';\n"."</script>";
803 803
 
804 804
         return $the_script;
805 805
     }
@@ -827,13 +827,13 @@  discard block
 block discarded – undo
827 827
                 "sugar_cache_dir" => "cache/",
828 828
                 );
829 829
 
830
-            if(isset($this->bean->module_dir)){
830
+            if (isset($this->bean->module_dir)) {
831 831
                 $js_vars['module_sugar_grp1'] = $this->bean->module_dir;
832 832
             }
833
-            if(isset($_REQUEST['action'])){
833
+            if (isset($_REQUEST['action'])) {
834 834
                 $js_vars['action_sugar_grp1'] = $_REQUEST['action'];
835 835
             }
836
-            echo '<script>jscal_today = 1000*' . $timedate->asUserTs($timedate->getNow()) . '; if(typeof app_strings == "undefined") app_strings = new Array();</script>';
836
+            echo '<script>jscal_today = 1000*'.$timedate->asUserTs($timedate->getNow()).'; if(typeof app_strings == "undefined") app_strings = new Array();</script>';
837 837
             if (!is_file(sugar_cached("include/javascript/sugar_grp1.js")) || !is_file(sugar_cached("include/javascript/sugar_grp1_yui.js")) || !is_file(sugar_cached("include/javascript/sugar_grp1_jquery.js"))) {
838 838
                 $_REQUEST['root_directory'] = ".";
839 839
                 require_once("jssource/minify_utils.php");
@@ -846,33 +846,33 @@  discard block
 block discarded – undo
846 846
 
847 847
             // output necessary config js in the top of the page
848 848
             $config_js = $this->getSugarConfigJS();
849
-            if(!empty($config_js)){
849
+            if (!empty($config_js)) {
850 850
                 echo "<script>\n".implode("\n", $config_js)."</script>\n";
851 851
             }
852 852
 
853
-            if ( isset($sugar_config['email_sugarclient_listviewmaxselect']) ) {
853
+            if (isset($sugar_config['email_sugarclient_listviewmaxselect'])) {
854 854
                 echo "<script>SUGAR.config.email_sugarclient_listviewmaxselect = {$GLOBALS['sugar_config']['email_sugarclient_listviewmaxselect']};</script>";
855 855
             }
856 856
 
857
-            $image_server = (defined('TEMPLATE_URL'))?TEMPLATE_URL . '/':'';
858
-            echo '<script type="text/javascript">SUGAR.themes.image_server="' . $image_server . '";</script>'; // cn: bug 12274 - create session-stored key to defend against CSRF
859
-            echo '<script type="text/javascript">var name_format = "' . $locale->getLocaleFormatMacro() . '";</script>';
857
+            $image_server = (defined('TEMPLATE_URL')) ?TEMPLATE_URL . '/' : '';
858
+            echo '<script type="text/javascript">SUGAR.themes.image_server="'.$image_server.'";</script>'; // cn: bug 12274 - create session-stored key to defend against CSRF
859
+            echo '<script type="text/javascript">var name_format = "'.$locale->getLocaleFormatMacro().'";</script>';
860 860
             echo self::getJavascriptValidation();
861
-            if (!is_file(sugar_cached('jsLanguage/') . $GLOBALS['current_language'] . '.js')) {
861
+            if (!is_file(sugar_cached('jsLanguage/').$GLOBALS['current_language'].'.js')) {
862 862
                 require_once ('include/language/jsLanguage.php');
863 863
                 jsLanguage::createAppStringsCache($GLOBALS['current_language']);
864 864
             }
865
-            echo getVersionedScript('cache/jsLanguage/'. $GLOBALS['current_language'] . '.js', $GLOBALS['sugar_config']['js_lang_version']);
865
+            echo getVersionedScript('cache/jsLanguage/'.$GLOBALS['current_language'].'.js', $GLOBALS['sugar_config']['js_lang_version']);
866 866
 
867 867
 			echo $this->_getModLanguageJS();
868 868
 
869
-            if(isset( $sugar_config['disc_client']) && $sugar_config['disc_client'])
869
+            if (isset($sugar_config['disc_client']) && $sugar_config['disc_client'])
870 870
                 echo getVersionedScript('modules/Sync/headersync.js');
871 871
 
872 872
 
873 873
             //echo out the $js_vars variables as javascript variables
874 874
             echo "<script type='text/javascript'>\n";
875
-            foreach($js_vars as $var=>$value)
875
+            foreach ($js_vars as $var=>$value)
876 876
             {
877 877
                 echo "var {$var} = '{$value}';\n";
878 878
             }
@@ -880,12 +880,12 @@  discard block
 block discarded – undo
880 880
         }
881 881
     }
882 882
 
883
-	protected function _getModLanguageJS(){
884
-		if (!is_file(sugar_cached('jsLanguage/') . $this->module . '/' . $GLOBALS['current_language'] . '.js')) {
883
+	protected function _getModLanguageJS() {
884
+		if (!is_file(sugar_cached('jsLanguage/').$this->module.'/'.$GLOBALS['current_language'].'.js')) {
885 885
 			require_once ('include/language/jsLanguage.php');
886 886
 			jsLanguage::createModuleStringsCache($this->module, $GLOBALS['current_language']);
887 887
 		}
888
-		return getVersionedScript("cache/jsLanguage/{$this->module}/". $GLOBALS['current_language'] . '.js', $GLOBALS['sugar_config']['js_lang_version']);
888
+		return getVersionedScript("cache/jsLanguage/{$this->module}/".$GLOBALS['current_language'].'.js', $GLOBALS['sugar_config']['js_lang_version']);
889 889
 	}
890 890
 
891 891
     /**
@@ -907,8 +907,8 @@  discard block
 block discarded – undo
907 907
         }
908 908
 
909 909
         $ss = new Sugar_Smarty();
910
-        $ss->assign("AUTHENTICATED",isset($_SESSION["authenticated_user_id"]));
911
-        $ss->assign('MOD',return_module_language($GLOBALS['current_language'], 'Users'));
910
+        $ss->assign("AUTHENTICATED", isset($_SESSION["authenticated_user_id"]));
911
+        $ss->assign('MOD', return_module_language($GLOBALS['current_language'], 'Users'));
912 912
 
913 913
 		$bottomLinkList = array();
914 914
 		 if (isset($this->action) && $this->action != "EditView") {
@@ -917,11 +917,11 @@  discard block
 block discarded – undo
917 917
 		$bottomLinkList['backtotop'] = array($app_strings['LNK_BACKTOTOP'] => 'javascript:SUGAR.util.top();');
918 918
 
919 919
 		$bottomLinksStr = "";
920
-		foreach($bottomLinkList as $key => $value) {
921
-			foreach($value as $text => $link) {
920
+		foreach ($bottomLinkList as $key => $value) {
921
+			foreach ($value as $text => $link) {
922 922
 				   $href = $link;
923
-				   if(substr($link, 0, 11) == "javascript:") {
924
-                       $onclick = " onclick=\"".substr($link,11)."\"";
923
+				   if (substr($link, 0, 11) == "javascript:") {
924
+                       $onclick = " onclick=\"".substr($link, 11)."\"";
925 925
                        $href = "javascript:void(0)";
926 926
                    } else {
927 927
                    		$onclick = "";
@@ -933,9 +933,9 @@  discard block
 block discarded – undo
933 933
 				$bottomLinksStr .= " ".$text."</a>";
934 934
 			}
935 935
 		}
936
-		$ss->assign("BOTTOMLINKS",$bottomLinksStr);
936
+		$ss->assign("BOTTOMLINKS", $bottomLinksStr);
937 937
         if (SugarConfig::getInstance()->get('calculate_response_time', false))
938
-            $ss->assign('STATISTICS',$this->_getStatistics());
938
+            $ss->assign('STATISTICS', $this->_getStatistics());
939 939
 
940 940
         // Under the License referenced above, you are required to leave in all copyright statements in both
941 941
         // the code and end-user application.
@@ -969,7 +969,7 @@  discard block
 block discarded – undo
969 969
         $companyLogoURL = $companyLogoURL_arr[0];
970 970
 
971 971
         $company_logo_attributes = sugar_cache_retrieve('company_logo_attributes');
972
-        if(!empty($company_logo_attributes)) {
972
+        if (!empty($company_logo_attributes)) {
973 973
             $ss->assign("COMPANY_LOGO_MD5", $company_logo_attributes[0]);
974 974
             $ss->assign("COMPANY_LOGO_WIDTH", $company_logo_attributes[1]);
975 975
             $ss->assign("COMPANY_LOGO_HEIGHT", $company_logo_attributes[2]);
@@ -978,16 +978,16 @@  discard block
 block discarded – undo
978 978
             // Always need to md5 the file
979 979
             $ss->assign("COMPANY_LOGO_MD5", md5_file($companyLogoURL));
980 980
 
981
-            list($width,$height) = getimagesize($companyLogoURL);
982
-            if ( $width > 212 || $height > 40 ) {
983
-                $resizePctWidth  = ($width - 212)/212;
984
-                $resizePctHeight = ($height - 40)/40;
985
-                if ( $resizePctWidth > $resizePctHeight )
981
+            list($width, $height) = getimagesize($companyLogoURL);
982
+            if ($width > 212 || $height > 40) {
983
+                $resizePctWidth  = ($width - 212) / 212;
984
+                $resizePctHeight = ($height - 40) / 40;
985
+                if ($resizePctWidth > $resizePctHeight)
986 986
                     $resizeAmount = $width / 212;
987 987
                 else
988 988
                     $resizeAmount = $height / 40;
989
-                $ss->assign("COMPANY_LOGO_WIDTH", round($width * (1/$resizeAmount)));
990
-                $ss->assign("COMPANY_LOGO_HEIGHT", round($height * (1/$resizeAmount)));
989
+                $ss->assign("COMPANY_LOGO_WIDTH", round($width * (1 / $resizeAmount)));
990
+                $ss->assign("COMPANY_LOGO_HEIGHT", round($height * (1 / $resizeAmount)));
991 991
             }
992 992
             else {
993 993
                 $ss->assign("COMPANY_LOGO_WIDTH", $width);
@@ -1003,28 +1003,28 @@  discard block
 block discarded – undo
1003 1003
                                 )
1004 1004
             );
1005 1005
         }
1006
-        $ss->assign("COMPANY_LOGO_URL",getJSPath($companyLogoURL)."&logo_md5=".$ss->get_template_vars("COMPANY_LOGO_MD5"));
1006
+        $ss->assign("COMPANY_LOGO_URL", getJSPath($companyLogoURL)."&logo_md5=".$ss->get_template_vars("COMPANY_LOGO_MD5"));
1007 1007
 
1008 1008
         // Bug 38594 - Add in Trademark wording
1009 1009
         $copyright .= 'SugarCRM is a trademark of SugarCRM, Inc. All other company and product names may be trademarks of the respective companies with which they are associated.<br />';
1010 1010
 
1011 1011
         //rrs bug: 20923 - if this image does not exist as per the license, then the proper image will be displayed regardless, so no need
1012 1012
         //to display an empty image here.
1013
-        if(file_exists('include/images/poweredby_sugarcrm_65.png')){
1013
+        if (file_exists('include/images/poweredby_sugarcrm_65.png')) {
1014 1014
             $copyright .= $attribLinkImg;
1015 1015
         }
1016 1016
         // End Required Image
1017
-        $ss->assign('COPYRIGHT',$copyright);
1017
+        $ss->assign('COPYRIGHT', $copyright);
1018 1018
 
1019 1019
         // here we allocate the help link data
1020 1020
         $help_actions_blacklist = array('Login'); // we don't want to show a context help link here
1021
-        if (!in_array($this->action,$help_actions_blacklist)) {
1021
+        if (!in_array($this->action, $help_actions_blacklist)) {
1022 1022
             $url = 'javascript:void(window.open(\'index.php?module=Administration&action=SupportPortal&view=documentation&version='.$GLOBALS['sugar_version'].'&edition='.$GLOBALS['sugar_flavor'].'&lang='.$GLOBALS['current_language'].
1023 1023
                         '&help_module='.$this->module.'&help_action='.$this->action.'&key='.$GLOBALS['server_unique_key'].'\'))';
1024 1024
             $label = (isset($GLOBALS['app_list_strings']['moduleList'][$this->module]) ?
1025
-                        $GLOBALS['app_list_strings']['moduleList'][$this->module] : $this->module). ' '.$app_strings['LNK_HELP'];
1026
-            $ss->assign('HELP_LINK',SugarThemeRegistry::current()->getLink($url, $label, "id='help_link_two'",
1027
-                'help-dashlet.png', 'class="icon"',null,null,'','left'));
1025
+                        $GLOBALS['app_list_strings']['moduleList'][$this->module] : $this->module).' '.$app_strings['LNK_HELP'];
1026
+            $ss->assign('HELP_LINK', SugarThemeRegistry::current()->getLink($url, $label, "id='help_link_two'",
1027
+                'help-dashlet.png', 'class="icon"', null, null, '', 'left'));
1028 1028
         }
1029 1029
         // end
1030 1030
 
@@ -1037,7 +1037,7 @@  discard block
 block discarded – undo
1037 1037
      */
1038 1038
     protected function _displaySubPanels()
1039 1039
     {
1040
-        if (isset($this->bean) && !empty($this->bean->id) && (file_exists('modules/' . $this->module . '/metadata/subpaneldefs.php') || file_exists('custom/modules/' . $this->module . '/metadata/subpaneldefs.php') || file_exists('custom/modules/' . $this->module . '/Ext/Layoutdefs/layoutdefs.ext.php'))) {
1040
+        if (isset($this->bean) && !empty($this->bean->id) && (file_exists('modules/'.$this->module.'/metadata/subpaneldefs.php') || file_exists('custom/modules/'.$this->module.'/metadata/subpaneldefs.php') || file_exists('custom/modules/'.$this->module.'/Ext/Layoutdefs/layoutdefs.ext.php'))) {
1041 1041
             $GLOBALS['focus'] = $this->bean;
1042 1042
             require_once ('include/SubPanel/SubPanelTiles.php');
1043 1043
             $subpanel = new SubPanelTiles($this->bean, $this->module);
@@ -1095,7 +1095,7 @@  discard block
 block discarded – undo
1095 1095
      */
1096 1096
     protected function _checkModule()
1097 1097
     {
1098
-        if(!empty($this->module) && !file_exists('modules/'.$this->module)){
1098
+        if (!empty($this->module) && !file_exists('modules/'.$this->module)) {
1099 1099
             $error = str_replace("[module]", "$this->module", $GLOBALS['app_strings']['ERR_CANNOT_FIND_MODULE']);
1100 1100
             $GLOBALS['log']->fatal($error);
1101 1101
             echo $error;
@@ -1124,7 +1124,7 @@  discard block
 block discarded – undo
1124 1124
     {
1125 1125
         $endTime = microtime(true);
1126 1126
         $deltaTime = $endTime - $GLOBALS['startTime'];
1127
-        $response_time_string = $GLOBALS['app_strings']['LBL_SERVER_RESPONSE_TIME'] . ' ' . number_format(round($deltaTime, 2), 2) . ' ' . $GLOBALS['app_strings']['LBL_SERVER_RESPONSE_TIME_SECONDS'];
1127
+        $response_time_string = $GLOBALS['app_strings']['LBL_SERVER_RESPONSE_TIME'].' '.number_format(round($deltaTime, 2), 2).' '.$GLOBALS['app_strings']['LBL_SERVER_RESPONSE_TIME_SECONDS'];
1128 1128
         $return = $response_time_string;
1129 1129
        // $return .= '<br />';
1130 1130
         if (!empty($GLOBALS['sugar_config']['show_page_resources'])) {
@@ -1135,16 +1135,16 @@  discard block
 block discarded – undo
1135 1135
             // I believe the full get_include_files result set appears to have one entry for each file in real
1136 1136
             // case, and one entry in all lower case.
1137 1137
             $list_of_files_case_insensitive = array();
1138
-            foreach($included_files as $key => $name) {
1138
+            foreach ($included_files as $key => $name) {
1139 1139
                 // preserve the first capitalization encountered.
1140
-                $list_of_files_case_insensitive[mb_strtolower($name) ] = $name;
1140
+                $list_of_files_case_insensitive[mb_strtolower($name)] = $name;
1141 1141
             }
1142
-            $return .= $GLOBALS['app_strings']['LBL_SERVER_RESPONSE_RESOURCES'] . '(' . DBManager::getQueryCount() . ',' . sizeof($list_of_files_case_insensitive) . ')<br>';
1142
+            $return .= $GLOBALS['app_strings']['LBL_SERVER_RESPONSE_RESOURCES'].'('.DBManager::getQueryCount().','.sizeof($list_of_files_case_insensitive).')<br>';
1143 1143
             // Display performance of the internal and external caches....
1144 1144
             $cacheStats = SugarCache::instance()->getCacheStats();
1145
-            $return .= "External cache (hits/total=ratio) local ({$cacheStats['localHits']}/{$cacheStats['requests']}=" . round($cacheStats['localHits']*100/$cacheStats['requests'], 0) . "%)";
1146
-            $return .= " external ({$cacheStats['externalHits']}/{$cacheStats['requests']}=" . round($cacheStats['externalHits']*100/$cacheStats['requests'], 0) . "%)<br />";
1147
-            $return .= " misses ({$cacheStats['misses']}/{$cacheStats['requests']}=" . round($cacheStats['misses']*100/$cacheStats['requests'], 0) . "%)<br />";
1145
+            $return .= "External cache (hits/total=ratio) local ({$cacheStats['localHits']}/{$cacheStats['requests']}=".round($cacheStats['localHits'] * 100 / $cacheStats['requests'], 0)."%)";
1146
+            $return .= " external ({$cacheStats['externalHits']}/{$cacheStats['requests']}=".round($cacheStats['externalHits'] * 100 / $cacheStats['requests'], 0)."%)<br />";
1147
+            $return .= " misses ({$cacheStats['misses']}/{$cacheStats['requests']}=".round($cacheStats['misses'] * 100 / $cacheStats['requests'], 0)."%)<br />";
1148 1148
         }
1149 1149
 
1150 1150
         $return .= $this->logMemoryStatistics();
@@ -1161,37 +1161,36 @@  discard block
 block discarded – undo
1161 1161
      * @param $newline String of newline character to use (defaults to </ br>)
1162 1162
      * @return $message String formatted message about memory statistics
1163 1163
      */
1164
-    protected function logMemoryStatistics($newline='<br>')
1164
+    protected function logMemoryStatistics($newline = '<br>')
1165 1165
     {
1166 1166
         $log_message = '';
1167 1167
 
1168
-        if(!empty($GLOBALS['sugar_config']['log_memory_usage']))
1168
+        if (!empty($GLOBALS['sugar_config']['log_memory_usage']))
1169 1169
         {
1170
-            if(function_exists('memory_get_usage'))
1170
+            if (function_exists('memory_get_usage'))
1171 1171
             {
1172 1172
                 $memory_usage = memory_get_usage();
1173 1173
                 $bytes = $GLOBALS['app_strings']['LBL_SERVER_MEMORY_BYTES'];
1174 1174
                 $data = array($memory_usage, $bytes);
1175
-                $log_message = string_format($GLOBALS['app_strings']['LBL_SERVER_MEMORY_USAGE'], $data) . $newline;
1175
+                $log_message = string_format($GLOBALS['app_strings']['LBL_SERVER_MEMORY_USAGE'], $data).$newline;
1176 1176
             }
1177 1177
 
1178
-            if(function_exists('memory_get_peak_usage'))
1178
+            if (function_exists('memory_get_peak_usage'))
1179 1179
             {
1180 1180
                 $memory_peak_usage = memory_get_peak_usage();
1181 1181
                 $bytes = $GLOBALS['app_strings']['LBL_SERVER_MEMORY_BYTES'];
1182 1182
                 $data = array($memory_peak_usage, $bytes);
1183
-                $log_message .= string_format($GLOBALS['app_strings']['LBL_SERVER_PEAK_MEMORY_USAGE'], $data) . $newline;
1183
+                $log_message .= string_format($GLOBALS['app_strings']['LBL_SERVER_PEAK_MEMORY_USAGE'], $data).$newline;
1184 1184
             }
1185 1185
 
1186
-            if(!empty($log_message))
1186
+            if (!empty($log_message))
1187 1187
             {
1188
-                $data = array
1189
-                (
1188
+                $data = array(
1190 1189
                    !empty($this->module) ? $this->module : $GLOBALS['app_strings']['LBL_LINK_NONE'],
1191 1190
                    !empty($this->action) ? $this->action : $GLOBALS['app_strings']['LBL_LINK_NONE'],
1192 1191
                 );
1193 1192
 
1194
-                $output = string_format($GLOBALS['app_strings']['LBL_SERVER_MEMORY_LOG_MESSAGE'], $data) . $newline;
1193
+                $output = string_format($GLOBALS['app_strings']['LBL_SERVER_MEMORY_LOG_MESSAGE'], $data).$newline;
1195 1194
                 $output .= $log_message;
1196 1195
                 $fp = fopen("memory_usage.log", "ab");
1197 1196
                 fwrite($fp, $output);
@@ -1215,30 +1214,30 @@  discard block
 block discarded – undo
1215 1214
     {
1216 1215
         global $current_language, $current_user, $mod_strings, $app_strings, $module_menu;
1217 1216
 
1218
-        if ( empty($module) )
1217
+        if (empty($module))
1219 1218
             $module = $this->module;
1220 1219
 
1221 1220
         //Need to make sure the mod_strings match the requested module or Menus may fail
1222 1221
         $curr_mod_strings = $mod_strings;
1223
-        $mod_strings = return_module_language ( $current_language, $module ) ;
1222
+        $mod_strings = return_module_language($current_language, $module);
1224 1223
 
1225 1224
         $module_menu = array();
1226 1225
 
1227
-        if (file_exists('modules/' . $module . '/Menu.php')) {
1228
-            require('modules/' . $module . '/Menu.php');
1226
+        if (file_exists('modules/'.$module.'/Menu.php')) {
1227
+            require('modules/'.$module.'/Menu.php');
1229 1228
         }
1230
-        if (file_exists('custom/modules/' . $module . '/Ext/Menus/menu.ext.php')) {
1231
-            require('custom/modules/' . $module . '/Ext/Menus/menu.ext.php');
1229
+        if (file_exists('custom/modules/'.$module.'/Ext/Menus/menu.ext.php')) {
1230
+            require('custom/modules/'.$module.'/Ext/Menus/menu.ext.php');
1232 1231
         }
1233
-        if (!file_exists('modules/' . $module . '/Menu.php')
1234
-                && !file_exists('custom/modules/' . $module . '/Ext/Menus/menu.ext.php')
1232
+        if (!file_exists('modules/'.$module.'/Menu.php')
1233
+                && !file_exists('custom/modules/'.$module.'/Ext/Menus/menu.ext.php')
1235 1234
                 && !empty($GLOBALS['mod_strings']['LNK_NEW_RECORD'])) {
1236 1235
             $module_menu[] = array("index.php?module=$module&action=EditView&return_module=$module&return_action=DetailView",
1237
-                $GLOBALS['mod_strings']['LNK_NEW_RECORD'],"{$GLOBALS['app_strings']['LBL_CREATE_BUTTON_LABEL']}$module" ,$module );
1236
+                $GLOBALS['mod_strings']['LNK_NEW_RECORD'], "{$GLOBALS['app_strings']['LBL_CREATE_BUTTON_LABEL']}$module", $module);
1238 1237
             $module_menu[] = array("index.php?module=$module&action=index", $GLOBALS['mod_strings']['LNK_LIST'],
1239 1238
                 $module, $module);
1240
-            if ( ($this->bean instanceOf SugarBean) && !empty($this->bean->importable) )
1241
-                if ( !empty($mod_strings['LNK_IMPORT_'.strtoupper($module)]) )
1239
+            if (($this->bean instanceOf SugarBean) && !empty($this->bean->importable))
1240
+                if (!empty($mod_strings['LNK_IMPORT_'.strtoupper($module)]))
1242 1241
                     $module_menu[] = array("index.php?module=Import&action=Step1&import_module=$module&return_module=$module&return_action=index",
1243 1242
                         $mod_strings['LNK_IMPORT_'.strtoupper($module)], "Import", $module);
1244 1243
                 else
@@ -1265,22 +1264,22 @@  discard block
 block discarded – undo
1265 1264
 
1266 1265
 		$userTabs = query_module_access_list($current_user);
1267 1266
 		//If the home tab is in the user array use it as the default tab, otherwise use the first element in the tab array
1268
-		$defaultTab = (in_array("Home",$userTabs)) ? "Home" : key($userTabs);
1267
+		$defaultTab = (in_array("Home", $userTabs)) ? "Home" : key($userTabs);
1269 1268
 
1270 1269
         // Need to figure out what tab this module belongs to, most modules have their own tabs, but there are exceptions.
1271
-        if ( !empty($_REQUEST['module_tab']) )
1270
+        if (!empty($_REQUEST['module_tab']))
1272 1271
             return $_REQUEST['module_tab'];
1273
-        elseif ( isset($moduleTabMap[$this->module]) )
1272
+        elseif (isset($moduleTabMap[$this->module]))
1274 1273
             return $moduleTabMap[$this->module];
1275 1274
         // Special cases
1276
-        elseif ( $this->module == 'MergeRecords' )
1275
+        elseif ($this->module == 'MergeRecords')
1277 1276
             return !empty($_REQUEST['merge_module']) ? $_REQUEST['merge_module'] : $_REQUEST['return_module'];
1278
-        elseif ( $this->module == 'Users' && $this->action == 'SetTimezone' )
1277
+        elseif ($this->module == 'Users' && $this->action == 'SetTimezone')
1279 1278
             return $defaultTab;
1280 1279
         // Default anonymous pages to be under Home
1281
-        elseif ( !isset($app_list_strings['moduleList'][$this->module]) )
1280
+        elseif (!isset($app_list_strings['moduleList'][$this->module]))
1282 1281
             return $defaultTab;
1283
-        elseif ( isset($_REQUEST['action']) && $_REQUEST['action'] == "ajaxui" )
1282
+        elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == "ajaxui")
1284 1283
         	return $defaultTab;
1285 1284
         else
1286 1285
             return $this->module;
@@ -1300,42 +1299,42 @@  discard block
 block discarded – undo
1300 1299
 
1301 1300
         $theTitle = "<div class='moduleTitle'>\n";
1302 1301
 
1303
-        $module = preg_replace("/ /","",$this->module);
1302
+        $module = preg_replace("/ /", "", $this->module);
1304 1303
 
1305 1304
         $params = $this->_getModuleTitleParams();
1306 1305
         $index = 0;
1307 1306
 
1308
-		if(SugarThemeRegistry::current()->directionality == "rtl") {
1307
+		if (SugarThemeRegistry::current()->directionality == "rtl") {
1309 1308
 			$params = array_reverse($params);
1310 1309
 		}
1311
-		if(count($params) > 1) {
1310
+		if (count($params) > 1) {
1312 1311
 			array_shift($params);
1313 1312
 		}
1314 1313
 		$count = count($params);
1315 1314
         $paramString = '';
1316
-        foreach($params as $parm){
1315
+        foreach ($params as $parm) {
1317 1316
             $index++;
1318 1317
             $paramString .= $parm;
1319
-            if($index < $count){
1318
+            if ($index < $count) {
1320 1319
                 $paramString .= $this->getBreadCrumbSymbol();
1321 1320
             }
1322 1321
         }
1323 1322
 
1324
-        if(!empty($paramString)){
1323
+        if (!empty($paramString)) {
1325 1324
                $theTitle .= "<h2> $paramString </h2>";
1326 1325
 
1327
-            if($this->type == "detail"){
1328
-                $theTitle .= "<div class='favorite' record_id='" . $this->bean->id . "' module='" . $this->bean->module_dir . "'><div class='favorite_icon_outline'>" . SugarThemeRegistry::current()->getImage('favorite-star-outline','title="' . translate('LBL_DASHLET_EDIT', 'Home') . '" border="0"  align="absmiddle"', null,null,'.gif',translate('LBL_DASHLET_EDIT', 'Home')) . "</div>
1329
-                                                    <div class='favorite_icon_fill'>" . SugarThemeRegistry::current()->getImage('favorite-star','title="' . translate('LBL_DASHLET_EDIT', 'Home') . '" border="0"  align="absmiddle"', null,null,'.gif',translate('LBL_DASHLET_EDIT', 'Home')) . "</div></div>";
1326
+            if ($this->type == "detail") {
1327
+                $theTitle .= "<div class='favorite' record_id='".$this->bean->id."' module='".$this->bean->module_dir."'><div class='favorite_icon_outline'>".SugarThemeRegistry::current()->getImage('favorite-star-outline', 'title="'.translate('LBL_DASHLET_EDIT', 'Home').'" border="0"  align="absmiddle"', null, null, '.gif', translate('LBL_DASHLET_EDIT', 'Home'))."</div>
1328
+                                                    <div class='favorite_icon_fill'>" . SugarThemeRegistry::current()->getImage('favorite-star', 'title="'.translate('LBL_DASHLET_EDIT', 'Home').'" border="0"  align="absmiddle"', null, null, '.gif', translate('LBL_DASHLET_EDIT', 'Home'))."</div></div>";
1330 1329
             }
1331 1330
            }
1332 1331
 
1333 1332
         // bug 56131 - restore conditional so that link doesn't appear where it shouldn't
1334
-        if($show_help || $this->type == 'list') {
1333
+        if ($show_help || $this->type == 'list') {
1335 1334
             $theTitle .= "<span class='utils'>";
1336 1335
             $createImageURL = SugarThemeRegistry::current()->getImageURL('create-record.gif');
1337
-            if($this->type == 'list') $theTitle .= '<a href="#" class="btn btn-success showsearch"><span class=" glyphicon glyphicon-search" aria-hidden="true"></span></a>';$url = ajaxLink("index.php?module=$module&action=EditView&return_module=$module&return_action=DetailView");
1338
-            if($show_help) {
1336
+            if ($this->type == 'list') $theTitle .= '<a href="#" class="btn btn-success showsearch"><span class=" glyphicon glyphicon-search" aria-hidden="true"></span></a>'; $url = ajaxLink("index.php?module=$module&action=EditView&return_module=$module&return_action=DetailView");
1337
+            if ($show_help) {
1339 1338
                 $theTitle .= <<<EOHTML
1340 1339
 &nbsp;
1341 1340
 <a id="create_image" href="{$url}" class="utilsLink">
@@ -1361,31 +1360,31 @@  discard block
 block discarded – undo
1361 1360
     {
1362 1361
         $metadataFile = null;
1363 1362
         $foundViewDefs = false;
1364
-        $viewDef = strtolower($this->type) . 'viewdefs';
1365
-        $coreMetaPath = 'modules/'.$this->module.'/metadata/' . $viewDef . '.php';
1366
-        if(file_exists('custom/' .$coreMetaPath )){
1367
-            $metadataFile = 'custom/' . $coreMetaPath;
1363
+        $viewDef = strtolower($this->type).'viewdefs';
1364
+        $coreMetaPath = 'modules/'.$this->module.'/metadata/'.$viewDef.'.php';
1365
+        if (file_exists('custom/'.$coreMetaPath)) {
1366
+            $metadataFile = 'custom/'.$coreMetaPath;
1368 1367
             $foundViewDefs = true;
1369
-        }else{
1370
-            if(file_exists('custom/modules/'.$this->module.'/metadata/metafiles.php')){
1368
+        } else {
1369
+            if (file_exists('custom/modules/'.$this->module.'/metadata/metafiles.php')) {
1371 1370
                 require_once('custom/modules/'.$this->module.'/metadata/metafiles.php');
1372
-                if(!empty($metafiles[$this->module][$viewDef])){
1371
+                if (!empty($metafiles[$this->module][$viewDef])) {
1373 1372
                     $metadataFile = $metafiles[$this->module][$viewDef];
1374 1373
                     $foundViewDefs = true;
1375 1374
                 }
1376
-            }elseif(file_exists('modules/'.$this->module.'/metadata/metafiles.php')){
1375
+            }elseif (file_exists('modules/'.$this->module.'/metadata/metafiles.php')) {
1377 1376
                 require_once('modules/'.$this->module.'/metadata/metafiles.php');
1378
-                if(!empty($metafiles[$this->module][$viewDef])){
1377
+                if (!empty($metafiles[$this->module][$viewDef])) {
1379 1378
                     $metadataFile = $metafiles[$this->module][$viewDef];
1380 1379
                     $foundViewDefs = true;
1381 1380
                 }
1382 1381
             }
1383 1382
         }
1384 1383
 
1385
-        if(!$foundViewDefs && file_exists($coreMetaPath)){
1384
+        if (!$foundViewDefs && file_exists($coreMetaPath)) {
1386 1385
                 $metadataFile = $coreMetaPath;
1387 1386
         }
1388
-        $GLOBALS['log']->debug("metadatafile=". $metadataFile);
1387
+        $GLOBALS['log']->debug("metadatafile=".$metadataFile);
1389 1388
 
1390 1389
         return $metadataFile;
1391 1390
     }
@@ -1402,10 +1401,10 @@  discard block
 block discarded – undo
1402 1401
     {
1403 1402
         $params = array($this->_getModuleTitleListParam($browserTitle));
1404 1403
 		//$params = array();
1405
-        if (isset($this->action)){
1404
+        if (isset($this->action)) {
1406 1405
             switch ($this->action) {
1407 1406
             case 'EditView':
1408
-                if(!empty($this->bean->id) && (empty($_REQUEST['isDuplicate']) || $_REQUEST['isDuplicate'] === 'false')) {
1407
+                if (!empty($this->bean->id) && (empty($_REQUEST['isDuplicate']) || $_REQUEST['isDuplicate'] === 'false')) {
1409 1408
                     $params[] = "<a href='index.php?module={$this->module}&action=DetailView&record={$this->bean->id}'>".$this->bean->get_summary_text()."</a>";
1410 1409
                     $params[] = $GLOBALS['app_strings']['LBL_EDIT_BUTTON_LABEL'];
1411 1410
                 }
@@ -1429,18 +1428,18 @@  discard block
 block discarded – undo
1429 1428
      *                           there should be no HTML in the string
1430 1429
      * @return string
1431 1430
      */
1432
-    protected function _getModuleTitleListParam( $browserTitle = false )
1431
+    protected function _getModuleTitleListParam($browserTitle = false)
1433 1432
     {
1434 1433
     	global $current_user;
1435 1434
     	global $app_strings;
1436 1435
 
1437
-    	if(!empty($GLOBALS['app_list_strings']['moduleList'][$this->module]))
1436
+    	if (!empty($GLOBALS['app_list_strings']['moduleList'][$this->module]))
1438 1437
     		$firstParam = $GLOBALS['app_list_strings']['moduleList'][$this->module];
1439 1438
     	else
1440 1439
     		$firstParam = $this->module;
1441 1440
 
1442 1441
     	$iconPath = $this->getModuleTitleIconPath($this->module);
1443
-    	if($this->action == "ListView" || $this->action == "index") {
1442
+    	if ($this->action == "ListView" || $this->action == "index") {
1444 1443
     	    if (!empty($iconPath) && !$browserTitle) {
1445 1444
     	    	if (SugarThemeRegistry::current()->directionality == "ltr") {
1446 1445
     	    		return $app_strings['LBL_SEARCH']."&nbsp;"
@@ -1466,10 +1465,10 @@  discard block
 block discarded – undo
1466 1465
     protected function getModuleTitleIconPath($module)
1467 1466
     {
1468 1467
     	$iconPath = "";
1469
-    	if(is_file(SugarThemeRegistry::current()->getImageURL('icon_'.$module.'_32.png',false))) {
1468
+    	if (is_file(SugarThemeRegistry::current()->getImageURL('icon_'.$module.'_32.png', false))) {
1470 1469
     		$iconPath = SugarThemeRegistry::current()->getImageURL('icon_'.$module.'_32.png');
1471 1470
     	}
1472
-    	else if (is_file(SugarThemeRegistry::current()->getImageURL('icon_'.ucfirst($module).'_32.png',false))) {
1471
+    	else if (is_file(SugarThemeRegistry::current()->getImageURL('icon_'.ucfirst($module).'_32.png', false))) {
1473 1472
     		$iconPath = SugarThemeRegistry::current()->getImageURL('icon_'.ucfirst($module).'_32.png');
1474 1473
     	}
1475 1474
     	return $iconPath;
@@ -1486,11 +1485,11 @@  discard block
 block discarded – undo
1486 1485
         global $app_strings;
1487 1486
 
1488 1487
         $browserTitle = $app_strings['LBL_BROWSER_TITLE'];
1489
-        if ( $this->module == 'Users' && ($this->action == 'SetTimezone' || $this->action == 'Login') )
1488
+        if ($this->module == 'Users' && ($this->action == 'SetTimezone' || $this->action == 'Login'))
1490 1489
             return $browserTitle;
1491 1490
         $params = $this->_getModuleTitleParams(true);
1492
-        foreach ($params as $value )
1493
-            $browserTitle = strip_tags($value) . ' &raquo; ' . $browserTitle;
1491
+        foreach ($params as $value)
1492
+            $browserTitle = strip_tags($value).' &raquo; '.$browserTitle;
1494 1493
 
1495 1494
         return $browserTitle;
1496 1495
     }
@@ -1502,7 +1501,7 @@  discard block
 block discarded – undo
1502 1501
      */
1503 1502
     public function getBreadCrumbSymbol()
1504 1503
     {
1505
-    	if(SugarThemeRegistry::current()->directionality == "ltr") {
1504
+    	if (SugarThemeRegistry::current()->directionality == "ltr") {
1506 1505
         	return "<span class='pointer'>&raquo;</span>";
1507 1506
         }
1508 1507
         else {
@@ -1515,29 +1514,29 @@  discard block
 block discarded – undo
1515 1514
      *
1516 1515
      * @return array
1517 1516
      */
1518
-    protected function getSugarConfigJS(){
1517
+    protected function getSugarConfigJS() {
1519 1518
         global $sugar_config;
1520 1519
 
1521 1520
         // Set all the config parameters in the JS config as necessary
1522 1521
         $config_js = array();
1523 1522
         // AjaxUI stock banned modules
1524 1523
         $config_js[] = "SUGAR.config.stockAjaxBannedModules = ".json_encode(ajaxBannedModules()).";";
1525
-        if ( isset($sugar_config['quicksearch_querydelay']) ) {
1524
+        if (isset($sugar_config['quicksearch_querydelay'])) {
1526 1525
             $config_js[] = $this->prepareConfigVarForJs('quicksearch_querydelay', $sugar_config['quicksearch_querydelay']);
1527 1526
         }
1528
-        if ( empty($sugar_config['disableAjaxUI']) ) {
1527
+        if (empty($sugar_config['disableAjaxUI'])) {
1529 1528
             $config_js[] = "SUGAR.config.disableAjaxUI = false;";
1530 1529
         }
1531
-        else{
1530
+        else {
1532 1531
             $config_js[] = "SUGAR.config.disableAjaxUI = true;";
1533 1532
         }
1534
-        if ( !empty($sugar_config['addAjaxBannedModules']) ){
1533
+        if (!empty($sugar_config['addAjaxBannedModules'])) {
1535 1534
             $config_js[] = $this->prepareConfigVarForJs('addAjaxBannedModules', $sugar_config['addAjaxBannedModules']);
1536 1535
         }
1537
-        if ( !empty($sugar_config['overrideAjaxBannedModules']) ){
1536
+        if (!empty($sugar_config['overrideAjaxBannedModules'])) {
1538 1537
             $config_js[] = $this->prepareConfigVarForJs('overrideAjaxBannedModules', $sugar_config['overrideAjaxBannedModules']);
1539 1538
         }
1540
-        if (!empty($sugar_config['js_available']) && is_array ($sugar_config['js_available']))
1539
+        if (!empty($sugar_config['js_available']) && is_array($sugar_config['js_available']))
1541 1540
         {
1542 1541
             foreach ($sugar_config['js_available'] as $configKey)
1543 1542
             {
@@ -1598,7 +1597,7 @@  discard block
 block discarded – undo
1598 1597
     protected function getFavicon()
1599 1598
     {
1600 1599
         // get favicon
1601
-        if(isset($GLOBALS['sugar_config']['default_module_favicon']))
1600
+        if (isset($GLOBALS['sugar_config']['default_module_favicon']))
1602 1601
             $module_favicon = $GLOBALS['sugar_config']['default_module_favicon'];
1603 1602
         else
1604 1603
             $module_favicon = false;
@@ -1606,10 +1605,10 @@  discard block
 block discarded – undo
1606 1605
         $themeObject = SugarThemeRegistry::current();
1607 1606
 
1608 1607
         $favicon = '';
1609
-        if ( $module_favicon )
1610
-            $favicon = $themeObject->getImageURL($this->module.'.gif',false);
1611
-        if ( !sugar_is_file($favicon) || !$module_favicon )
1612
-            $favicon = $themeObject->getImageURL('sugar_icon.ico',false);
1608
+        if ($module_favicon)
1609
+            $favicon = $themeObject->getImageURL($this->module.'.gif', false);
1610
+        if (!sugar_is_file($favicon) || !$module_favicon)
1611
+            $favicon = $themeObject->getImageURL('sugar_icon.ico', false);
1613 1612
 
1614 1613
         $extension = pathinfo($favicon, PATHINFO_EXTENSION);
1615 1614
         switch ($extension)
@@ -1666,10 +1665,10 @@  discard block
 block discarded – undo
1666 1665
      * @return array augmented history with image link and shortened name
1667 1666
      */
1668 1667
     protected function processRecentRecords($history) {
1669
-        foreach ( $history as $key => $row ) {
1668
+        foreach ($history as $key => $row) {
1670 1669
             $history[$key]['item_summary_short'] = to_html(getTrackerSubstring($row['item_summary'])); //bug 56373 - need to re-HTML-encode
1671 1670
             $history[$key]['image'] = SugarThemeRegistry::current()
1672
-                ->getImage($row['module_name'],'border="0" align="absmiddle"',null,null,'.gif',$row['item_summary']);
1671
+                ->getImage($row['module_name'], 'border="0" align="absmiddle"', null, null, '.gif', $row['item_summary']);
1673 1672
         }
1674 1673
         return $history;
1675 1674
     }
@@ -1683,10 +1682,10 @@  discard block
 block discarded – undo
1683 1682
      *
1684 1683
 	 * @return boolean indicating true or false
1685 1684
 	 */
1686
-    public function checkPostMaxSizeError(){
1685
+    public function checkPostMaxSizeError() {
1687 1686
          //if the referrer is post, and the post array is empty, then an error has occurred, most likely
1688 1687
          //while uploading a file that exceeds the post_max_size.
1689
-         if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
1688
+         if (empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
1690 1689
              $GLOBALS['log']->fatal($GLOBALS['app_strings']['UPLOAD_ERROR_HOME_TEXT']);
1691 1690
              return true;
1692 1691
         }
Please login to merge, or discard this patch.