Completed
Push — develop ( 7c1bda...edae1e )
by Adam
18:38 queued 03:14
created
modules/UpgradeWizard/end.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
     if (file_exists($file)) {
80 80
         require_once $file;
81 81
         unset($GLOBALS['dictionary'][$bean]);
82
-        $focus = new $bean ();
82
+        $focus = new $bean();
83 83
         if (($focus instanceof SugarBean)) {
84 84
             if (!isset($repairedTables[$focus->table_name])) {
85 85
                 $sql = $GLOBALS['db']->repairTable($focus, true);
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 $mod_strings = return_module_language($current_language, 'UpgradeWizard');
249 249
 $stop = false;
250 250
 
251
-$httpHost = $_SERVER['HTTP_HOST'];  // cn: 8472 - HTTP_HOST includes port in some cases
251
+$httpHost = $_SERVER['HTTP_HOST']; // cn: 8472 - HTTP_HOST includes port in some cases
252 252
 if ($colon = strpos($httpHost, ':')) {
253 253
     $httpHost = substr($httpHost, 0, $colon);
254 254
 }
Please login to merge, or discard this patch.
Charts/Dashlets/PipelineBySalesStageDashlet/PipelineBySalesStageDashlet.php 2 patches
Braces   +26 added lines, -19 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.
@@ -67,14 +69,17 @@  discard block
 block discarded – undo
67 69
     {
68 70
         global $timedate;
69 71
 
70
-        if(empty($options['pbss_date_start']))
71
-            $options['pbss_date_start'] = $timedate->nowDbDate();
72
+        if(empty($options['pbss_date_start'])) {
73
+                    $options['pbss_date_start'] = $timedate->nowDbDate();
74
+        }
72 75
 
73
-        if(empty($options['pbss_date_end']))
74
-            $options['pbss_date_end'] = $timedate->asDbDate($timedate->getNow()->modify("+6 months"));
76
+        if(empty($options['pbss_date_end'])) {
77
+                    $options['pbss_date_end'] = $timedate->asDbDate($timedate->getNow()->modify("+6 months"));
78
+        }
75 79
 
76
-        if(empty($options['title']))
77
-            $options['title'] = translate('LBL_RGraph_PIPELINE_FORM_TITLE', 'Home');
80
+        if(empty($options['title'])) {
81
+                    $options['title'] = translate('LBL_RGraph_PIPELINE_FORM_TITLE', 'Home');
82
+        }
78 83
 
79 84
         parent::__construct($id,$options);
80 85
     }
@@ -86,11 +91,12 @@  discard block
 block discarded – undo
86 91
     {
87 92
         global $app_list_strings;
88 93
 
89
-        if (!empty($this->pbss_sales_stages) && count($this->pbss_sales_stages) > 0)
90
-            foreach ($this->pbss_sales_stages as $key)
94
+        if (!empty($this->pbss_sales_stages) && count($this->pbss_sales_stages) > 0) {
95
+                    foreach ($this->pbss_sales_stages as $key)
91 96
                 $selected_datax[] = $key;
92
-        else
93
-            $selected_datax = array_keys($app_list_strings['sales_stage_dom']);
97
+        } else {
98
+                    $selected_datax = array_keys($app_list_strings['sales_stage_dom']);
99
+        }
94 100
 
95 101
         $this->_searchFields['pbss_sales_stages']['options'] = $app_list_strings['sales_stage_dom'];
96 102
         $this->_searchFields['pbss_sales_stages']['input_name0'] = $selected_datax;
@@ -265,15 +271,15 @@  discard block
 block discarded – undo
265 271
                 $datax[$key] = $app_list_strings['sales_stage_dom'][$key];
266 272
                 $selected_datax[] = $key;
267 273
             }
268
-        }
269
-        else {
274
+        } else {
270 275
             $datax = $app_list_strings['sales_stage_dom'];
271 276
             $selected_datax = array_keys($app_list_strings['sales_stage_dom']);
272 277
         }
273 278
 
274 279
         $result = $db->query($query);
275
-        while($row = $db->fetchByAssoc($result, false))
276
-            $temp_data[] = $row;
280
+        while($row = $db->fetchByAssoc($result, false)) {
281
+                    $temp_data[] = $row;
282
+        }
277 283
 
278 284
         // reorder and set the array based on the order of selected_datax
279 285
         foreach($selected_datax as $sales_stage){
@@ -348,10 +354,11 @@  discard block
 block discarded – undo
348 354
 
349 355
     protected function resizeLabel($label)
350 356
     {
351
-        if(strlen($label) < $this->maxLabelSizeBeforeTotal)
352
-            return $label;
353
-        else
354
-            return substr($label,0,$this->maxLabelSizeBeforeTotal).$this->labelReplacementString;
357
+        if(strlen($label) < $this->maxLabelSizeBeforeTotal) {
358
+                    return $label;
359
+        } else {
360
+                    return substr($label,0,$this->maxLabelSizeBeforeTotal).$this->labelReplacementString;
361
+        }
355 362
 
356 363
     }
357 364
 
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 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.
@@ -67,16 +67,16 @@  discard block
 block discarded – undo
67 67
     {
68 68
         global $timedate;
69 69
 
70
-        if(empty($options['pbss_date_start']))
70
+        if (empty($options['pbss_date_start']))
71 71
             $options['pbss_date_start'] = $timedate->nowDbDate();
72 72
 
73
-        if(empty($options['pbss_date_end']))
73
+        if (empty($options['pbss_date_end']))
74 74
             $options['pbss_date_end'] = $timedate->asDbDate($timedate->getNow()->modify("+6 months"));
75 75
 
76
-        if(empty($options['title']))
76
+        if (empty($options['title']))
77 77
             $options['title'] = translate('LBL_RGraph_PIPELINE_FORM_TITLE', 'Home');
78 78
 
79
-        parent::__construct($id,$options);
79
+        parent::__construct($id, $options);
80 80
     }
81 81
 
82 82
     /**
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
         $thousands_symbol = translate('LBL_OPP_THOUSANDS', 'Charts');
110 110
 
111 111
         $currency_symbol = $sugar_config['default_currency_symbol'];
112
-        if ($current_user->getPreference('currency')){
112
+        if ($current_user->getPreference('currency')) {
113 113
 
114 114
             $currency = new Currency();
115 115
             $currency->retrieve($current_user->getPreference('currency'));
@@ -136,20 +136,20 @@  discard block
 block discarded – undo
136 136
         //These are taken in the same fashion as the hard-coded array above
137 137
         $module = 'Opportunities';
138 138
         $action = 'index';
139
-        $query  ='true';
140
-        $searchFormTab ='advanced_search';
139
+        $query  = 'true';
140
+        $searchFormTab = 'advanced_search';
141 141
 
142 142
         $chartWidth     = 900;
143 143
         $chartHeight    = 500;
144 144
 
145
-        $autoRefresh = $this->processAutoRefresh();//$autoRefresh
145
+        $autoRefresh = $this->processAutoRefresh(); //$autoRefresh
146 146
 
147 147
         $colours = "['#a6cee3','#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99','#b15928']";
148 148
         //<canvas id='$canvasId' width='$chartWidth' height='$chartHeight'>[No canvas support]</canvas>
149 149
         //<canvas id='test123'  width='$chartWidth' height='$chartHeight'>[No canvas support]</canvas>
150 150
 
151 151
         //Check for an empty array
152
-        if(!is_array($chartReadyData['data'])||count($chartReadyData['data']) < 1)
152
+        if (!is_array($chartReadyData['data']) || count($chartReadyData['data']) < 1)
153 153
         {
154 154
             return "<h3 class='noGraphDataPoints'>$this->noDataMessage</h3>";
155 155
         }
@@ -274,13 +274,13 @@  discard block
 block discarded – undo
274 274
         }
275 275
 
276 276
         $result = $db->query($query);
277
-        while($row = $db->fetchByAssoc($result, false))
277
+        while ($row = $db->fetchByAssoc($result, false))
278 278
             $temp_data[] = $row;
279 279
 
280 280
         // reorder and set the array based on the order of selected_datax
281
-        foreach($selected_datax as $sales_stage){
282
-            foreach($temp_data as $key => $value){
283
-                if ($value['sales_stage'] == $sales_stage){
281
+        foreach ($selected_datax as $sales_stage) {
282
+            foreach ($temp_data as $key => $value) {
283
+                if ($value['sales_stage'] == $sales_stage) {
284 284
                     $value['sales_stage'] = $app_list_strings['sales_stage_dom'][$value['sales_stage']];
285 285
                     $value['key'] = $sales_stage;
286 286
                     $value['value'] = $value['sales_stage'];
@@ -320,40 +320,40 @@  discard block
 block discarded – undo
320 320
                         count(*) AS opp_count,
321 321
                         sum(amount_usdollar/1000) AS total
322 322
                     FROM users,opportunities  ";
323
-        $query .= " WHERE opportunities.date_closed >= ". db_convert("'".$this->pbss_date_start."'",'date').
324
-            " AND opportunities.date_closed <= ".db_convert("'".$this->pbss_date_end."'",'date') .
323
+        $query .= " WHERE opportunities.date_closed >= ".db_convert("'".$this->pbss_date_start."'", 'date').
324
+            " AND opportunities.date_closed <= ".db_convert("'".$this->pbss_date_end."'", 'date').
325 325
             " AND opportunities.assigned_user_id = users.id  AND opportunities.deleted=0 ";
326 326
         $query .= " GROUP BY opportunities.sales_stage";
327 327
 
328 328
         return $query;
329 329
     }
330 330
 
331
-    protected function prepareChartData($data,$currency_symbol, $thousands_symbol)
331
+    protected function prepareChartData($data, $currency_symbol, $thousands_symbol)
332 332
     {
333 333
         //return $data;
334
-        $chart['labels']=array();
335
-        $chart['data']=array();
336
-        $chart['keys']=array();
334
+        $chart['labels'] = array();
335
+        $chart['data'] = array();
336
+        $chart['keys'] = array();
337 337
         $total = 0;
338
-        foreach($data as $i)
338
+        foreach ($data as $i)
339 339
         {
340 340
             //$chart['labelsAndValues'][]=$i['key'].' ('.$currency.(int)$i['total'].')';
341
-            $chart['labelsAndValues'][]=$this->resizeLabel($i['value']).' ('.$currency_symbol.(int)$i['total'].$thousands_symbol.')';
342
-            $chart['labels'][]=$i['value'];
343
-            $chart['keys'][]=$i['key'];
344
-            $chart['data'][]=(int)$i['total'];
345
-            $total+=(int)$i['total'];
341
+            $chart['labelsAndValues'][] = $this->resizeLabel($i['value']).' ('.$currency_symbol.(int)$i['total'].$thousands_symbol.')';
342
+            $chart['labels'][] = $i['value'];
343
+            $chart['keys'][] = $i['key'];
344
+            $chart['data'][] = (int)$i['total'];
345
+            $total += (int)$i['total'];
346 346
         }
347
-        $chart['total']=$total;
347
+        $chart['total'] = $total;
348 348
         return $chart;
349 349
     }
350 350
 
351 351
     protected function resizeLabel($label)
352 352
     {
353
-        if(strlen($label) < $this->maxLabelSizeBeforeTotal)
353
+        if (strlen($label) < $this->maxLabelSizeBeforeTotal)
354 354
             return $label;
355 355
         else
356
-            return substr($label,0,$this->maxLabelSizeBeforeTotal).$this->labelReplacementString;
356
+            return substr($label, 0, $this->maxLabelSizeBeforeTotal).$this->labelReplacementString;
357 357
 
358 358
     }
359 359
 
Please login to merge, or discard this patch.
include/database/DBManager.php 3 patches
Braces   +276 added lines, -198 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.
@@ -403,13 +405,15 @@  discard block
 block discarded – undo
403 405
 	$match = array();
404 406
 	preg_match_all("'.* FROM ([^ ]*).* ORDER BY (.*)'is", $sql, $match);
405 407
 	$indices = false;
406
-	if (!empty($match[1][0]))
407
-		$table = $match[1][0];
408
-	else
409
-		return false;
408
+	if (!empty($match[1][0])) {
409
+			$table = $match[1][0];
410
+	} else {
411
+			return false;
412
+	}
410 413
 
411
-	if (!empty($object_name) && !empty($GLOBALS['dictionary'][$object_name]))
412
-		$indices = $GLOBALS['dictionary'][$object_name]['indices'];
414
+	if (!empty($object_name) && !empty($GLOBALS['dictionary'][$object_name])) {
415
+			$indices = $GLOBALS['dictionary'][$object_name]['indices'];
416
+	}
413 417
 
414 418
 	if (empty($indices)) {
415 419
 		foreach ( $GLOBALS['dictionary'] as $current ) {
@@ -427,25 +431,29 @@  discard block
 block discarded – undo
427 431
 		$orderBys = explode(' ', $match[2][0]);
428 432
 		foreach ($orderBys as $orderBy){
429 433
 			$orderBy = trim($orderBy);
430
-			if (empty($orderBy))
431
-				continue;
434
+			if (empty($orderBy)) {
435
+							continue;
436
+			}
432 437
 			$orderBy = strtolower($orderBy);
433
-			if ($orderBy == 'asc' || $orderBy == 'desc')
434
-				continue;
438
+			if ($orderBy == 'asc' || $orderBy == 'desc') {
439
+							continue;
440
+			}
435 441
 
436 442
 			$orderBy = str_replace(array($table . '.', ','), '', $orderBy);
437 443
 
438
-			foreach ($indices as $index)
439
-				if (empty($index['db']) || $index['db'] == $this->dbType)
444
+			foreach ($indices as $index) {
445
+							if (empty($index['db']) || $index['db'] == $this->dbType)
440 446
 					foreach ($index['fields'] as $field)
441 447
 						if ($field == $orderBy)
442 448
 							return true;
449
+			}
443 450
 
444 451
 			$warning = 'Missing Index For Order By Table: ' . $table . ' Order By:' . $orderBy ;
445
-			if (!empty($GLOBALS['sugar_config']['dump_slow_queries']))
446
-				$this->log->fatal('CHECK QUERY:' .$warning);
447
-			else
448
-				$this->log->warn('CHECK QUERY:' .$warning);
452
+			if (!empty($GLOBALS['sugar_config']['dump_slow_queries'])) {
453
+							$this->log->fatal('CHECK QUERY:' .$warning);
454
+			} else {
455
+							$this->log->warn('CHECK QUERY:' .$warning);
456
+			}
449 457
 		}
450 458
 	}
451 459
 	return false;
@@ -467,8 +475,9 @@  discard block
 block discarded – undo
467 475
 	public function checkConnection()
468 476
 	{
469 477
 		$this->last_error = '';
470
-		if (!isset($this->database))
471
-			$this->connect();
478
+		if (!isset($this->database)) {
479
+					$this->connect();
480
+		}
472 481
 	}
473 482
 
474 483
 	/**
@@ -510,9 +519,13 @@  discard block
 block discarded – undo
510 519
 		$values = array();
511 520
 		foreach ($field_defs as $field => $fieldDef)
512 521
 		{
513
-			if (isset($fieldDef['source']) && $fieldDef['source'] != 'db')  continue;
522
+			if (isset($fieldDef['source']) && $fieldDef['source'] != 'db') {
523
+			    continue;
524
+			}
514 525
 			//custom fields handle there save seperatley
515
-			if(!empty($field_map) && !empty($field_map[$field]['custom_type'])) continue;
526
+			if(!empty($field_map) && !empty($field_map[$field]['custom_type'])) {
527
+			    continue;
528
+			}
516 529
 
517 530
 			if(isset($data[$field])) {
518 531
 				// clean the incoming value..
@@ -541,8 +554,10 @@  discard block
 block discarded – undo
541 554
 			}
542 555
 		}
543 556
 
544
-		if (empty($values))
545
-			return $execute?true:''; // no columns set
557
+		if (empty($values)) {
558
+					return $execute?true:'';
559
+		}
560
+		// no columns set
546 561
 
547 562
 		// get the entire sql
548 563
 		$query = "INSERT INTO $table (".implode(",", array_keys($values)).")
@@ -642,9 +657,10 @@  discard block
 block discarded – undo
642 657
 		if(!$this->supports("inline_keys")) {
643 658
 		// handle constraints and indices
644 659
 			$indicesArr = $this->createConstraintSql($bean);
645
-			if (count($indicesArr) > 0)
646
-				foreach ($indicesArr as $indexSql)
660
+			if (count($indicesArr) > 0) {
661
+							foreach ($indicesArr as $indexSql)
647 662
 					$this->query($indexSql, true, $msg);
663
+			}
648 664
 		}
649 665
 	}
650 666
 
@@ -681,9 +697,10 @@  discard block
 block discarded – undo
681 697
 			if(!$this->supports("inline_keys")) {
682 698
 				// handle constraints and indices
683 699
 				$indicesArr = $this->getConstraintSql($indices, $tablename);
684
-				if (count($indicesArr) > 0)
685
-					foreach ($indicesArr as $indexSql)
700
+				if (count($indicesArr) > 0) {
701
+									foreach ($indicesArr as $indexSql)
686 702
 						$res = ($res and $this->query($indexSql, true, "Error creating indexes"));
703
+				}
687 704
 			}
688 705
 			return $res;
689 706
 		}
@@ -710,13 +727,15 @@  discard block
 block discarded – undo
710 727
 		}
711 728
 		//jc: added this for beans that do not actually have a table, namely
712 729
 		//ForecastOpportunities
713
-		if($tablename == 'does_not_exist' || $tablename == '')
714
-			return '';
730
+		if($tablename == 'does_not_exist' || $tablename == '') {
731
+					return '';
732
+		}
715 733
 
716 734
 		global $dictionary;
717 735
 		$engine=null;
718
-		if (isset($dictionary[$bean->getObjectName()]['engine']) && !empty($dictionary[$bean->getObjectName()]['engine']) )
719
-			$engine = $dictionary[$bean->getObjectName()]['engine'];
736
+		if (isset($dictionary[$bean->getObjectName()]['engine']) && !empty($dictionary[$bean->getObjectName()]['engine']) ) {
737
+					$engine = $dictionary[$bean->getObjectName()]['engine'];
738
+		}
720 739
 
721 740
 		return $this->repairTableParams($tablename, $fielddefs,$new_index,$execute,$engine);
722 741
 	}
@@ -760,8 +779,9 @@  discard block
 block discarded – undo
760 779
 	{
761 780
 		//jc: had a bug when running the repair if the tablename is blank the repair will
762 781
 		//fail when it tries to create a repair table
763
-		if ($tablename == '' || empty($fielddefs))
764
-			return '';
782
+		if ($tablename == '' || empty($fielddefs)) {
783
+					return '';
784
+		}
765 785
 
766 786
 		//if the table does not exist create it and we are done
767 787
 		$sql = "/* Table : $tablename */\n";
@@ -784,16 +804,16 @@  discard block
 block discarded – undo
784 804
 		// do column comparisons
785 805
 		$sql .=	"/*COLUMNS*/\n";
786 806
 		foreach ($fielddefs as $name => $value) {
787
-			if (isset($value['source']) && $value['source'] != 'db')
788
-				continue;
807
+			if (isset($value['source']) && $value['source'] != 'db') {
808
+							continue;
809
+			}
789 810
 
790 811
             // Bug #42406. Skipping breaked vardef without type or name
791 812
             if (isset($value['name']) == false || $value['name'] == false)
792 813
             {
793 814
                 $sql .= "/* NAME IS MISSING IN VARDEF $tablename::$name */\n";
794 815
                 continue;
795
-            }
796
-            else if (isset($value['type']) == false || $value['type'] == false)
816
+            } else if (isset($value['type']) == false || $value['type'] == false)
797 817
             {
798 818
                 $sql .= "/* TYPE IS MISSING IN VARDEF $tablename::$name */\n";
799 819
                 continue;
@@ -823,8 +843,9 @@  discard block
 block discarded – undo
823 843
 				// ok we need this field lets create it
824 844
 				$sql .=	"/*MISSING IN DATABASE - $name -  ROW*/\n";
825 845
 				$sql .= $this->addColumnSQL($tablename, $value) .  "\n";
826
-				if ($execute)
827
-					$this->addColumn($tablename, $value);
846
+				if ($execute) {
847
+									$this->addColumn($tablename, $value);
848
+				}
828 849
 				$take_action = true;
829 850
 			} elseif ( !$this->compareVarDefs($compareFieldDefs[$name],$value)) {
830 851
 				//fields are different lets alter it
@@ -880,8 +901,9 @@  discard block
 block discarded – undo
880 901
 		unset($compareIndices_case_insensitive);
881 902
 
882 903
 		foreach ($indices as $value) {
883
-			if (isset($value['source']) && $value['source'] != 'db')
884
-				continue;
904
+			if (isset($value['source']) && $value['source'] != 'db') {
905
+							continue;
906
+			}
885 907
 
886 908
 
887 909
 			$validDBName = $this->getValidDBName($value['name'], true, 'index', true);
@@ -891,19 +913,23 @@  discard block
 block discarded – undo
891 913
 		    $name = strtolower($value['name']);
892 914
 
893 915
 			//Don't attempt to fix the same index twice in one pass;
894
-			if (isset($correctedIndexs[$name]))
895
-				continue;
916
+			if (isset($correctedIndexs[$name])) {
917
+							continue;
918
+			}
896 919
 
897 920
 			//don't bother checking primary nothing we can do about them
898
-			if (isset($value['type']) && $value['type'] == 'primary')
899
-				continue;
921
+			if (isset($value['type']) && $value['type'] == 'primary') {
922
+							continue;
923
+			}
900 924
 
901 925
 			//database helpers do not know how to handle full text indices
902
-			if ($value['type']=='fulltext')
903
-				continue;
926
+			if ($value['type']=='fulltext') {
927
+							continue;
928
+			}
904 929
 
905
-			if ( in_array($value['type'],array('alternate_key','foreign')) )
906
-				$value['type'] = 'index';
930
+			if ( in_array($value['type'],array('alternate_key','foreign')) ) {
931
+							$value['type'] = 'index';
932
+			}
907 933
 
908 934
 			if ( !isset($compareIndices[$name]) ) {
909 935
 				//First check if an index exists that doesn't match our name, if so, try to rename it
@@ -934,21 +960,23 @@  discard block
 block discarded – undo
934 960
 				$sql .=	"/*INDEX MISMATCH WITH DATABASE - $name -  ROW ";
935 961
 				foreach ($compareIndices[$name] as $n1 => $t1) {
936 962
 					$sql .=	 "<$n1>";
937
-					if ( $n1 == 'fields' )
938
-						foreach($t1 as $rKey => $rValue)
963
+					if ( $n1 == 'fields' ) {
964
+											foreach($t1 as $rKey => $rValue)
939 965
 							$sql .= "[$rKey] => '$rValue'  ";
940
-					else
941
-						$sql .= " $t1 ";
966
+					} else {
967
+											$sql .= " $t1 ";
968
+					}
942 969
 				}
943 970
 				$sql .=	"*/\n";
944 971
 				$sql .=	"/* VARDEF - $name -  ROW";
945 972
 				foreach ($value as $n1 => $t1) {
946 973
 					$sql .=	"<$n1>";
947
-					if ( $n1 == 'fields' )
948
-						foreach ($t1 as $rKey => $rValue)
974
+					if ( $n1 == 'fields' ) {
975
+											foreach ($t1 as $rKey => $rValue)
949 976
 							$sql .=	"[$rKey] => '$rValue'  ";
950
-					else
951
-						$sql .= " $t1 ";
977
+					} else {
978
+											$sql .= " $t1 ";
979
+					}
952 980
 				}
953 981
 				$sql .=	"*/\n";
954 982
 				$sql .= $this->modifyIndexes($tablename,array($value), $execute) .  "\n";
@@ -971,8 +999,9 @@  discard block
 block discarded – undo
971 999
 	public function compareVarDefs($fielddef1, $fielddef2, $ignoreName = false)
972 1000
 	{
973 1001
 		foreach ( $fielddef1 as $key => $value ) {
974
-			if ($key == 'name' && $ignoreName)
975
-				continue;
1002
+			if ($key == 'name' && $ignoreName) {
1003
+							continue;
1004
+			}
976 1005
             if (isset($fielddef2[$key]))
977 1006
             {
978 1007
                 if (!is_array($fielddef1[$key]) && !is_array($fielddef2[$key]))
@@ -981,8 +1010,7 @@  discard block
 block discarded – undo
981 1010
                     {
982 1011
                         continue;
983 1012
                     }
984
-                }
985
-                else
1013
+                } else
986 1014
                 {
987 1015
                     if (array_map('strtolower', $fielddef1[$key]) == array_map('strtolower',$fielddef2[$key]))
988 1016
                     {
@@ -991,8 +1019,9 @@  discard block
 block discarded – undo
991 1019
                 }
992 1020
             }
993 1021
 			//Ignore len if its not set in the vardef
994
-			if ($key == 'len' && empty($fielddef2[$key]))
995
-				continue;
1022
+			if ($key == 'len' && empty($fielddef2[$key])) {
1023
+							continue;
1024
+			}
996 1025
             // if the length in db is greather than the vardef, ignore it
997 1026
             if ($key == 'len' && ($fielddef1[$key] >= $fielddef2[$key])) {
998 1027
                 continue;
@@ -1026,12 +1055,10 @@  discard block
 block discarded – undo
1026 1055
 			if (!$row2) {
1027 1056
 				// Exists on table1 but not table2
1028 1057
 				$returnArray['msg'] = 'not_exists_table2';
1029
-			}
1030
-			else {
1058
+			} else {
1031 1059
 				if (sizeof($row1) != sizeof($row2)) {
1032 1060
 					$returnArray['msg'] = 'no_match';
1033
-				}
1034
-				else {
1061
+				} else {
1035 1062
 					$returnArray['msg'] = 'match';
1036 1063
 					foreach($row1 as $key => $value){
1037 1064
 						//ignore keys when checking we will check them when we do the index check
@@ -1041,8 +1068,7 @@  discard block
 block discarded – undo
1041 1068
 					}
1042 1069
 				}
1043 1070
 			}
1044
-		}
1045
-		else {
1071
+		} else {
1046 1072
 			$returnArray['msg'] = 'not_exists_table1';
1047 1073
 		}
1048 1074
 
@@ -1122,16 +1148,19 @@  discard block
 block discarded – undo
1122 1148
 	 */
1123 1149
 	public function getConstraintSql($indices, $table)
1124 1150
 	{
1125
-		if (!$this->isFieldArray($indices))
1126
-			$indices = array($indices);
1151
+		if (!$this->isFieldArray($indices)) {
1152
+					$indices = array($indices);
1153
+		}
1127 1154
 
1128 1155
 		$columns = array();
1129 1156
 
1130 1157
 		foreach ($indices as $index) {
1131
-			if(!empty($index['db']) && $index['db'] != $this->dbType)
1132
-				continue;
1133
-			if (isset($index['source']) && $index['source'] != 'db')
1134
-			continue;
1158
+			if(!empty($index['db']) && $index['db'] != $this->dbType) {
1159
+							continue;
1160
+			}
1161
+			if (isset($index['source']) && $index['source'] != 'db') {
1162
+						continue;
1163
+			}
1135 1164
 
1136 1165
 			$sql = $this->add_drop_constraint($table, $index);
1137 1166
 
@@ -1221,11 +1250,11 @@  discard block
 block discarded – undo
1221 1250
 		$sql = $this->addColumnSQL($tablename, $fieldDefs);
1222 1251
 		if ($this->isFieldArray($fieldDefs)){
1223 1252
 			$columns = array();
1224
-			foreach ($fieldDefs as $fieldDef)
1225
-				$columns[] = $fieldDef['name'];
1253
+			foreach ($fieldDefs as $fieldDef) {
1254
+							$columns[] = $fieldDef['name'];
1255
+			}
1226 1256
 			$columns = implode(",", $columns);
1227
-		}
1228
-		else {
1257
+		} else {
1229 1258
 			$columns = $fieldDefs['name'];
1230 1259
 		}
1231 1260
 		$msg = "Error adding column(s) $columns on table: $tablename:";
@@ -1249,8 +1278,7 @@  discard block
 block discarded – undo
1249 1278
 				$columns[] = $fieldDef['name'];
1250 1279
 			}
1251 1280
 			$columns = implode(",", $columns);
1252
-		}
1253
-		else {
1281
+		} else {
1254 1282
 			$columns = $newFieldDef['name'];
1255 1283
 		}
1256 1284
 
@@ -1370,7 +1398,9 @@  discard block
 block discarded – undo
1370 1398
 			if(!$is_related_query){
1371 1399
 				foreach ($fields as $fieldDef)
1372 1400
 				{
1373
-					if(isset($fieldDef['source']) && $fieldDef['source'] != 'db' && $fieldDef['source'] != 'custom_fields') continue;
1401
+					if(isset($fieldDef['source']) && $fieldDef['source'] != 'db' && $fieldDef['source'] != 'custom_fields') {
1402
+					    continue;
1403
+					}
1374 1404
 					$val = $row[$fieldDef['name']];
1375 1405
 
1376 1406
 					//handle auto increment values here only need to do this on insert not create
@@ -1379,8 +1409,7 @@  discard block
 block discarded – undo
1379 1409
 							if(!$built_columns){
1380 1410
 							$columns[] = 'deleted';
1381 1411
 						}
1382
-					}
1383
-					else
1412
+					} else
1384 1413
 					{
1385 1414
 						$type = $fieldDef['type'];
1386 1415
 						if(!empty($fieldDef['custom_type'])){
@@ -1388,28 +1417,32 @@  discard block
 block discarded – undo
1388 1417
 						}
1389 1418
 						// need to do some thing about types of values
1390 1419
 						if($this->dbType == 'mysql' && $val == '' && ($type == 'datetime' ||  $type == 'date' || $type == 'int' || $type == 'currency' || $type == 'decimal')){
1391
-							if(!empty($custom_fields[$fieldDef['name']]))
1392
-								$cstm_values[$fieldDef['name']] = 'null';
1393
-							else
1394
-								$values[$fieldDef['name']] = 'null';
1395
-						}else{
1420
+							if(!empty($custom_fields[$fieldDef['name']])) {
1421
+															$cstm_values[$fieldDef['name']] = 'null';
1422
+							} else {
1423
+															$values[$fieldDef['name']] = 'null';
1424
+							}
1425
+						} else{
1396 1426
 							if(isset($type) && $type=='int') {
1397
-								if(!empty($custom_fields[$fieldDef['name']]))
1398
-									$cstm_values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1399
-								else
1400
-									$values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1427
+								if(!empty($custom_fields[$fieldDef['name']])) {
1428
+																	$cstm_values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1429
+								} else {
1430
+																	$values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1431
+								}
1401 1432
 							} else {
1402
-								if(!empty($custom_fields[$fieldDef['name']]))
1403
-									$cstm_values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1404
-								else
1405
-									$values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1433
+								if(!empty($custom_fields[$fieldDef['name']])) {
1434
+																	$cstm_values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1435
+								} else {
1436
+																	$values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1437
+								}
1406 1438
 							}
1407 1439
 						}
1408 1440
 						if(!$built_columns){
1409
-							if(!empty($custom_fields[$fieldDef['name']]))
1410
-								$cstm_columns[] = $fieldDef['name'];
1411
-							else
1412
-								$columns[] = $fieldDef['name'];
1441
+							if(!empty($custom_fields[$fieldDef['name']])) {
1442
+															$cstm_columns[] = $fieldDef['name'];
1443
+							} else {
1444
+															$columns[] = $fieldDef['name'];
1445
+							}
1413 1446
 						}
1414 1447
 					}
1415 1448
 
@@ -1624,7 +1657,9 @@  discard block
 block discarded – undo
1624 1657
 		    $queryresult = $this->query($sql, $dieOnError, $msg);
1625 1658
 		}
1626 1659
 		$this->checkError($msg.' Get One Failed:' . $sql, $dieOnError);
1627
-		if (!$queryresult) return false;
1660
+		if (!$queryresult) {
1661
+		    return false;
1662
+		}
1628 1663
 		$row = $this->fetchByAssoc($queryresult);
1629 1664
 		if(!empty($row)) {
1630 1665
 			return array_shift($row);
@@ -1648,10 +1683,14 @@  discard block
 block discarded – undo
1648 1683
 		$queryresult = $this->query($sql, $dieOnError, $msg);
1649 1684
 		$this->checkError($msg.' Fetch One Failed:' . $sql, $dieOnError);
1650 1685
 
1651
-		if (!$queryresult) return false;
1686
+		if (!$queryresult) {
1687
+		    return false;
1688
+		}
1652 1689
 
1653 1690
 		$row = $this->fetchByAssoc($queryresult);
1654
-		if ( !$row ) return false;
1691
+		if ( !$row ) {
1692
+		    return false;
1693
+		}
1655 1694
 
1656 1695
 		$this->freeResult($queryresult);
1657 1696
 		return $row;
@@ -1708,13 +1747,15 @@  discard block
 block discarded – undo
1708 1747
 	protected function describeField($name, $tablename)
1709 1748
 	{
1710 1749
 		$table = $this->getTableDescription($tablename);
1711
-		if(!empty($table) && isset($table[$name]))
1712
-			return 	$table[$name];
1750
+		if(!empty($table) && isset($table[$name])) {
1751
+					return 	$table[$name];
1752
+		}
1713 1753
 
1714 1754
 		$table = $this->getTableDescription($tablename, true);
1715 1755
 
1716
-		if(isset($table[$name]))
1717
-		return $table[$name];
1756
+		if(isset($table[$name])) {
1757
+				return $table[$name];
1758
+		}
1718 1759
 
1719 1760
 		return array();
1720 1761
 	}
@@ -1768,11 +1809,15 @@  discard block
 block discarded – undo
1768 1809
      */
1769 1810
 	public function concat($table, array $fields, $space = ' ')
1770 1811
 	{
1771
-		if(empty($fields)) return '';
1812
+		if(empty($fields)) {
1813
+		    return '';
1814
+		}
1772 1815
 		$elems = array();
1773 1816
 		$space = $this->quoted($space);
1774 1817
 		foreach ( $fields as $field ) {
1775
-			if(!empty($elems)) $elems[] = $space;
1818
+			if(!empty($elems)) {
1819
+			    $elems[] = $space;
1820
+			}
1776 1821
 			$elems[] = $this->convert("$table.$field", 'IFNULL', array("''"));
1777 1822
 		}
1778 1823
 		$first = array_shift($elems);
@@ -1864,7 +1909,7 @@  discard block
 block discarded – undo
1864 1909
 				}//switch
1865 1910
 			}//foreach
1866 1911
 			return $this->query($query);
1867
-		}else{
1912
+		} else{
1868 1913
 			return false;
1869 1914
 		}
1870 1915
 	}
@@ -1926,20 +1971,30 @@  discard block
 block discarded – undo
1926 1971
         $fields = $bean->getFieldDefinitions();
1927 1972
 		// get column names and values
1928 1973
 		foreach ($fields as $field => $fieldDef) {
1929
-			if (isset($fieldDef['source']) && $fieldDef['source'] != 'db')  continue;
1974
+			if (isset($fieldDef['source']) && $fieldDef['source'] != 'db') {
1975
+			    continue;
1976
+			}
1930 1977
 			// Do not write out the id field on the update statement.
1931 1978
     		// We are not allowed to change ids.
1932
-    		if (empty($fieldDef['name']) || $fieldDef['name'] == $primaryField['name']) continue;
1979
+    		if (empty($fieldDef['name']) || $fieldDef['name'] == $primaryField['name']) {
1980
+    		    continue;
1981
+    		}
1933 1982
 
1934 1983
     		// If the field is an auto_increment field, then we shouldn't be setting it.  This was added
1935 1984
     		// specially for Bugs and Cases which have a number associated with them.
1936
-    		if (!empty($bean->field_name_map[$field]['auto_increment'])) continue;
1985
+    		if (!empty($bean->field_name_map[$field]['auto_increment'])) {
1986
+    		    continue;
1987
+    		}
1937 1988
 
1938 1989
     		//custom fields handle their save separately
1939
-    		if(isset($bean->field_name_map) && !empty($bean->field_name_map[$field]['custom_type']))  continue;
1990
+    		if(isset($bean->field_name_map) && !empty($bean->field_name_map[$field]['custom_type'])) {
1991
+    		    continue;
1992
+    		}
1940 1993
 
1941 1994
     		// no need to clear deleted since we only update not deleted records anyway
1942
-    		if($fieldDef['name'] == 'deleted' && empty($bean->deleted)) continue;
1995
+    		if($fieldDef['name'] == 'deleted' && empty($bean->deleted)) {
1996
+    		    continue;
1997
+    		}
1943 1998
 
1944 1999
     		if(isset($bean->$field)) {
1945 2000
     			$val = from_html($bean->$field);
@@ -1972,8 +2027,10 @@  discard block
 block discarded – undo
1972 2027
     		}
1973 2028
 		}
1974 2029
 
1975
-		if ( sizeof($columns) == 0 )
1976
-			return ""; // no columns set
2030
+		if ( sizeof($columns) == 0 ) {
2031
+					return "";
2032
+		}
2033
+		// no columns set
1977 2034
 
1978 2035
 		// build where clause
1979 2036
 		$where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
@@ -2039,8 +2096,9 @@  discard block
 block discarded – undo
2039 2096
 			$where[] = " $table.$name $op $val";
2040 2097
 		}
2041 2098
 
2042
-		if (!empty($where))
2043
-			return implode(" AND ", $where);
2099
+		if (!empty($where)) {
2100
+					return implode(" AND ", $where);
2101
+		}
2044 2102
 
2045 2103
 		return '';
2046 2104
 	}
@@ -2144,21 +2202,25 @@  discard block
 block discarded – undo
2144 2202
 	public function massageFieldDef(&$fieldDef, $tablename)
2145 2203
 	{
2146 2204
 		if ( !isset($fieldDef['dbType']) ) {
2147
-			if ( isset($fieldDef['dbtype']) )
2148
-				$fieldDef['dbType'] = $fieldDef['dbtype'];
2149
-			else
2150
-				$fieldDef['dbType'] = $fieldDef['type'];
2205
+			if ( isset($fieldDef['dbtype']) ) {
2206
+							$fieldDef['dbType'] = $fieldDef['dbtype'];
2207
+			} else {
2208
+							$fieldDef['dbType'] = $fieldDef['type'];
2209
+			}
2151 2210
 		}
2152 2211
 		$type = $this->getColumnType($fieldDef['dbType'],$fieldDef['name'],$tablename);
2153 2212
 		$matches = array();
2154 2213
         // len can be a number or a string like 'max', for example, nvarchar(max)
2155 2214
         preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*|\w+)\)|)/i', $type, $matches);
2156
-		if ( isset($matches[1][0]) )
2157
-			$fieldDef['type'] = $matches[1][0];
2158
-		if ( isset($matches[2][0]) && empty($fieldDef['len']) )
2159
-			$fieldDef['len'] = $matches[2][0];
2160
-		if ( !empty($fieldDef['precision']) && is_numeric($fieldDef['precision']) && !strstr($fieldDef['len'],',') )
2161
-			$fieldDef['len'] .= ",{$fieldDef['precision']}";
2215
+		if ( isset($matches[1][0]) ) {
2216
+					$fieldDef['type'] = $matches[1][0];
2217
+		}
2218
+		if ( isset($matches[2][0]) && empty($fieldDef['len']) ) {
2219
+					$fieldDef['len'] = $matches[2][0];
2220
+		}
2221
+		if ( !empty($fieldDef['precision']) && is_numeric($fieldDef['precision']) && !strstr($fieldDef['len'],',') ) {
2222
+					$fieldDef['len'] .= ",{$fieldDef['precision']}";
2223
+		}
2162 2224
 		if (!empty($fieldDef['required']) || ($fieldDef['name'] == 'id' && !isset($fieldDef['required'])) ) {
2163 2225
 			$fieldDef['required'] = 'true';
2164 2226
 		}
@@ -2172,8 +2234,9 @@  discard block
 block discarded – undo
2172 2234
 	public function getSelectFieldsFromQuery($selectStatement)
2173 2235
 	{
2174 2236
 		$selectStatement = trim($selectStatement);
2175
-		if (strtoupper(substr($selectStatement, 0, 6)) == "SELECT")
2176
-			$selectStatement = trim(substr($selectStatement, 6));
2237
+		if (strtoupper(substr($selectStatement, 0, 6)) == "SELECT") {
2238
+					$selectStatement = trim(substr($selectStatement, 6));
2239
+		}
2177 2240
 
2178 2241
 		//Due to sql functions existing in many selects, we can't use php explode
2179 2242
 		$fields = array();
@@ -2189,17 +2252,15 @@  discard block
 block discarded – undo
2189 2252
 				$field = $this->getFieldNameFromSelect(trim($selectField));
2190 2253
 				$fields[$field] = $selectField;
2191 2254
 				$selectField = "";
2192
-			}
2193
-			else if ($char == "("){
2255
+			} else if ($char == "("){
2194 2256
 				$level++;
2195 2257
 				$selectField .= $char;
2196
-			}
2197
-			else if($char == ")"){
2258
+			} else if($char == ")"){
2198 2259
 				$level--;
2199 2260
 				$selectField .= $char;
2200 2261
 
2201 2262
 
2202
-			}else{
2263
+			} else{
2203 2264
 				$selectField .= $char;
2204 2265
 			}
2205 2266
 
@@ -2218,18 +2279,19 @@  discard block
 block discarded – undo
2218 2279
 		if(strncasecmp($string, "DISTINCT ", 9) == 0) {
2219 2280
 			$string = substr($string, 9);
2220 2281
 		}
2221
-		if (stripos($string, " as ") !== false)
2222
-			//"as" used for an alias
2282
+		if (stripos($string, " as ") !== false) {
2283
+					//"as" used for an alias
2223 2284
 			return trim(substr($string, strripos($string, " as ") + 4));
2224
-		else if (strrpos($string, " ") != 0)
2225
-			//Space used as a delimiter for an alias
2285
+		} else if (strrpos($string, " ") != 0) {
2286
+					//Space used as a delimiter for an alias
2226 2287
 			return trim(substr($string, strrpos($string, " ")));
2227
-		else if (strpos($string, ".") !== false)
2228
-			//No alias, but a table.field format was used
2288
+		} else if (strpos($string, ".") !== false) {
2289
+					//No alias, but a table.field format was used
2229 2290
 			return substr($string, strpos($string, ".") + 1);
2230
-		else
2231
-			//Give up and assume the whole thing is the field name
2291
+		} else {
2292
+					//Give up and assume the whole thing is the field name
2232 2293
 			return $string;
2294
+		}
2233 2295
 	}
2234 2296
 
2235 2297
 	/**
@@ -2289,8 +2351,9 @@  discard block
 block discarded – undo
2289 2351
 			$aliases[$tableName][] = $table;
2290 2352
 
2291 2353
 			// build part of select for this table
2292
-			if (is_array($cols[$beanID]))
2293
-				foreach ($cols[$beanID] as $def) $select[] = $table.".".$def['name'];
2354
+			if (is_array($cols[$beanID])) {
2355
+							foreach ($cols[$beanID] as $def) $select[] = $table.".".$def['name'];
2356
+			}
2294 2357
 
2295 2358
 			// build part of where clause
2296 2359
 			if (is_array($whereClause[$beanID])){
@@ -2322,7 +2385,10 @@  discard block
 block discarded – undo
2322 2385
 		$separator = "";
2323 2386
 		$from = ''; $table_used_in_from = array();
2324 2387
 		foreach ($relations as $table1 => $rightsidearray){
2325
-			if ($table_used_in_from[$table1]) continue; // table has been joined
2388
+			if ($table_used_in_from[$table1]) {
2389
+			    continue;
2390
+			}
2391
+			// table has been joined
2326 2392
 
2327 2393
 			$from .= $separator." ".$table1;
2328 2394
 			$table_used_in_from[$table1] = true;
@@ -2333,7 +2399,9 @@  discard block
 block discarded – undo
2333 2399
 					//choose first alias that does not match
2334 2400
 					// we are doing this because of self joins.
2335 2401
 					// in case of self joins, the same table will have many aliases.
2336
-					if ($table2 != $table1) break;
2402
+					if ($table2 != $table1) {
2403
+					    break;
2404
+					}
2337 2405
 				}
2338 2406
 
2339 2407
 				$col = $tablearray['foreingColumn'];
@@ -2362,11 +2430,13 @@  discard block
 block discarded – undo
2362 2430
 		$tablename = $bean->getTableName();
2363 2431
 		$columns = array();
2364 2432
 		// get column names
2365
-		foreach ($fields as $fieldDef)
2366
-			$columns[] = $fieldDef['name'];
2433
+		foreach ($fields as $fieldDef) {
2434
+					$columns[] = $fieldDef['name'];
2435
+		}
2367 2436
 
2368
-		if (empty($columns))
2369
-			return "";
2437
+		if (empty($columns)) {
2438
+					return "";
2439
+		}
2370 2440
 
2371 2441
 		$columns = implode(",", $columns);
2372 2442
 
@@ -2386,16 +2456,21 @@  discard block
 block discarded – undo
2386 2456
 		// we do not have change a lot of existing code
2387 2457
 		// and add dbtype where type is being used for some special
2388 2458
 		// purposes like referring to foreign table etc.
2389
-		if(!empty($fieldDef['dbType']))
2390
-			return  $fieldDef['dbType'];
2391
-		if(!empty($fieldDef['dbtype']))
2392
-			return  $fieldDef['dbtype'];
2393
-		if (!empty($fieldDef['type']))
2394
-			return  $fieldDef['type'];
2395
-		if (!empty($fieldDef['Type']))
2396
-			return  $fieldDef['Type'];
2397
-		if (!empty($fieldDef['data_type']))
2398
-			return  $fieldDef['data_type'];
2459
+		if(!empty($fieldDef['dbType'])) {
2460
+					return  $fieldDef['dbType'];
2461
+		}
2462
+		if(!empty($fieldDef['dbtype'])) {
2463
+					return  $fieldDef['dbtype'];
2464
+		}
2465
+		if (!empty($fieldDef['type'])) {
2466
+					return  $fieldDef['type'];
2467
+		}
2468
+		if (!empty($fieldDef['Type'])) {
2469
+					return  $fieldDef['Type'];
2470
+		}
2471
+		if (!empty($fieldDef['data_type'])) {
2472
+					return  $fieldDef['data_type'];
2473
+		}
2399 2474
 
2400 2475
 		return null;
2401 2476
 	}
@@ -2453,14 +2528,15 @@  discard block
 block discarded – undo
2453 2528
                                           'clob', 'blob', 'text'))) {
2454 2529
           	    $colType = "$colBaseType(${fieldDef['len']})";
2455 2530
             } elseif(($colBaseType == 'decimal' || $colBaseType == 'float')){
2456
-                  if(!empty($fieldDef['precision']) && is_numeric($fieldDef['precision']))
2457
-                      if(strpos($fieldDef['len'],',') === false){
2531
+                  if(!empty($fieldDef['precision']) && is_numeric($fieldDef['precision'])) {
2532
+                                        if(strpos($fieldDef['len'],',') === false){
2458 2533
                           $colType = $colBaseType . "(".$fieldDef['len'].",".$fieldDef['precision'].")";
2459
-                      }else{
2460
-                          $colType = $colBaseType . "(".$fieldDef['len'].")";
2461
-                      }
2462
-                  else
2534
+                  }
2535
+                      } else{
2463 2536
                           $colType = $colBaseType . "(".$fieldDef['len'].")";
2537
+                      } else {
2538
+                                            $colType = $colBaseType . "(".$fieldDef['len'].")";
2539
+                  }
2464 2540
               }
2465 2541
         } else {
2466 2542
             if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char'))) {
@@ -2474,19 +2550,18 @@  discard block
 block discarded – undo
2474 2550
         if (!empty($fieldDef['no_default']))
2475 2551
         {
2476 2552
             // nothing to do
2477
-        }
2478
-        elseif (isset($fieldDef['default']) && strlen($fieldDef['default']) > 0)
2553
+        } elseif (isset($fieldDef['default']) && strlen($fieldDef['default']) > 0)
2479 2554
         {
2480 2555
             $default = " DEFAULT ".$this->quoted($fieldDef['default']);
2481
-        }
2482
-        elseif (!isset($default) && $type == 'bool')
2556
+        } elseif (!isset($default) && $type == 'bool')
2483 2557
         {
2484 2558
             $default = " DEFAULT 0 ";
2485 2559
         }
2486 2560
 
2487 2561
 		$auto_increment = '';
2488
-		if(!empty($fieldDef['auto_increment']) && $fieldDef['auto_increment'])
2489
-			$auto_increment = $this->setAutoIncrement($table , $fieldDef['name']);
2562
+		if(!empty($fieldDef['auto_increment']) && $fieldDef['auto_increment']) {
2563
+					$auto_increment = $this->setAutoIncrement($table , $fieldDef['name']);
2564
+		}
2490 2565
 
2491 2566
 		$required = 'NULL';  // MySQL defaults to NULL, SQL Server defaults to NOT NULL -- must specify
2492 2567
 		//Starting in 6.0, only ID and auto_increment fields will be NOT NULL in the DB.
@@ -2500,8 +2575,9 @@  discard block
 block discarded – undo
2500 2575
 			&& !empty($fieldDef['required'])) {
2501 2576
 			$required =  "NOT NULL";
2502 2577
 		}
2503
-		if ($ignoreRequired)
2504
-			$required = "";
2578
+		if ($ignoreRequired) {
2579
+					$required = "";
2580
+		}
2505 2581
 
2506 2582
 		if ( $return_as_array ) {
2507 2583
 			return array(
@@ -2537,8 +2613,7 @@  discard block
 block discarded – undo
2537 2613
 				}
2538 2614
 			}
2539 2615
 			$columns = implode(",", $columns);
2540
-		}
2541
-		else {
2616
+		} else {
2542 2617
 			$columns = $this->oneColumnSQLRep($fieldDefs,$ignoreRequired, $tablename);
2543 2618
 		}
2544 2619
 
@@ -2760,8 +2835,9 @@  discard block
 block discarded – undo
2760 2835
 	 */
2761 2836
 	public function isFieldArray($defArray)
2762 2837
 	{
2763
-		if ( !is_array($defArray) )
2764
-			return false;
2838
+		if ( !is_array($defArray) ) {
2839
+					return false;
2840
+		}
2765 2841
 
2766 2842
 		if ( isset($defArray['type']) ){
2767 2843
 			// type key exists. May be an array of defs or a simple definition
@@ -2872,11 +2948,9 @@  discard block
 block discarded – undo
2872 2948
                 } else {
2873 2949
                     if (isset($properties['dbType'])) {
2874 2950
                         $field_type=$properties['dbType'];
2875
-                    }
2876
-                    else if(isset($properties['data_type'])) {
2951
+                    } else if(isset($properties['data_type'])) {
2877 2952
                         $field_type=$properties['data_type'];
2878
-                    }
2879
-                    else {
2953
+                    } else {
2880 2954
                         $field_type=$properties['dbtype'];
2881 2955
                     }
2882 2956
                 }
@@ -2901,13 +2975,11 @@  discard block
 block discarded – undo
2901 2975
                             if ($error >= 0.0000000001) {    // Smaller than 10E-10
2902 2976
                                 $change = true;
2903 2977
                             }
2904
-                        }
2905
-                        else if ($this->isBooleanType($field_type)) {
2978
+                        } else if ($this->isBooleanType($field_type)) {
2906 2979
                             if ($this->_getBooleanValue($before_value) != $this->_getBooleanValue($after_value)) {
2907 2980
                                 $change = true;
2908 2981
                             }
2909
-                        }
2910
-                        else {
2982
+                        } else {
2911 2983
                             $change = true;
2912 2984
                         }
2913 2985
                         if ($change) {
@@ -3005,8 +3077,9 @@  discard block
 block discarded – undo
3005 3077
 	protected function _getBooleanValue($val)
3006 3078
 	{
3007 3079
 		//need to put the === sign here otherwise true == 'non empty string'
3008
-		if (empty($val) or $val==='off')
3009
-			return false;
3080
+		if (empty($val) or $val==='off') {
3081
+					return false;
3082
+		}
3010 3083
 
3011 3084
 		return true;
3012 3085
 	}
@@ -3032,8 +3105,9 @@  discard block
 block discarded – undo
3032 3105
      */
3033 3106
 	protected function _emptyValue($val, $type)
3034 3107
 	{
3035
-		if (empty($val))
3036
-			return true;
3108
+		if (empty($val)) {
3109
+					return true;
3110
+		}
3037 3111
 
3038 3112
 		if($this->emptyValue($type) == $val) {
3039 3113
 			return true;
@@ -3050,10 +3124,12 @@  discard block
 block discarded – undo
3050 3124
 			case 'short':
3051 3125
 				return ($val == 0);
3052 3126
 			case 'date':
3053
-				if ($val == '0000-00-00')
3054
-					return true;
3055
-				if ($val == 'NULL')
3056
-					return true;
3127
+				if ($val == '0000-00-00') {
3128
+									return true;
3129
+				}
3130
+				if ($val == 'NULL') {
3131
+									return true;
3132
+				}
3057 3133
 				return false;
3058 3134
 		}
3059 3135
 
@@ -3407,7 +3483,9 @@  discard block
 block discarded – undo
3407 3483
 	 */
3408 3484
 	public function fetchByAssoc($result, $encode = true)
3409 3485
 	{
3410
-	    if (empty($result))	return false;
3486
+	    if (empty($result)) {
3487
+	        return false;
3488
+	    }
3411 3489
 
3412 3490
 	    if(is_int($encode) && func_num_args() == 3) {
3413 3491
 	        // old API: $result, $rowNum, $encode
Please login to merge, or discard this patch.
Indentation   +3274 added lines, -3274 removed lines patch added patch discarded remove patch
@@ -97,389 +97,389 @@  discard block
 block discarded – undo
97 97
  */
98 98
 abstract class DBManager
99 99
 {
100
-	/**
101
-	 * Name of database
102
-	 * @var resource
103
-	 */
104
-	public $database = null;
105
-
106
-	/**
107
-	 * Indicates whether we should die when we get an error from the DB
108
-	 */
109
-	protected $dieOnError = false;
110
-
111
-	/**
112
-	 * Indicates whether we should html encode the results from a query by default
113
-	 */
114
-	protected $encode = true;
115
-
116
-	/**
117
-	 * Records the execution time of the last query
118
-	 */
119
-	protected $query_time = 0;
120
-
121
-	/**
122
-	 * Last error message from the DB backend
123
-	 */
124
-	protected $last_error = false;
125
-
126
-	/**
127
-	 * Registry of available result sets
128
-	 */
129
-	protected $lastResult;
130
-
131
-	/**
132
-	 * Current query count
133
-	 */
134
-	private static $queryCount = 0;
135
-
136
-	/**
137
-	 * Query threshold limit
138
-	 */
139
-	private static $queryLimit = 0;
140
-
141
-	/**
142
-	 * Array of prepared statements and their correspoding parsed tokens
143
-	 */
144
-	protected $preparedTokens = array();
145
-
146
-	/**
147
-	 * TimeDate instance
148
-	 * @var TimeDate
149
-	 */
150
-	protected $timedate;
151
-
152
-	/**
153
-	 * PHP Logger
154
-	 * @var Logger
155
-	 */
156
-	protected $log;
157
-
158
-	/**
159
-	 * Table descriptions
160
-	 * @var array
161
-	 */
162
-	protected static $table_descriptions = array();
163
-
164
-	/**
165
-	 * Index descriptions
166
-	 * @var array
167
-	 */
168
-	protected static $index_descriptions = array();
169
-
170
-	/**
171
-	 * Maximum length of identifiers
172
-	 * @abstract
173
-	 * @var array
174
-	 */
175
-	protected $maxNameLengths = array(
176
-		'table' => 64,
177
-		'column' => 64,
178
-		'index' => 64,
179
-		'alias' => 64
180
-	);
181
-
182
-	/**
183
-	 * DB driver priority
184
-	 * Higher priority drivers override lower priority ones
185
-	 * @var int
186
-	 */
187
-	public $priority = 0;
188
-
189
-	/**
190
-	 * Driver name label, for install
191
-	 * @absrtact
192
-	 * @var string
193
-	 */
194
-	public $label = '';
195
-
196
-	/**
197
-	 * Type names map
198
-	 * @abstract
199
-	 * @var array
200
-	 */
201
-	protected $type_map = array();
202
-
203
-	/**
204
-	 * Type classification into:
205
-	 * - int
206
-	 * - bool
207
-	 * - float
208
-	 * - date
209
-	 * @abstract
210
-	 * @var array
211
-	 */
212
-	protected $type_class = array(
213
-			'int'      => 'int',
214
-			'double'   => 'float',
215
-			'float'    => 'float',
216
-			'uint'     => 'int',
217
-			'ulong'    => 'bigint',
218
-			'long'     => 'bigint',
219
-			'short'    => 'int',
220
-			'date'     => 'date',
221
-			'datetime' => 'date',
222
-			'datetimecombo' => 'date',
223
-			'time'     => 'time',
224
-			'bool'     => 'bool',
225
-			'tinyint'  => 'int',
226
-			'currency' => 'float',
227
-			'decimal'  => 'float',
228
-			'decimal2' => 'float',
229
-	);
230
-
231
-	/**
232
-	 * Capabilities this DB supports. Supported list:
233
-	 * affected_rows	Can report query affected rows for UPDATE/DELETE
234
-	 * 					implement getAffectedRowCount()
235
-	 * select_rows		Can report row count for SELECT
236
-	 * 					implement getRowCount()
237
-	 * case_sensitive	Supports case-sensitive text columns
238
-	 * fulltext			Supports fulltext search indexes
239
-	 * inline_keys		Supports defining keys together with the table
240
-	 * auto_increment_sequence Autoincrement support implemented as sequence
241
-	 * limit_subquery   Supports LIMIT clauses in subqueries
242
-	 * create_user		Can create users for Sugar
243
-	 * create_db		Can create databases
244
-	 * collation		Supports setting collations
245
-	 * disable_keys     Supports temporarily disabling keys (for upgrades, etc.)
246
-	 *
247
-	 * @abstract
248
-	 * Special cases:
249
-	 * fix:expandDatabase - needs expandDatabase fix, see expandDatabase.php
250
-	 * TODO: verify if we need these cases
251
-	 */
252
-	protected $capabilities = array();
253
-
254
-	/**
255
-	 * Database options
256
-	 * @var array
257
-	 */
258
-	protected $options = array();
100
+    /**
101
+     * Name of database
102
+     * @var resource
103
+     */
104
+    public $database = null;
105
+
106
+    /**
107
+     * Indicates whether we should die when we get an error from the DB
108
+     */
109
+    protected $dieOnError = false;
110
+
111
+    /**
112
+     * Indicates whether we should html encode the results from a query by default
113
+     */
114
+    protected $encode = true;
115
+
116
+    /**
117
+     * Records the execution time of the last query
118
+     */
119
+    protected $query_time = 0;
120
+
121
+    /**
122
+     * Last error message from the DB backend
123
+     */
124
+    protected $last_error = false;
125
+
126
+    /**
127
+     * Registry of available result sets
128
+     */
129
+    protected $lastResult;
130
+
131
+    /**
132
+     * Current query count
133
+     */
134
+    private static $queryCount = 0;
135
+
136
+    /**
137
+     * Query threshold limit
138
+     */
139
+    private static $queryLimit = 0;
140
+
141
+    /**
142
+     * Array of prepared statements and their correspoding parsed tokens
143
+     */
144
+    protected $preparedTokens = array();
145
+
146
+    /**
147
+     * TimeDate instance
148
+     * @var TimeDate
149
+     */
150
+    protected $timedate;
151
+
152
+    /**
153
+     * PHP Logger
154
+     * @var Logger
155
+     */
156
+    protected $log;
157
+
158
+    /**
159
+     * Table descriptions
160
+     * @var array
161
+     */
162
+    protected static $table_descriptions = array();
163
+
164
+    /**
165
+     * Index descriptions
166
+     * @var array
167
+     */
168
+    protected static $index_descriptions = array();
169
+
170
+    /**
171
+     * Maximum length of identifiers
172
+     * @abstract
173
+     * @var array
174
+     */
175
+    protected $maxNameLengths = array(
176
+        'table' => 64,
177
+        'column' => 64,
178
+        'index' => 64,
179
+        'alias' => 64
180
+    );
181
+
182
+    /**
183
+     * DB driver priority
184
+     * Higher priority drivers override lower priority ones
185
+     * @var int
186
+     */
187
+    public $priority = 0;
188
+
189
+    /**
190
+     * Driver name label, for install
191
+     * @absrtact
192
+     * @var string
193
+     */
194
+    public $label = '';
195
+
196
+    /**
197
+     * Type names map
198
+     * @abstract
199
+     * @var array
200
+     */
201
+    protected $type_map = array();
202
+
203
+    /**
204
+     * Type classification into:
205
+     * - int
206
+     * - bool
207
+     * - float
208
+     * - date
209
+     * @abstract
210
+     * @var array
211
+     */
212
+    protected $type_class = array(
213
+            'int'      => 'int',
214
+            'double'   => 'float',
215
+            'float'    => 'float',
216
+            'uint'     => 'int',
217
+            'ulong'    => 'bigint',
218
+            'long'     => 'bigint',
219
+            'short'    => 'int',
220
+            'date'     => 'date',
221
+            'datetime' => 'date',
222
+            'datetimecombo' => 'date',
223
+            'time'     => 'time',
224
+            'bool'     => 'bool',
225
+            'tinyint'  => 'int',
226
+            'currency' => 'float',
227
+            'decimal'  => 'float',
228
+            'decimal2' => 'float',
229
+    );
230
+
231
+    /**
232
+     * Capabilities this DB supports. Supported list:
233
+     * affected_rows	Can report query affected rows for UPDATE/DELETE
234
+     * 					implement getAffectedRowCount()
235
+     * select_rows		Can report row count for SELECT
236
+     * 					implement getRowCount()
237
+     * case_sensitive	Supports case-sensitive text columns
238
+     * fulltext			Supports fulltext search indexes
239
+     * inline_keys		Supports defining keys together with the table
240
+     * auto_increment_sequence Autoincrement support implemented as sequence
241
+     * limit_subquery   Supports LIMIT clauses in subqueries
242
+     * create_user		Can create users for Sugar
243
+     * create_db		Can create databases
244
+     * collation		Supports setting collations
245
+     * disable_keys     Supports temporarily disabling keys (for upgrades, etc.)
246
+     *
247
+     * @abstract
248
+     * Special cases:
249
+     * fix:expandDatabase - needs expandDatabase fix, see expandDatabase.php
250
+     * TODO: verify if we need these cases
251
+     */
252
+    protected $capabilities = array();
253
+
254
+    /**
255
+     * Database options
256
+     * @var array
257
+     */
258
+    protected $options = array();
259 259
 
260 260
     /**
261 261
      * Create DB Driver
262 262
      */
263
-	public function __construct()
264
-	{
265
-		$this->timedate = TimeDate::getInstance();
266
-		$this->log = isset($GLOBALS['log']) ? $GLOBALS['log'] : null;
267
-		$this->helper = $this; // compatibility
268
-	}
263
+    public function __construct()
264
+    {
265
+        $this->timedate = TimeDate::getInstance();
266
+        $this->log = isset($GLOBALS['log']) ? $GLOBALS['log'] : null;
267
+        $this->helper = $this; // compatibility
268
+    }
269 269
 
270 270
     /**
271 271
      * Wrapper for those trying to access the private and protected class members directly
272 272
      * @param string $p var name
273 273
      * @return mixed
274 274
      */
275
-	public function __get($p)
276
-	{
277
-		$this->log->info('Call to DBManager::$'.$p.' is deprecated');
278
-		return $this->$p;
279
-	}
280
-
281
-	/**
282
-	 * Returns the current database handle
283
-	 * @return resource
284
-	 */
285
-	public function getDatabase()
286
-	{
287
-		$this->checkConnection();
288
-		return $this->database;
289
-	}
290
-
291
-	/**
292
-	 * Returns this instance's DBHelper
293
-	 * Actually now returns $this
294
-	 * @deprecated
295
-	 * @return DBManager
296
-	 */
297
-	public function getHelper()
298
-	{
299
-		return $this;
300
-	}
301
-
302
-	/**
303
-	 * Checks for error happening in the database
304
-	 *
305
-	 * @param  string $msg        message to prepend to the error message
306
-	 * @param  bool   $dieOnError true if we want to die immediately on error
307
-	 * @return bool True if there was an error
308
-	 */
309
-	public function checkError($msg = '', $dieOnError = false)
310
-	{
311
-		if (empty($this->database)) {
312
-			$this->registerError($msg, "Database Is Not Connected", $dieOnError);
313
-			return true;
314
-		}
315
-
316
-		$dberror = $this->lastDbError();
317
-		if($dberror === false) {
318
-    		$this->last_error = false;
319
-	    	return false;
320
-		}
321
-		$this->registerError($msg, $dberror, $dieOnError);
275
+    public function __get($p)
276
+    {
277
+        $this->log->info('Call to DBManager::$'.$p.' is deprecated');
278
+        return $this->$p;
279
+    }
280
+
281
+    /**
282
+     * Returns the current database handle
283
+     * @return resource
284
+     */
285
+    public function getDatabase()
286
+    {
287
+        $this->checkConnection();
288
+        return $this->database;
289
+    }
290
+
291
+    /**
292
+     * Returns this instance's DBHelper
293
+     * Actually now returns $this
294
+     * @deprecated
295
+     * @return DBManager
296
+     */
297
+    public function getHelper()
298
+    {
299
+        return $this;
300
+    }
301
+
302
+    /**
303
+     * Checks for error happening in the database
304
+     *
305
+     * @param  string $msg        message to prepend to the error message
306
+     * @param  bool   $dieOnError true if we want to die immediately on error
307
+     * @return bool True if there was an error
308
+     */
309
+    public function checkError($msg = '', $dieOnError = false)
310
+    {
311
+        if (empty($this->database)) {
312
+            $this->registerError($msg, "Database Is Not Connected", $dieOnError);
313
+            return true;
314
+        }
315
+
316
+        $dberror = $this->lastDbError();
317
+        if($dberror === false) {
318
+            $this->last_error = false;
319
+            return false;
320
+        }
321
+        $this->registerError($msg, $dberror, $dieOnError);
322 322
         return true;
323
-	}
324
-
325
-	/**
326
-	 * Register database error
327
-	 * If die-on-error flag is set, logs the message and dies,
328
-	 * otherwise sets last_error to the message
329
-	 * @param string $userMessage Message from function user
330
-	 * @param string $message Message from SQL driver
331
-	 * @param bool $dieOnError
332
-	 */
333
-	protected function registerError($userMessage, $message, $dieOnError = false)
334
-	{
335
-		if(!empty($message)) {
336
-			if(!empty($userMessage)) {
337
-				$message = "$userMessage: $message";
338
-			}
339
-			if(empty($message)) {
340
-			    $message = "Database error";
341
-			}
342
-			$this->log->fatal($message);
343
-			if ($dieOnError || $this->dieOnError) {
344
-				if(isset($GLOBALS['app_strings']['ERR_DB_FAIL'])) {
345
-					sugar_die($GLOBALS['app_strings']['ERR_DB_FAIL']);
346
-				} else {
347
-					sugar_die("Database error. Please check suitecrm.log for details.");
348
-				}
349
-			} else {
350
-				$this->last_error = $message;
351
-			}
352
-		}
353
-	}
354
-
355
-	/**
356
-	 * Return DB error message for the last query executed
357
-	 * @return string Last error message
358
-	 */
359
-	public function lastError()
360
-	{
361
-		return $this->last_error;
362
-	}
363
-
364
-	/**
365
-	 * This method is called by every method that runs a query.
366
-	 * If slow query dumping is turned on and the query time is beyond
367
-	 * the time limit, we will log the query. This function may do
368
-	 * additional reporting or log in a different area in the future.
369
-	 *
370
-	 * @param  string  $query query to log
371
-	 * @return boolean true if the query was logged, false otherwise
372
-	 */
373
-	protected function dump_slow_queries($query)
374
-	{
375
-		global $sugar_config;
376
-
377
-		$do_the_dump = isset($sugar_config['dump_slow_queries'])
378
-			? $sugar_config['dump_slow_queries'] : false;
379
-		$slow_query_time_msec = isset($sugar_config['slow_query_time_msec'])
380
-			? $sugar_config['slow_query_time_msec'] : 5000;
381
-
382
-		if($do_the_dump) {
383
-			if($slow_query_time_msec < ($this->query_time * 1000)) {
384
-				// Then log both the query and the query time
385
-				$this->log->fatal('Slow Query (time:'.$this->query_time."\n".$query);
386
-				return true;
387
-			}
388
-		}
389
-		return false;
390
-	}
323
+    }
324
+
325
+    /**
326
+     * Register database error
327
+     * If die-on-error flag is set, logs the message and dies,
328
+     * otherwise sets last_error to the message
329
+     * @param string $userMessage Message from function user
330
+     * @param string $message Message from SQL driver
331
+     * @param bool $dieOnError
332
+     */
333
+    protected function registerError($userMessage, $message, $dieOnError = false)
334
+    {
335
+        if(!empty($message)) {
336
+            if(!empty($userMessage)) {
337
+                $message = "$userMessage: $message";
338
+            }
339
+            if(empty($message)) {
340
+                $message = "Database error";
341
+            }
342
+            $this->log->fatal($message);
343
+            if ($dieOnError || $this->dieOnError) {
344
+                if(isset($GLOBALS['app_strings']['ERR_DB_FAIL'])) {
345
+                    sugar_die($GLOBALS['app_strings']['ERR_DB_FAIL']);
346
+                } else {
347
+                    sugar_die("Database error. Please check suitecrm.log for details.");
348
+                }
349
+            } else {
350
+                $this->last_error = $message;
351
+            }
352
+        }
353
+    }
354
+
355
+    /**
356
+     * Return DB error message for the last query executed
357
+     * @return string Last error message
358
+     */
359
+    public function lastError()
360
+    {
361
+        return $this->last_error;
362
+    }
363
+
364
+    /**
365
+     * This method is called by every method that runs a query.
366
+     * If slow query dumping is turned on and the query time is beyond
367
+     * the time limit, we will log the query. This function may do
368
+     * additional reporting or log in a different area in the future.
369
+     *
370
+     * @param  string  $query query to log
371
+     * @return boolean true if the query was logged, false otherwise
372
+     */
373
+    protected function dump_slow_queries($query)
374
+    {
375
+        global $sugar_config;
376
+
377
+        $do_the_dump = isset($sugar_config['dump_slow_queries'])
378
+            ? $sugar_config['dump_slow_queries'] : false;
379
+        $slow_query_time_msec = isset($sugar_config['slow_query_time_msec'])
380
+            ? $sugar_config['slow_query_time_msec'] : 5000;
381
+
382
+        if($do_the_dump) {
383
+            if($slow_query_time_msec < ($this->query_time * 1000)) {
384
+                // Then log both the query and the query time
385
+                $this->log->fatal('Slow Query (time:'.$this->query_time."\n".$query);
386
+                return true;
387
+            }
388
+        }
389
+        return false;
390
+    }
391 391
 
392 392
 /**
393
-	* Scans order by to ensure that any field being ordered by is.
394
-	*
395
-	* It will throw a warning error to the log file - fatal if slow query logging is enabled
396
-	*
397
-	* @param  string $sql         query to be run
398
-	* @param  bool   $object_name optional, object to look up indices in
399
-	* @return bool   true if an index is found false otherwise
400
-	*/
393
+ * Scans order by to ensure that any field being ordered by is.
394
+ *
395
+ * It will throw a warning error to the log file - fatal if slow query logging is enabled
396
+ *
397
+ * @param  string $sql         query to be run
398
+ * @param  bool   $object_name optional, object to look up indices in
399
+ * @return bool   true if an index is found false otherwise
400
+ */
401 401
 protected function checkQuery($sql, $object_name = false)
402 402
 {
403
-	$match = array();
404
-	preg_match_all("'.* FROM ([^ ]*).* ORDER BY (.*)'is", $sql, $match);
405
-	$indices = false;
406
-	if (!empty($match[1][0]))
407
-		$table = $match[1][0];
408
-	else
409
-		return false;
410
-
411
-	if (!empty($object_name) && !empty($GLOBALS['dictionary'][$object_name]))
412
-		$indices = $GLOBALS['dictionary'][$object_name]['indices'];
413
-
414
-	if (empty($indices)) {
415
-		foreach ( $GLOBALS['dictionary'] as $current ) {
416
-			if ($current['table'] == $table){
417
-				$indices = $current['indices'];
418
-				break;
419
-			}
420
-		}
421
-	}
422
-	if (empty($indices)) {
423
-		$this->log->warn('CHECK QUERY: Could not find index definitions for table ' . $table);
424
-		return false;
425
-	}
426
-	if (!empty($match[2][0])) {
427
-		$orderBys = explode(' ', $match[2][0]);
428
-		foreach ($orderBys as $orderBy){
429
-			$orderBy = trim($orderBy);
430
-			if (empty($orderBy))
431
-				continue;
432
-			$orderBy = strtolower($orderBy);
433
-			if ($orderBy == 'asc' || $orderBy == 'desc')
434
-				continue;
435
-
436
-			$orderBy = str_replace(array($table . '.', ','), '', $orderBy);
437
-
438
-			foreach ($indices as $index)
439
-				if (empty($index['db']) || $index['db'] == $this->dbType)
440
-					foreach ($index['fields'] as $field)
441
-						if ($field == $orderBy)
442
-							return true;
443
-
444
-			$warning = 'Missing Index For Order By Table: ' . $table . ' Order By:' . $orderBy ;
445
-			if (!empty($GLOBALS['sugar_config']['dump_slow_queries']))
446
-				$this->log->fatal('CHECK QUERY:' .$warning);
447
-			else
448
-				$this->log->warn('CHECK QUERY:' .$warning);
449
-		}
450
-	}
451
-	return false;
452
-	}
453
-
454
-	/**
455
-	 * Returns the time the last query took to execute
456
-	 *
457
-	 * @return int
458
-	 */
459
-	public function getQueryTime()
460
-	{
461
-		return $this->query_time;
462
-	}
463
-
464
-	/**
465
-	 * Checks the current connection; if it is not connected then reconnect
466
-	 */
467
-	public function checkConnection()
468
-	{
469
-		$this->last_error = '';
470
-		if (!isset($this->database))
471
-			$this->connect();
472
-	}
473
-
474
-	/**
475
-	 * Sets the dieOnError value
476
-	 *
477
-	 * @param bool $value
478
-	 */
479
-	public function setDieOnError($value)
480
-	{
481
-		$this->dieOnError = $value;
482
-	}
403
+    $match = array();
404
+    preg_match_all("'.* FROM ([^ ]*).* ORDER BY (.*)'is", $sql, $match);
405
+    $indices = false;
406
+    if (!empty($match[1][0]))
407
+        $table = $match[1][0];
408
+    else
409
+        return false;
410
+
411
+    if (!empty($object_name) && !empty($GLOBALS['dictionary'][$object_name]))
412
+        $indices = $GLOBALS['dictionary'][$object_name]['indices'];
413
+
414
+    if (empty($indices)) {
415
+        foreach ( $GLOBALS['dictionary'] as $current ) {
416
+            if ($current['table'] == $table){
417
+                $indices = $current['indices'];
418
+                break;
419
+            }
420
+        }
421
+    }
422
+    if (empty($indices)) {
423
+        $this->log->warn('CHECK QUERY: Could not find index definitions for table ' . $table);
424
+        return false;
425
+    }
426
+    if (!empty($match[2][0])) {
427
+        $orderBys = explode(' ', $match[2][0]);
428
+        foreach ($orderBys as $orderBy){
429
+            $orderBy = trim($orderBy);
430
+            if (empty($orderBy))
431
+                continue;
432
+            $orderBy = strtolower($orderBy);
433
+            if ($orderBy == 'asc' || $orderBy == 'desc')
434
+                continue;
435
+
436
+            $orderBy = str_replace(array($table . '.', ','), '', $orderBy);
437
+
438
+            foreach ($indices as $index)
439
+                if (empty($index['db']) || $index['db'] == $this->dbType)
440
+                    foreach ($index['fields'] as $field)
441
+                        if ($field == $orderBy)
442
+                            return true;
443
+
444
+            $warning = 'Missing Index For Order By Table: ' . $table . ' Order By:' . $orderBy ;
445
+            if (!empty($GLOBALS['sugar_config']['dump_slow_queries']))
446
+                $this->log->fatal('CHECK QUERY:' .$warning);
447
+            else
448
+                $this->log->warn('CHECK QUERY:' .$warning);
449
+        }
450
+    }
451
+    return false;
452
+    }
453
+
454
+    /**
455
+     * Returns the time the last query took to execute
456
+     *
457
+     * @return int
458
+     */
459
+    public function getQueryTime()
460
+    {
461
+        return $this->query_time;
462
+    }
463
+
464
+    /**
465
+     * Checks the current connection; if it is not connected then reconnect
466
+     */
467
+    public function checkConnection()
468
+    {
469
+        $this->last_error = '';
470
+        if (!isset($this->database))
471
+            $this->connect();
472
+    }
473
+
474
+    /**
475
+     * Sets the dieOnError value
476
+     *
477
+     * @param bool $value
478
+     */
479
+    public function setDieOnError($value)
480
+    {
481
+        $this->dieOnError = $value;
482
+    }
483 483
 
484 484
     /**
485 485
      * Implements a generic insert for any bean.
@@ -488,67 +488,67 @@  discard block
 block discarded – undo
488 488
      * @return bool query result
489 489
      *
490 490
      */
491
-	public function insert(SugarBean $bean)
492
-	{
493
-		$sql = $this->insertSQL($bean);
494
-		$tablename =  $bean->getTableName();
495
-		$msg = "Error inserting into table: $tablename:";
496
-		return $this->query($sql,true,$msg);
497
-	}
498
-
499
-	/**
500
-	 * Insert data into table by parameter definition
501
-	 * @param string $table Table name
502
-	 * @param array $field_defs Definitions in vardef-like format
503
-	 * @param array $data Key/value to insert
504
-	 * @param array $field_map Fields map from SugarBean
505
-	 * @param bool $execute Execute or return query?
491
+    public function insert(SugarBean $bean)
492
+    {
493
+        $sql = $this->insertSQL($bean);
494
+        $tablename =  $bean->getTableName();
495
+        $msg = "Error inserting into table: $tablename:";
496
+        return $this->query($sql,true,$msg);
497
+    }
498
+
499
+    /**
500
+     * Insert data into table by parameter definition
501
+     * @param string $table Table name
502
+     * @param array $field_defs Definitions in vardef-like format
503
+     * @param array $data Key/value to insert
504
+     * @param array $field_map Fields map from SugarBean
505
+     * @param bool $execute Execute or return query?
506 506
      * @return bool query result
507 507
      */
508
-	public function insertParams($table, $field_defs, $data, $field_map = null, $execute = true)
509
-	{
510
-		$values = array();
511
-		foreach ($field_defs as $field => $fieldDef)
512
-		{
513
-			if (isset($fieldDef['source']) && $fieldDef['source'] != 'db')  continue;
514
-			//custom fields handle there save seperatley
515
-			if(!empty($field_map) && !empty($field_map[$field]['custom_type'])) continue;
516
-
517
-			if(isset($data[$field])) {
518
-				// clean the incoming value..
519
-				$val = from_html($data[$field]);
520
-			} else {
521
-				if(isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) {
522
-					$val = $fieldDef['default'];
523
-				} else {
524
-					$val = null;
525
-				}
526
-			}
527
-
528
-			//handle auto increment values here - we may have to do something like nextval for oracle
529
-			if (!empty($fieldDef['auto_increment'])) {
530
-				$auto = $this->getAutoIncrementSQL($table, $fieldDef['name']);
531
-				if(!empty($auto)) {
532
-					$values[$field] = $auto;
533
-				}
534
-			} elseif ($fieldDef['name'] == 'deleted') {
535
-				$values['deleted'] = (int)$val;
536
-			} else {
537
-				// need to do some thing about types of values
538
-				if(!is_null($val) || !empty($fieldDef['required'])) {
539
-					$values[$field] = $this->massageValue($val, $fieldDef);
540
-				}
541
-			}
542
-		}
543
-
544
-		if (empty($values))
545
-			return $execute?true:''; // no columns set
546
-
547
-		// get the entire sql
548
-		$query = "INSERT INTO $table (".implode(",", array_keys($values)).")
508
+    public function insertParams($table, $field_defs, $data, $field_map = null, $execute = true)
509
+    {
510
+        $values = array();
511
+        foreach ($field_defs as $field => $fieldDef)
512
+        {
513
+            if (isset($fieldDef['source']) && $fieldDef['source'] != 'db')  continue;
514
+            //custom fields handle there save seperatley
515
+            if(!empty($field_map) && !empty($field_map[$field]['custom_type'])) continue;
516
+
517
+            if(isset($data[$field])) {
518
+                // clean the incoming value..
519
+                $val = from_html($data[$field]);
520
+            } else {
521
+                if(isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) {
522
+                    $val = $fieldDef['default'];
523
+                } else {
524
+                    $val = null;
525
+                }
526
+            }
527
+
528
+            //handle auto increment values here - we may have to do something like nextval for oracle
529
+            if (!empty($fieldDef['auto_increment'])) {
530
+                $auto = $this->getAutoIncrementSQL($table, $fieldDef['name']);
531
+                if(!empty($auto)) {
532
+                    $values[$field] = $auto;
533
+                }
534
+            } elseif ($fieldDef['name'] == 'deleted') {
535
+                $values['deleted'] = (int)$val;
536
+            } else {
537
+                // need to do some thing about types of values
538
+                if(!is_null($val) || !empty($fieldDef['required'])) {
539
+                    $values[$field] = $this->massageValue($val, $fieldDef);
540
+                }
541
+            }
542
+        }
543
+
544
+        if (empty($values))
545
+            return $execute?true:''; // no columns set
546
+
547
+        // get the entire sql
548
+        $query = "INSERT INTO $table (".implode(",", array_keys($values)).")
549 549
 					VALUES (".implode(",", $values).")";
550
-		return $execute?$this->query($query):$query;
551
-	}
550
+        return $execute?$this->query($query):$query;
551
+    }
552 552
 
553 553
     /**
554 554
      * Implements a generic update for any bean
@@ -560,13 +560,13 @@  discard block
 block discarded – undo
560 560
      * @return bool query result
561 561
      *
562 562
      */
563
-	public function update(SugarBean $bean, array $where = array())
564
-	{
565
-		$sql = $this->updateSQL($bean, $where);
566
-		$tablename = $bean->getTableName();
567
-		$msg = "Error updating table: $tablename:";
568
-		return $this->query($sql,true,$msg);
569
-	}
563
+    public function update(SugarBean $bean, array $where = array())
564
+    {
565
+        $sql = $this->updateSQL($bean, $where);
566
+        $tablename = $bean->getTableName();
567
+        $msg = "Error updating table: $tablename:";
568
+        return $this->query($sql,true,$msg);
569
+    }
570 570
 
571 571
     /**
572 572
      * Implements a generic delete for any bean identified by id
@@ -577,215 +577,215 @@  discard block
 block discarded – undo
577 577
      * If where is not passed, it defaults to id of table
578 578
      * @return bool query result
579 579
      */
580
-	public function delete(SugarBean $bean, array $where = array())
581
-	{
582
-		$sql = $this->deleteSQL($bean, $where);
583
-		$tableName = $bean->getTableName();
584
-		$msg = "Error deleting from table: ".$tableName. ":";
585
-		return $this->query($sql,true,$msg);
586
-	}
587
-
588
-	/**
589
-	 * Implements a generic retrieve for any bean identified by id
590
-	 *
591
-	 * If we want to pass multiple values for a name, pass it as an array
592
-	 * If where is not passed, it defaults to id of table
593
-	 *
594
-	 * @param  SugarBean   $bean  Sugarbean instance
595
-	 * @param  array    $where values with the keys as names of fields.
596
-	 * @return resource result from the query
597
-	 */
598
-	public function retrieve(SugarBean $bean, array $where = array())
599
-	{
600
-		$sql = $this->retrieveSQL($bean, $where);
601
-		$tableName = $bean->getTableName();
602
-		$msg = "Error retriving values from table:".$tableName. ":";
603
-		return $this->query($sql,true,$msg);
604
-	}
605
-
606
-	/**
607
-	 * Implements a generic retrieve for a collection of beans.
608
-	 *
609
-	 * These beans will be joined in the sql by the key attribute of field defs.
610
-	 * Currently, this function does support outer joins.
611
-	 *
612
-	 * @param  array $beans Sugarbean instance(s)
613
-	 * @param  array $cols  columns to be returned with the keys as names of bean as identified by
614
-	 * get_class of bean. Values of this array is the array of fieldDefs to be returned for a bean.
615
-	 * If an empty array is passed, all columns are selected.
616
-	 * @param  array $where  values with the keys as names of bean as identified by get_class of bean
617
-	 * Each value at the first level is an array of values for that bean identified by name of fields.
618
-	 * If we want to pass multiple values for a name, pass it as an array
619
-	 * If where is not passed, all the rows will be returned.
620
-	 * @return resource
621
-	 */
622
-	public function retrieveView(array $beans, array $cols = array(), array $where = array())
623
-	{
624
-		$sql = $this->retrieveViewSQL($beans, $cols, $where);
625
-		$msg = "Error retriving values from View Collection:";
626
-		return $this->query($sql,true,$msg);
627
-	}
628
-
629
-
630
-	/**
631
-	 * Implements creation of a db table for a bean.
632
-	 *
633
-	 * NOTE: does not handle out-of-table constraints, use createConstraintSQL for that
634
-	 * @param SugarBean $bean  Sugarbean instance
635
-	 */
636
-	public function createTable(SugarBean $bean)
637
-	{
638
-		$sql = $this->createTableSQL($bean);
639
-		$tablename = $bean->getTableName();
640
-		$msg = "Error creating table: $tablename:";
641
-		$this->query($sql,true,$msg);
642
-		if(!$this->supports("inline_keys")) {
643
-		// handle constraints and indices
644
-			$indicesArr = $this->createConstraintSql($bean);
645
-			if (count($indicesArr) > 0)
646
-				foreach ($indicesArr as $indexSql)
647
-					$this->query($indexSql, true, $msg);
648
-		}
649
-	}
650
-
651
-	/**
652
-	 * returns SQL to create constraints or indices
653
-	 *
654
-	 * @param  SugarBean $bean SugarBean instance
655
-	 * @return array list of SQL statements
656
-	 */
657
-	protected function createConstraintSql(SugarBean $bean)
658
-	{
659
-		return $this->getConstraintSql($bean->getIndices(), $bean->getTableName());
660
-	}
661
-
662
-	/**
663
-	 * Implements creation of a db table
664
-	 *
665
-	 * @param string $tablename
666
-	 * @param array  $fieldDefs  Field definitions, in vardef format
667
-	 * @param array  $indices    Index definitions, in vardef format
668
-	 * @param string $engine    Engine parameter, used for MySQL engine so far
580
+    public function delete(SugarBean $bean, array $where = array())
581
+    {
582
+        $sql = $this->deleteSQL($bean, $where);
583
+        $tableName = $bean->getTableName();
584
+        $msg = "Error deleting from table: ".$tableName. ":";
585
+        return $this->query($sql,true,$msg);
586
+    }
587
+
588
+    /**
589
+     * Implements a generic retrieve for any bean identified by id
590
+     *
591
+     * If we want to pass multiple values for a name, pass it as an array
592
+     * If where is not passed, it defaults to id of table
593
+     *
594
+     * @param  SugarBean   $bean  Sugarbean instance
595
+     * @param  array    $where values with the keys as names of fields.
596
+     * @return resource result from the query
597
+     */
598
+    public function retrieve(SugarBean $bean, array $where = array())
599
+    {
600
+        $sql = $this->retrieveSQL($bean, $where);
601
+        $tableName = $bean->getTableName();
602
+        $msg = "Error retriving values from table:".$tableName. ":";
603
+        return $this->query($sql,true,$msg);
604
+    }
605
+
606
+    /**
607
+     * Implements a generic retrieve for a collection of beans.
608
+     *
609
+     * These beans will be joined in the sql by the key attribute of field defs.
610
+     * Currently, this function does support outer joins.
611
+     *
612
+     * @param  array $beans Sugarbean instance(s)
613
+     * @param  array $cols  columns to be returned with the keys as names of bean as identified by
614
+     * get_class of bean. Values of this array is the array of fieldDefs to be returned for a bean.
615
+     * If an empty array is passed, all columns are selected.
616
+     * @param  array $where  values with the keys as names of bean as identified by get_class of bean
617
+     * Each value at the first level is an array of values for that bean identified by name of fields.
618
+     * If we want to pass multiple values for a name, pass it as an array
619
+     * If where is not passed, all the rows will be returned.
620
+     * @return resource
621
+     */
622
+    public function retrieveView(array $beans, array $cols = array(), array $where = array())
623
+    {
624
+        $sql = $this->retrieveViewSQL($beans, $cols, $where);
625
+        $msg = "Error retriving values from View Collection:";
626
+        return $this->query($sql,true,$msg);
627
+    }
628
+
629
+
630
+    /**
631
+     * Implements creation of a db table for a bean.
632
+     *
633
+     * NOTE: does not handle out-of-table constraints, use createConstraintSQL for that
634
+     * @param SugarBean $bean  Sugarbean instance
635
+     */
636
+    public function createTable(SugarBean $bean)
637
+    {
638
+        $sql = $this->createTableSQL($bean);
639
+        $tablename = $bean->getTableName();
640
+        $msg = "Error creating table: $tablename:";
641
+        $this->query($sql,true,$msg);
642
+        if(!$this->supports("inline_keys")) {
643
+        // handle constraints and indices
644
+            $indicesArr = $this->createConstraintSql($bean);
645
+            if (count($indicesArr) > 0)
646
+                foreach ($indicesArr as $indexSql)
647
+                    $this->query($indexSql, true, $msg);
648
+        }
649
+    }
650
+
651
+    /**
652
+     * returns SQL to create constraints or indices
653
+     *
654
+     * @param  SugarBean $bean SugarBean instance
655
+     * @return array list of SQL statements
656
+     */
657
+    protected function createConstraintSql(SugarBean $bean)
658
+    {
659
+        return $this->getConstraintSql($bean->getIndices(), $bean->getTableName());
660
+    }
661
+
662
+    /**
663
+     * Implements creation of a db table
664
+     *
665
+     * @param string $tablename
666
+     * @param array  $fieldDefs  Field definitions, in vardef format
667
+     * @param array  $indices    Index definitions, in vardef format
668
+     * @param string $engine    Engine parameter, used for MySQL engine so far
669 669
      * @todo: refactor engine param to be more generic
670 670
      * @return bool success value
671 671
      */
672
-	public function createTableParams($tablename, $fieldDefs, $indices, $engine = null)
673
-	{
674
-		if (!empty($fieldDefs)) {
675
-			$sql = $this->createTableSQLParams($tablename, $fieldDefs, $indices, $engine);
676
-			$res = true;
677
-			if ($sql) {
678
-				$msg = "Error creating table: $tablename";
679
-				$res = ($res and $this->query($sql,true,$msg));
680
-			}
681
-			if(!$this->supports("inline_keys")) {
682
-				// handle constraints and indices
683
-				$indicesArr = $this->getConstraintSql($indices, $tablename);
684
-				if (count($indicesArr) > 0)
685
-					foreach ($indicesArr as $indexSql)
686
-						$res = ($res and $this->query($indexSql, true, "Error creating indexes"));
687
-			}
688
-			return $res;
689
-		}
690
-		return false;
691
-	}
692
-
693
-	/**
694
-	 * Implements repair of a db table for a bean.
695
-	 *
696
-	 * @param  SugarBean $bean    SugarBean instance
697
-	 * @param  bool   $execute true if we want the action to take place, false if we just want the sql returned
698
-	 * @return string SQL statement or empty string, depending upon $execute
699
-	 */
700
-	public function repairTable(SugarBean $bean, $execute = true)
701
-	{
702
-		$indices   = $bean->getIndices();
703
-		$fielddefs = $bean->getFieldDefinitions();
704
-		$tablename = $bean->getTableName();
705
-
706
-		//Clean the indexes to prevent duplicate definitions
707
-		$new_index = array();
708
-		foreach($indices as $ind_def){
709
-			$new_index[$ind_def['name']] = $ind_def;
710
-		}
711
-		//jc: added this for beans that do not actually have a table, namely
712
-		//ForecastOpportunities
713
-		if($tablename == 'does_not_exist' || $tablename == '')
714
-			return '';
715
-
716
-		global $dictionary;
717
-		$engine=null;
718
-		if (isset($dictionary[$bean->getObjectName()]['engine']) && !empty($dictionary[$bean->getObjectName()]['engine']) )
719
-			$engine = $dictionary[$bean->getObjectName()]['engine'];
720
-
721
-		return $this->repairTableParams($tablename, $fielddefs,$new_index,$execute,$engine);
722
-	}
723
-
724
-	/**
725
-	 * Can this field be null?
726
-	 * Auto-increment and ID fields can not be null
727
-	 * @param array $vardef
672
+    public function createTableParams($tablename, $fieldDefs, $indices, $engine = null)
673
+    {
674
+        if (!empty($fieldDefs)) {
675
+            $sql = $this->createTableSQLParams($tablename, $fieldDefs, $indices, $engine);
676
+            $res = true;
677
+            if ($sql) {
678
+                $msg = "Error creating table: $tablename";
679
+                $res = ($res and $this->query($sql,true,$msg));
680
+            }
681
+            if(!$this->supports("inline_keys")) {
682
+                // handle constraints and indices
683
+                $indicesArr = $this->getConstraintSql($indices, $tablename);
684
+                if (count($indicesArr) > 0)
685
+                    foreach ($indicesArr as $indexSql)
686
+                        $res = ($res and $this->query($indexSql, true, "Error creating indexes"));
687
+            }
688
+            return $res;
689
+        }
690
+        return false;
691
+    }
692
+
693
+    /**
694
+     * Implements repair of a db table for a bean.
695
+     *
696
+     * @param  SugarBean $bean    SugarBean instance
697
+     * @param  bool   $execute true if we want the action to take place, false if we just want the sql returned
698
+     * @return string SQL statement or empty string, depending upon $execute
699
+     */
700
+    public function repairTable(SugarBean $bean, $execute = true)
701
+    {
702
+        $indices   = $bean->getIndices();
703
+        $fielddefs = $bean->getFieldDefinitions();
704
+        $tablename = $bean->getTableName();
705
+
706
+        //Clean the indexes to prevent duplicate definitions
707
+        $new_index = array();
708
+        foreach($indices as $ind_def){
709
+            $new_index[$ind_def['name']] = $ind_def;
710
+        }
711
+        //jc: added this for beans that do not actually have a table, namely
712
+        //ForecastOpportunities
713
+        if($tablename == 'does_not_exist' || $tablename == '')
714
+            return '';
715
+
716
+        global $dictionary;
717
+        $engine=null;
718
+        if (isset($dictionary[$bean->getObjectName()]['engine']) && !empty($dictionary[$bean->getObjectName()]['engine']) )
719
+            $engine = $dictionary[$bean->getObjectName()]['engine'];
720
+
721
+        return $this->repairTableParams($tablename, $fielddefs,$new_index,$execute,$engine);
722
+    }
723
+
724
+    /**
725
+     * Can this field be null?
726
+     * Auto-increment and ID fields can not be null
727
+     * @param array $vardef
728 728
      * @return bool
729 729
      */
730
-	protected function isNullable($vardef)
731
-	{
732
-
733
-		if(isset($vardef['isnull']) && (strtolower($vardef['isnull']) == 'false' || $vardef['isnull'] === false)
734
-			&& !empty($vardef['required'])) {
735
-				/* required + is_null=false => not null */
736
-			return false;
737
-		}
738
-		if(empty($vardef['auto_increment']) && (empty($vardef['type']) || $vardef['type'] != 'id')
739
-					&& (empty($vardef['dbType']) || $vardef['dbType'] != 'id')
740
-					&& (empty($vardef['name']) || ($vardef['name'] != 'id' && $vardef['name'] != 'deleted'))
741
-		) {
742
-			return true;
743
-		}
744
-		return false;
745
-	}
746
-
747
-
748
-	/**
749
-	 * Builds the SQL commands that repair a table structure
750
-	 *
751
-	 * @param  string $tablename
752
-	 * @param  array  $fielddefs Field definitions, in vardef format
753
-	 * @param  array  $indices   Index definitions, in vardef format
754
-	 * @param  bool   $execute   optional, true if we want the queries executed instead of returned
755
-	 * @param  string $engine    optional, MySQL engine
730
+    protected function isNullable($vardef)
731
+    {
732
+
733
+        if(isset($vardef['isnull']) && (strtolower($vardef['isnull']) == 'false' || $vardef['isnull'] === false)
734
+            && !empty($vardef['required'])) {
735
+                /* required + is_null=false => not null */
736
+            return false;
737
+        }
738
+        if(empty($vardef['auto_increment']) && (empty($vardef['type']) || $vardef['type'] != 'id')
739
+                    && (empty($vardef['dbType']) || $vardef['dbType'] != 'id')
740
+                    && (empty($vardef['name']) || ($vardef['name'] != 'id' && $vardef['name'] != 'deleted'))
741
+        ) {
742
+            return true;
743
+        }
744
+        return false;
745
+    }
746
+
747
+
748
+    /**
749
+     * Builds the SQL commands that repair a table structure
750
+     *
751
+     * @param  string $tablename
752
+     * @param  array  $fielddefs Field definitions, in vardef format
753
+     * @param  array  $indices   Index definitions, in vardef format
754
+     * @param  bool   $execute   optional, true if we want the queries executed instead of returned
755
+     * @param  string $engine    optional, MySQL engine
756 756
      * @todo: refactor engine param to be more generic
757 757
      * @return string
758 758
      */
759
-	public function repairTableParams($tablename, $fielddefs,  $indices, $execute = true, $engine = null)
760
-	{
761
-		//jc: had a bug when running the repair if the tablename is blank the repair will
762
-		//fail when it tries to create a repair table
763
-		if ($tablename == '' || empty($fielddefs))
764
-			return '';
765
-
766
-		//if the table does not exist create it and we are done
767
-		$sql = "/* Table : $tablename */\n";
768
-		if (!$this->tableExists($tablename)) {
769
-			$createtablesql = $this->createTableSQLParams($tablename,$fielddefs,$indices,$engine);
770
-			if($execute && $createtablesql){
771
-				$this->createTableParams($tablename,$fielddefs,$indices,$engine);
772
-			}
773
-
774
-			$sql .= "/* MISSING TABLE: {$tablename} */\n";
775
-			$sql .= $createtablesql . "\n";
776
-			return $sql;
777
-		}
778
-
779
-		$compareFieldDefs = $this->get_columns($tablename);
780
-		$compareIndices = $this->get_indices($tablename);
781
-
782
-		$take_action = false;
783
-
784
-		// do column comparisons
785
-		$sql .=	"/*COLUMNS*/\n";
786
-		foreach ($fielddefs as $name => $value) {
787
-			if (isset($value['source']) && $value['source'] != 'db')
788
-				continue;
759
+    public function repairTableParams($tablename, $fielddefs,  $indices, $execute = true, $engine = null)
760
+    {
761
+        //jc: had a bug when running the repair if the tablename is blank the repair will
762
+        //fail when it tries to create a repair table
763
+        if ($tablename == '' || empty($fielddefs))
764
+            return '';
765
+
766
+        //if the table does not exist create it and we are done
767
+        $sql = "/* Table : $tablename */\n";
768
+        if (!$this->tableExists($tablename)) {
769
+            $createtablesql = $this->createTableSQLParams($tablename,$fielddefs,$indices,$engine);
770
+            if($execute && $createtablesql){
771
+                $this->createTableParams($tablename,$fielddefs,$indices,$engine);
772
+            }
773
+
774
+            $sql .= "/* MISSING TABLE: {$tablename} */\n";
775
+            $sql .= $createtablesql . "\n";
776
+            return $sql;
777
+        }
778
+
779
+        $compareFieldDefs = $this->get_columns($tablename);
780
+        $compareIndices = $this->get_indices($tablename);
781
+
782
+        $take_action = false;
783
+
784
+        // do column comparisons
785
+        $sql .=	"/*COLUMNS*/\n";
786
+        foreach ($fielddefs as $name => $value) {
787
+            if (isset($value['source']) && $value['source'] != 'db')
788
+                continue;
789 789
 
790 790
             // Bug #42406. Skipping breaked vardef without type or name
791 791
             if (isset($value['name']) == false || $value['name'] == false)
@@ -799,183 +799,183 @@  discard block
 block discarded – undo
799 799
                 continue;
800 800
             }
801 801
 
802
-			$name = strtolower($value['name']);
803
-			// add or fix the field defs per what the DB is expected to give us back
804
-			$this->massageFieldDef($value,$tablename);
805
-
806
-			$ignorerequired=false;
807
-
808
-			//Do not track requiredness in the DB, auto_increment, ID,
809
-			// and deleted fields are always required in the DB, so don't force those
810
-			if ($this->isNullable($value)) {
811
-				$value['required'] = false;
812
-			}
813
-			//Should match the conditions in DBManager::oneColumnSQLRep for DB required fields, type='id' fields will sometimes
814
-
815
-			//come into this function as 'type' = 'char', 'dbType' = 'id' without required set in $value. Assume they are correct and leave them alone.
816
-			else if (($name == 'id' || $value['type'] == 'id' || (isset($value['dbType']) && $value['dbType'] == 'id'))
817
-				&& (!isset($value['required']) && isset($compareFieldDefs[$name]['required'])))
818
-			{
819
-				$value['required'] = $compareFieldDefs[$name]['required'];
820
-			}
821
-
822
-			if ( !isset($compareFieldDefs[$name]) ) {
823
-				// ok we need this field lets create it
824
-				$sql .=	"/*MISSING IN DATABASE - $name -  ROW*/\n";
825
-				$sql .= $this->addColumnSQL($tablename, $value) .  "\n";
826
-				if ($execute)
827
-					$this->addColumn($tablename, $value);
828
-				$take_action = true;
829
-			} elseif ( !$this->compareVarDefs($compareFieldDefs[$name],$value)) {
830
-				//fields are different lets alter it
831
-				$sql .=	"/*MISMATCH WITH DATABASE - $name -  ROW ";
832
-				foreach($compareFieldDefs[$name] as $rKey => $rValue) {
833
-					$sql .=	"[$rKey] => '$rValue'  ";
834
-				}
835
-				$sql .=	"*/\n";
836
-				$sql .=	"/* VARDEF - $name -  ROW";
837
-				foreach($value as $rKey => $rValue) {
838
-					$sql .=	"[$rKey] => '$rValue'  ";
839
-				}
840
-				$sql .=	"*/\n";
841
-
842
-				//jc: oracle will complain if you try to execute a statement that sets a column to (not) null
843
-				//when it is already (not) null
844
-				if ( isset($value['isnull']) && isset($compareFieldDefs[$name]['isnull']) &&
845
-					$value['isnull'] === $compareFieldDefs[$name]['isnull']) {
846
-					unset($value['required']);
847
-					$ignorerequired=true;
848
-				}
849
-
850
-				//dwheeler: Once a column has been defined as null, we cannot try to force it back to !null
851
-				if ((isset($value['required']) && ($value['required'] === true || $value['required'] == 'true' || $value['required'] === 1))
852
-					&& (empty($compareFieldDefs[$name]['required']) || $compareFieldDefs[$name]['required'] != 'true'))
853
-				{
854
-					$ignorerequired = true;
855
-				}
856
-				$altersql = $this->alterColumnSQL($tablename, $value,$ignorerequired);
857
-				if(is_array($altersql)) {
858
-					$altersql = join("\n", $altersql);
859
-				}
860
-				$sql .= $altersql .  "\n";
861
-				if($execute){
862
-					$this->alterColumn($tablename, $value, $ignorerequired);
863
-				}
864
-				$take_action = true;
865
-			}
866
-		}
867
-
868
-		// do index comparisons
869
-		$sql .=	"/* INDEXES */\n";
870
-		$correctedIndexs = array();
802
+            $name = strtolower($value['name']);
803
+            // add or fix the field defs per what the DB is expected to give us back
804
+            $this->massageFieldDef($value,$tablename);
871 805
 
872
-        $compareIndices_case_insensitive = array();
806
+            $ignorerequired=false;
873 807
 
874
-		// do indices comparisons case-insensitive
875
-		foreach($compareIndices as $k => $value){
876
-			$value['name'] = strtolower($value['name']);
877
-			$compareIndices_case_insensitive[strtolower($k)] = $value;
878
-		}
879
-		$compareIndices = $compareIndices_case_insensitive;
880
-		unset($compareIndices_case_insensitive);
881
-
882
-		foreach ($indices as $value) {
883
-			if (isset($value['source']) && $value['source'] != 'db')
884
-				continue;
885
-
886
-
887
-			$validDBName = $this->getValidDBName($value['name'], true, 'index', true);
888
-			if (isset($compareIndices[$validDBName])) {
889
-				$value['name'] = $validDBName;
890
-			}
891
-		    $name = strtolower($value['name']);
892
-
893
-			//Don't attempt to fix the same index twice in one pass;
894
-			if (isset($correctedIndexs[$name]))
895
-				continue;
896
-
897
-			//don't bother checking primary nothing we can do about them
898
-			if (isset($value['type']) && $value['type'] == 'primary')
899
-				continue;
900
-
901
-			//database helpers do not know how to handle full text indices
902
-			if ($value['type']=='fulltext')
903
-				continue;
904
-
905
-			if ( in_array($value['type'],array('alternate_key','foreign')) )
906
-				$value['type'] = 'index';
907
-
908
-			if ( !isset($compareIndices[$name]) ) {
909
-				//First check if an index exists that doesn't match our name, if so, try to rename it
910
-				$found = false;
911
-				foreach ($compareIndices as $ex_name => $ex_value) {
912
-					if($this->compareVarDefs($ex_value, $value, true)) {
913
-						$found = $ex_name;
914
-						break;
915
-					}
916
-				}
917
-				if ($found) {
918
-					$sql .=	 "/*MISSNAMED INDEX IN DATABASE - $name - $ex_name */\n";
919
-					$rename = $this->renameIndexDefs($ex_value, $value, $tablename);
920
-					if($execute) {
921
-						$this->query($rename, true, "Cannot rename index");
922
-					}
923
-					$sql .= is_array($rename)?join("\n", $rename). "\n":$rename."\n";
924
-
925
-				} else {
926
-					// ok we need this field lets create it
927
-					$sql .=	 "/*MISSING INDEX IN DATABASE - $name -{$value['type']}  ROW */\n";
928
-					$sql .= $this->addIndexes($tablename,array($value), $execute) .  "\n";
929
-				}
930
-				$take_action = true;
931
-				$correctedIndexs[$name] = true;
932
-			} elseif ( !$this->compareVarDefs($compareIndices[$name],$value) ) {
933
-				// fields are different lets alter it
934
-				$sql .=	"/*INDEX MISMATCH WITH DATABASE - $name -  ROW ";
935
-				foreach ($compareIndices[$name] as $n1 => $t1) {
936
-					$sql .=	 "<$n1>";
937
-					if ( $n1 == 'fields' )
938
-						foreach($t1 as $rKey => $rValue)
939
-							$sql .= "[$rKey] => '$rValue'  ";
940
-					else
941
-						$sql .= " $t1 ";
942
-				}
943
-				$sql .=	"*/\n";
944
-				$sql .=	"/* VARDEF - $name -  ROW";
945
-				foreach ($value as $n1 => $t1) {
946
-					$sql .=	"<$n1>";
947
-					if ( $n1 == 'fields' )
948
-						foreach ($t1 as $rKey => $rValue)
949
-							$sql .=	"[$rKey] => '$rValue'  ";
950
-					else
951
-						$sql .= " $t1 ";
952
-				}
953
-				$sql .=	"*/\n";
954
-				$sql .= $this->modifyIndexes($tablename,array($value), $execute) .  "\n";
955
-				$take_action = true;
956
-				$correctedIndexs[$name] = true;
957
-			}
958
-		}
959
-
960
-		return ($take_action === true) ? $sql : '';
961
-	}
808
+            //Do not track requiredness in the DB, auto_increment, ID,
809
+            // and deleted fields are always required in the DB, so don't force those
810
+            if ($this->isNullable($value)) {
811
+                $value['required'] = false;
812
+            }
813
+            //Should match the conditions in DBManager::oneColumnSQLRep for DB required fields, type='id' fields will sometimes
962 814
 
963
-    /**
964
-     * Compares two vardefs
965
-     *
966
-     * @param  array  $fielddef1 This is from the database
967
-     * @param  array  $fielddef2 This is from the vardef
968
-     * @param bool $ignoreName Ignore name-only differences?
969
-     * @return bool   true if they match, false if they don't
970
-     */
971
-	public function compareVarDefs($fielddef1, $fielddef2, $ignoreName = false)
972
-	{
973
-		foreach ( $fielddef1 as $key => $value ) {
974
-			if ($key == 'name' && $ignoreName)
975
-				continue;
976
-            if (isset($fielddef2[$key]))
815
+            //come into this function as 'type' = 'char', 'dbType' = 'id' without required set in $value. Assume they are correct and leave them alone.
816
+            else if (($name == 'id' || $value['type'] == 'id' || (isset($value['dbType']) && $value['dbType'] == 'id'))
817
+                && (!isset($value['required']) && isset($compareFieldDefs[$name]['required'])))
977 818
             {
978
-                if (!is_array($fielddef1[$key]) && !is_array($fielddef2[$key]))
819
+                $value['required'] = $compareFieldDefs[$name]['required'];
820
+            }
821
+
822
+            if ( !isset($compareFieldDefs[$name]) ) {
823
+                // ok we need this field lets create it
824
+                $sql .=	"/*MISSING IN DATABASE - $name -  ROW*/\n";
825
+                $sql .= $this->addColumnSQL($tablename, $value) .  "\n";
826
+                if ($execute)
827
+                    $this->addColumn($tablename, $value);
828
+                $take_action = true;
829
+            } elseif ( !$this->compareVarDefs($compareFieldDefs[$name],$value)) {
830
+                //fields are different lets alter it
831
+                $sql .=	"/*MISMATCH WITH DATABASE - $name -  ROW ";
832
+                foreach($compareFieldDefs[$name] as $rKey => $rValue) {
833
+                    $sql .=	"[$rKey] => '$rValue'  ";
834
+                }
835
+                $sql .=	"*/\n";
836
+                $sql .=	"/* VARDEF - $name -  ROW";
837
+                foreach($value as $rKey => $rValue) {
838
+                    $sql .=	"[$rKey] => '$rValue'  ";
839
+                }
840
+                $sql .=	"*/\n";
841
+
842
+                //jc: oracle will complain if you try to execute a statement that sets a column to (not) null
843
+                //when it is already (not) null
844
+                if ( isset($value['isnull']) && isset($compareFieldDefs[$name]['isnull']) &&
845
+                    $value['isnull'] === $compareFieldDefs[$name]['isnull']) {
846
+                    unset($value['required']);
847
+                    $ignorerequired=true;
848
+                }
849
+
850
+                //dwheeler: Once a column has been defined as null, we cannot try to force it back to !null
851
+                if ((isset($value['required']) && ($value['required'] === true || $value['required'] == 'true' || $value['required'] === 1))
852
+                    && (empty($compareFieldDefs[$name]['required']) || $compareFieldDefs[$name]['required'] != 'true'))
853
+                {
854
+                    $ignorerequired = true;
855
+                }
856
+                $altersql = $this->alterColumnSQL($tablename, $value,$ignorerequired);
857
+                if(is_array($altersql)) {
858
+                    $altersql = join("\n", $altersql);
859
+                }
860
+                $sql .= $altersql .  "\n";
861
+                if($execute){
862
+                    $this->alterColumn($tablename, $value, $ignorerequired);
863
+                }
864
+                $take_action = true;
865
+            }
866
+        }
867
+
868
+        // do index comparisons
869
+        $sql .=	"/* INDEXES */\n";
870
+        $correctedIndexs = array();
871
+
872
+        $compareIndices_case_insensitive = array();
873
+
874
+        // do indices comparisons case-insensitive
875
+        foreach($compareIndices as $k => $value){
876
+            $value['name'] = strtolower($value['name']);
877
+            $compareIndices_case_insensitive[strtolower($k)] = $value;
878
+        }
879
+        $compareIndices = $compareIndices_case_insensitive;
880
+        unset($compareIndices_case_insensitive);
881
+
882
+        foreach ($indices as $value) {
883
+            if (isset($value['source']) && $value['source'] != 'db')
884
+                continue;
885
+
886
+
887
+            $validDBName = $this->getValidDBName($value['name'], true, 'index', true);
888
+            if (isset($compareIndices[$validDBName])) {
889
+                $value['name'] = $validDBName;
890
+            }
891
+            $name = strtolower($value['name']);
892
+
893
+            //Don't attempt to fix the same index twice in one pass;
894
+            if (isset($correctedIndexs[$name]))
895
+                continue;
896
+
897
+            //don't bother checking primary nothing we can do about them
898
+            if (isset($value['type']) && $value['type'] == 'primary')
899
+                continue;
900
+
901
+            //database helpers do not know how to handle full text indices
902
+            if ($value['type']=='fulltext')
903
+                continue;
904
+
905
+            if ( in_array($value['type'],array('alternate_key','foreign')) )
906
+                $value['type'] = 'index';
907
+
908
+            if ( !isset($compareIndices[$name]) ) {
909
+                //First check if an index exists that doesn't match our name, if so, try to rename it
910
+                $found = false;
911
+                foreach ($compareIndices as $ex_name => $ex_value) {
912
+                    if($this->compareVarDefs($ex_value, $value, true)) {
913
+                        $found = $ex_name;
914
+                        break;
915
+                    }
916
+                }
917
+                if ($found) {
918
+                    $sql .=	 "/*MISSNAMED INDEX IN DATABASE - $name - $ex_name */\n";
919
+                    $rename = $this->renameIndexDefs($ex_value, $value, $tablename);
920
+                    if($execute) {
921
+                        $this->query($rename, true, "Cannot rename index");
922
+                    }
923
+                    $sql .= is_array($rename)?join("\n", $rename). "\n":$rename."\n";
924
+
925
+                } else {
926
+                    // ok we need this field lets create it
927
+                    $sql .=	 "/*MISSING INDEX IN DATABASE - $name -{$value['type']}  ROW */\n";
928
+                    $sql .= $this->addIndexes($tablename,array($value), $execute) .  "\n";
929
+                }
930
+                $take_action = true;
931
+                $correctedIndexs[$name] = true;
932
+            } elseif ( !$this->compareVarDefs($compareIndices[$name],$value) ) {
933
+                // fields are different lets alter it
934
+                $sql .=	"/*INDEX MISMATCH WITH DATABASE - $name -  ROW ";
935
+                foreach ($compareIndices[$name] as $n1 => $t1) {
936
+                    $sql .=	 "<$n1>";
937
+                    if ( $n1 == 'fields' )
938
+                        foreach($t1 as $rKey => $rValue)
939
+                            $sql .= "[$rKey] => '$rValue'  ";
940
+                    else
941
+                        $sql .= " $t1 ";
942
+                }
943
+                $sql .=	"*/\n";
944
+                $sql .=	"/* VARDEF - $name -  ROW";
945
+                foreach ($value as $n1 => $t1) {
946
+                    $sql .=	"<$n1>";
947
+                    if ( $n1 == 'fields' )
948
+                        foreach ($t1 as $rKey => $rValue)
949
+                            $sql .=	"[$rKey] => '$rValue'  ";
950
+                    else
951
+                        $sql .= " $t1 ";
952
+                }
953
+                $sql .=	"*/\n";
954
+                $sql .= $this->modifyIndexes($tablename,array($value), $execute) .  "\n";
955
+                $take_action = true;
956
+                $correctedIndexs[$name] = true;
957
+            }
958
+        }
959
+
960
+        return ($take_action === true) ? $sql : '';
961
+    }
962
+
963
+    /**
964
+     * Compares two vardefs
965
+     *
966
+     * @param  array  $fielddef1 This is from the database
967
+     * @param  array  $fielddef2 This is from the vardef
968
+     * @param bool $ignoreName Ignore name-only differences?
969
+     * @return bool   true if they match, false if they don't
970
+     */
971
+    public function compareVarDefs($fielddef1, $fielddef2, $ignoreName = false)
972
+    {
973
+        foreach ( $fielddef1 as $key => $value ) {
974
+            if ($key == 'name' && $ignoreName)
975
+                continue;
976
+            if (isset($fielddef2[$key]))
977
+            {
978
+                if (!is_array($fielddef1[$key]) && !is_array($fielddef2[$key]))
979 979
                 {
980 980
                     if (strtolower($fielddef1[$key]) == strtolower($fielddef2[$key]))
981 981
                     {
@@ -990,64 +990,64 @@  discard block
 block discarded – undo
990 990
                     }
991 991
                 }
992 992
             }
993
-			//Ignore len if its not set in the vardef
994
-			if ($key == 'len' && empty($fielddef2[$key]))
995
-				continue;
993
+            //Ignore len if its not set in the vardef
994
+            if ($key == 'len' && empty($fielddef2[$key]))
995
+                continue;
996 996
             // if the length in db is greather than the vardef, ignore it
997 997
             if ($key == 'len' && ($fielddef1[$key] >= $fielddef2[$key])) {
998 998
                 continue;
999 999
             }
1000
-			return false;
1001
-		}
1002
-
1003
-		return true;
1004
-	}
1005
-
1006
-	/**
1007
-	 * Compare a field in two tables
1008
-	 * @deprecated
1009
-	 * @param  string $name   field name
1010
-	 * @param  string $table1
1011
-	 * @param  string $table2
1012
-	 * @return array  array with keys 'msg','table1','table2'
1013
-	 */
1014
-	public function compareFieldInTables($name, $table1, $table2)
1015
-	{
1016
-		$row1 = $this->describeField($name, $table1);
1017
-		$row2 = $this->describeField($name, $table2);
1018
-		$returnArray = array(
1019
-			'table1' => $row1,
1020
-			'table2' => $row2,
1021
-			'msg'    => 'error',
1022
-			);
1023
-
1024
-		$ignore_filter = array('Key'=>1);
1025
-		if ($row1) {
1026
-			if (!$row2) {
1027
-				// Exists on table1 but not table2
1028
-				$returnArray['msg'] = 'not_exists_table2';
1029
-			}
1030
-			else {
1031
-				if (sizeof($row1) != sizeof($row2)) {
1032
-					$returnArray['msg'] = 'no_match';
1033
-				}
1034
-				else {
1035
-					$returnArray['msg'] = 'match';
1036
-					foreach($row1 as $key => $value){
1037
-						//ignore keys when checking we will check them when we do the index check
1038
-						if( !isset($ignore_filter[$key]) && (!isset($row2[$key]) || $row1[$key] !== $row2[$key])){
1039
-							$returnArray['msg'] = 'no_match';
1040
-						}
1041
-					}
1042
-				}
1043
-			}
1044
-		}
1045
-		else {
1046
-			$returnArray['msg'] = 'not_exists_table1';
1047
-		}
1048
-
1049
-		return $returnArray;
1050
-	}
1000
+            return false;
1001
+        }
1002
+
1003
+        return true;
1004
+    }
1005
+
1006
+    /**
1007
+     * Compare a field in two tables
1008
+     * @deprecated
1009
+     * @param  string $name   field name
1010
+     * @param  string $table1
1011
+     * @param  string $table2
1012
+     * @return array  array with keys 'msg','table1','table2'
1013
+     */
1014
+    public function compareFieldInTables($name, $table1, $table2)
1015
+    {
1016
+        $row1 = $this->describeField($name, $table1);
1017
+        $row2 = $this->describeField($name, $table2);
1018
+        $returnArray = array(
1019
+            'table1' => $row1,
1020
+            'table2' => $row2,
1021
+            'msg'    => 'error',
1022
+            );
1023
+
1024
+        $ignore_filter = array('Key'=>1);
1025
+        if ($row1) {
1026
+            if (!$row2) {
1027
+                // Exists on table1 but not table2
1028
+                $returnArray['msg'] = 'not_exists_table2';
1029
+            }
1030
+            else {
1031
+                if (sizeof($row1) != sizeof($row2)) {
1032
+                    $returnArray['msg'] = 'no_match';
1033
+                }
1034
+                else {
1035
+                    $returnArray['msg'] = 'match';
1036
+                    foreach($row1 as $key => $value){
1037
+                        //ignore keys when checking we will check them when we do the index check
1038
+                        if( !isset($ignore_filter[$key]) && (!isset($row2[$key]) || $row1[$key] !== $row2[$key])){
1039
+                            $returnArray['msg'] = 'no_match';
1040
+                        }
1041
+                    }
1042
+                }
1043
+            }
1044
+        }
1045
+        else {
1046
+            $returnArray['msg'] = 'not_exists_table1';
1047
+        }
1048
+
1049
+        return $returnArray;
1050
+    }
1051 1051
 //
1052 1052
 //    /**
1053 1053
 //     * Compare an index in two different tables
@@ -1097,193 +1097,193 @@  discard block
 block discarded – undo
1097 1097
 //    }
1098 1098
 
1099 1099
 
1100
-	/**
1101
-	 * Creates an index identified by name on the given fields.
1102
-	 *
1103
-	 * @param SugarBean $bean      SugarBean instance
1104
-	 * @param array  $fieldDefs Field definitions, in vardef format
1105
-	 * @param string $name      index name
1106
-	 * @param bool   $unique    optional, true if we want to create an unique index
1100
+    /**
1101
+     * Creates an index identified by name on the given fields.
1102
+     *
1103
+     * @param SugarBean $bean      SugarBean instance
1104
+     * @param array  $fieldDefs Field definitions, in vardef format
1105
+     * @param string $name      index name
1106
+     * @param bool   $unique    optional, true if we want to create an unique index
1107 1107
      * @return bool query result
1108 1108
      */
1109
-	public function createIndex(SugarBean $bean, $fieldDefs, $name, $unique = true)
1110
-	{
1111
-		$sql = $this->createIndexSQL($bean, $fieldDefs, $name, $unique);
1112
-		$tablename = $bean->getTableName();
1113
-		$msg = "Error creating index $name on table: $tablename:";
1114
-		return $this->query($sql,true,$msg);
1115
-	}
1116
-
1117
-	/**
1118
-	 * returns a SQL query that creates the indices as defined in metadata
1119
-	 * @param  array  $indices Assoc array with index definitions from vardefs
1120
-	 * @param  string $table Focus table
1121
-	 * @return array  Array of SQL queries to generate indices
1122
-	 */
1123
-	public function getConstraintSql($indices, $table)
1124
-	{
1125
-		if (!$this->isFieldArray($indices))
1126
-			$indices = array($indices);
1127
-
1128
-		$columns = array();
1129
-
1130
-		foreach ($indices as $index) {
1131
-			if(!empty($index['db']) && $index['db'] != $this->dbType)
1132
-				continue;
1133
-			if (isset($index['source']) && $index['source'] != 'db')
1134
-			continue;
1135
-
1136
-			$sql = $this->add_drop_constraint($table, $index);
1137
-
1138
-			if(!empty($sql)) {
1139
-				$columns[] = $sql;
1140
-			}
1141
-		}
1142
-
1143
-		return $columns;
1144
-	}
1145
-
1146
-	/**
1147
-	 * Adds a new indexes
1148
-	 *
1149
-	 * @param  string $tablename
1150
-	 * @param  array  $indexes   indexes to add
1151
-	 * @param  bool   $execute   true if we want to execute the returned sql statement
1152
-	 * @return string SQL statement
1153
-	 */
1154
-	public function addIndexes($tablename, $indexes, $execute = true)
1155
-	{
1156
-		$alters = $this->getConstraintSql($indexes, $tablename);
1157
-		if ($execute) {
1158
-			foreach($alters as $sql) {
1159
-				$this->query($sql, true, "Error adding index: ");
1160
-			}
1161
-		}
1162
-		if(!empty($alters)) {
1163
-			$sql = join(";\n", $alters).";\n";
1164
-		} else {
1165
-			$sql = '';
1166
-		}
1167
-		return $sql;
1168
-	}
1169
-
1170
-	/**
1171
-	 * Drops indexes
1172
-	 *
1173
-	 * @param  string $tablename
1174
-	 * @param  array  $indexes   indexes to drop
1175
-	 * @param  bool   $execute   true if we want to execute the returned sql statement
1176
-	 * @return string SQL statement
1177
-	 */
1178
-	public function dropIndexes($tablename, $indexes, $execute = true)
1179
-	{
1180
-		$sqls = array();
1181
-		foreach ($indexes as $index) {
1182
-			$name =$index['name'];
1183
-			$sqls[$name] = $this->add_drop_constraint($tablename,$index,true);
1184
-		}
1185
-		if (!empty($sqls) && $execute) {
1186
-			foreach($sqls as $name => $sql) {
1187
-				unset(self::$index_descriptions[$tablename][$name]);
1188
-				$this->query($sql);
1189
-			}
1190
-		}
1191
-		if(!empty($sqls)) {
1192
-			return join(";\n",$sqls).";";
1193
-		} else {
1194
-			return '';
1195
-		}
1196
-	}
1197
-
1198
-	/**
1199
-	 * Modifies indexes
1200
-	 *
1201
-	 * @param  string $tablename
1202
-	 * @param  array  $indexes   indexes to modify
1203
-	 * @param  bool   $execute   true if we want to execute the returned sql statement
1204
-	 * @return string SQL statement
1205
-	 */
1206
-	public function modifyIndexes($tablename, $indexes, $execute = true)
1207
-	{
1208
-		return $this->dropIndexes($tablename, $indexes, $execute)."\n".
1209
-			$this->addIndexes($tablename, $indexes, $execute);
1210
-	}
1211
-
1212
-	/**
1213
-	 * Adds a column to table identified by field def.
1214
-	 *
1215
-	 * @param string $tablename
1216
-	 * @param array  $fieldDefs
1109
+    public function createIndex(SugarBean $bean, $fieldDefs, $name, $unique = true)
1110
+    {
1111
+        $sql = $this->createIndexSQL($bean, $fieldDefs, $name, $unique);
1112
+        $tablename = $bean->getTableName();
1113
+        $msg = "Error creating index $name on table: $tablename:";
1114
+        return $this->query($sql,true,$msg);
1115
+    }
1116
+
1117
+    /**
1118
+     * returns a SQL query that creates the indices as defined in metadata
1119
+     * @param  array  $indices Assoc array with index definitions from vardefs
1120
+     * @param  string $table Focus table
1121
+     * @return array  Array of SQL queries to generate indices
1122
+     */
1123
+    public function getConstraintSql($indices, $table)
1124
+    {
1125
+        if (!$this->isFieldArray($indices))
1126
+            $indices = array($indices);
1127
+
1128
+        $columns = array();
1129
+
1130
+        foreach ($indices as $index) {
1131
+            if(!empty($index['db']) && $index['db'] != $this->dbType)
1132
+                continue;
1133
+            if (isset($index['source']) && $index['source'] != 'db')
1134
+            continue;
1135
+
1136
+            $sql = $this->add_drop_constraint($table, $index);
1137
+
1138
+            if(!empty($sql)) {
1139
+                $columns[] = $sql;
1140
+            }
1141
+        }
1142
+
1143
+        return $columns;
1144
+    }
1145
+
1146
+    /**
1147
+     * Adds a new indexes
1148
+     *
1149
+     * @param  string $tablename
1150
+     * @param  array  $indexes   indexes to add
1151
+     * @param  bool   $execute   true if we want to execute the returned sql statement
1152
+     * @return string SQL statement
1153
+     */
1154
+    public function addIndexes($tablename, $indexes, $execute = true)
1155
+    {
1156
+        $alters = $this->getConstraintSql($indexes, $tablename);
1157
+        if ($execute) {
1158
+            foreach($alters as $sql) {
1159
+                $this->query($sql, true, "Error adding index: ");
1160
+            }
1161
+        }
1162
+        if(!empty($alters)) {
1163
+            $sql = join(";\n", $alters).";\n";
1164
+        } else {
1165
+            $sql = '';
1166
+        }
1167
+        return $sql;
1168
+    }
1169
+
1170
+    /**
1171
+     * Drops indexes
1172
+     *
1173
+     * @param  string $tablename
1174
+     * @param  array  $indexes   indexes to drop
1175
+     * @param  bool   $execute   true if we want to execute the returned sql statement
1176
+     * @return string SQL statement
1177
+     */
1178
+    public function dropIndexes($tablename, $indexes, $execute = true)
1179
+    {
1180
+        $sqls = array();
1181
+        foreach ($indexes as $index) {
1182
+            $name =$index['name'];
1183
+            $sqls[$name] = $this->add_drop_constraint($tablename,$index,true);
1184
+        }
1185
+        if (!empty($sqls) && $execute) {
1186
+            foreach($sqls as $name => $sql) {
1187
+                unset(self::$index_descriptions[$tablename][$name]);
1188
+                $this->query($sql);
1189
+            }
1190
+        }
1191
+        if(!empty($sqls)) {
1192
+            return join(";\n",$sqls).";";
1193
+        } else {
1194
+            return '';
1195
+        }
1196
+    }
1197
+
1198
+    /**
1199
+     * Modifies indexes
1200
+     *
1201
+     * @param  string $tablename
1202
+     * @param  array  $indexes   indexes to modify
1203
+     * @param  bool   $execute   true if we want to execute the returned sql statement
1204
+     * @return string SQL statement
1205
+     */
1206
+    public function modifyIndexes($tablename, $indexes, $execute = true)
1207
+    {
1208
+        return $this->dropIndexes($tablename, $indexes, $execute)."\n".
1209
+            $this->addIndexes($tablename, $indexes, $execute);
1210
+    }
1211
+
1212
+    /**
1213
+     * Adds a column to table identified by field def.
1214
+     *
1215
+     * @param string $tablename
1216
+     * @param array  $fieldDefs
1217 1217
      * @return bool query result
1218 1218
      */
1219
-	public function addColumn($tablename, $fieldDefs)
1220
-	{
1221
-		$sql = $this->addColumnSQL($tablename, $fieldDefs);
1222
-		if ($this->isFieldArray($fieldDefs)){
1223
-			$columns = array();
1224
-			foreach ($fieldDefs as $fieldDef)
1225
-				$columns[] = $fieldDef['name'];
1226
-			$columns = implode(",", $columns);
1227
-		}
1228
-		else {
1229
-			$columns = $fieldDefs['name'];
1230
-		}
1231
-		$msg = "Error adding column(s) $columns on table: $tablename:";
1232
-		return $this->query($sql,true,$msg);
1233
-	}
1234
-
1235
-	/**
1236
-	 * Alters old column identified by oldFieldDef to new fieldDef.
1237
-	 *
1238
-	 * @param string $tablename
1239
-	 * @param array  $newFieldDef
1240
-	 * @param bool   $ignoreRequired optional, true if we are ignoring this being a required field
1219
+    public function addColumn($tablename, $fieldDefs)
1220
+    {
1221
+        $sql = $this->addColumnSQL($tablename, $fieldDefs);
1222
+        if ($this->isFieldArray($fieldDefs)){
1223
+            $columns = array();
1224
+            foreach ($fieldDefs as $fieldDef)
1225
+                $columns[] = $fieldDef['name'];
1226
+            $columns = implode(",", $columns);
1227
+        }
1228
+        else {
1229
+            $columns = $fieldDefs['name'];
1230
+        }
1231
+        $msg = "Error adding column(s) $columns on table: $tablename:";
1232
+        return $this->query($sql,true,$msg);
1233
+    }
1234
+
1235
+    /**
1236
+     * Alters old column identified by oldFieldDef to new fieldDef.
1237
+     *
1238
+     * @param string $tablename
1239
+     * @param array  $newFieldDef
1240
+     * @param bool   $ignoreRequired optional, true if we are ignoring this being a required field
1241 1241
      * @return bool query result
1242 1242
      */
1243
-	public function alterColumn($tablename, $newFieldDef, $ignoreRequired = false)
1244
-	{
1245
-		$sql = $this->alterColumnSQL($tablename, $newFieldDef,$ignoreRequired);
1246
-		if ($this->isFieldArray($newFieldDef)){
1247
-			$columns = array();
1248
-			foreach ($newFieldDef as $fieldDef) {
1249
-				$columns[] = $fieldDef['name'];
1250
-			}
1251
-			$columns = implode(",", $columns);
1252
-		}
1253
-		else {
1254
-			$columns = $newFieldDef['name'];
1255
-		}
1256
-
1257
-		$msg = "Error altering column(s) $columns on table: $tablename:";
1258
-		$res = $this->query($sql,true,$msg);
1259
-		if($res) {
1260
-			$this->getTableDescription($tablename, true); // reload table description after altering
1261
-		}
1262
-		return $res;
1263
-	}
1264
-
1265
-	/**
1266
-	 * Drops the table associated with a bean
1267
-	 *
1268
-	 * @param SugarBean $bean SugarBean instance
1243
+    public function alterColumn($tablename, $newFieldDef, $ignoreRequired = false)
1244
+    {
1245
+        $sql = $this->alterColumnSQL($tablename, $newFieldDef,$ignoreRequired);
1246
+        if ($this->isFieldArray($newFieldDef)){
1247
+            $columns = array();
1248
+            foreach ($newFieldDef as $fieldDef) {
1249
+                $columns[] = $fieldDef['name'];
1250
+            }
1251
+            $columns = implode(",", $columns);
1252
+        }
1253
+        else {
1254
+            $columns = $newFieldDef['name'];
1255
+        }
1256
+
1257
+        $msg = "Error altering column(s) $columns on table: $tablename:";
1258
+        $res = $this->query($sql,true,$msg);
1259
+        if($res) {
1260
+            $this->getTableDescription($tablename, true); // reload table description after altering
1261
+        }
1262
+        return $res;
1263
+    }
1264
+
1265
+    /**
1266
+     * Drops the table associated with a bean
1267
+     *
1268
+     * @param SugarBean $bean SugarBean instance
1269 1269
      * @return bool query result
1270
-	 */
1271
-	public function dropTable(SugarBean $bean)
1272
-	{
1273
-		return $this->dropTableName($bean->getTableName());
1274
-	}
1275
-
1276
-	/**
1277
-	 * Drops the table by name
1278
-	 *
1279
-	 * @param string $name Table name
1270
+     */
1271
+    public function dropTable(SugarBean $bean)
1272
+    {
1273
+        return $this->dropTableName($bean->getTableName());
1274
+    }
1275
+
1276
+    /**
1277
+     * Drops the table by name
1278
+     *
1279
+     * @param string $name Table name
1280 1280
      * @return bool query result
1281
-	 */
1282
-	public function dropTableName($name)
1283
-	{
1284
-		$sql = $this->dropTableNameSQL($name);
1285
-		return $this->query($sql,true,"Error dropping table $name:");
1286
-	}
1281
+     */
1282
+    public function dropTableName($name)
1283
+    {
1284
+        $sql = $this->dropTableNameSQL($name);
1285
+        return $this->query($sql,true,"Error dropping table $name:");
1286
+    }
1287 1287
 
1288 1288
     /**
1289 1289
      * Deletes a column identified by fieldDef.
@@ -1292,13 +1292,13 @@  discard block
 block discarded – undo
1292 1292
      * @param array  $fieldDefs Vardef definition of the field
1293 1293
      * @return bool query result
1294 1294
      */
1295
-	public function deleteColumn(SugarBean $bean, $fieldDefs)
1296
-	{
1297
-		$tablename = $bean->getTableName();
1298
-		$sql = $this->dropColumnSQL($tablename, $fieldDefs);
1299
-		$msg = "Error deleting column(s) on table: $tablename:";
1300
-		return $this->query($sql,true,$msg);
1301
-	}
1295
+    public function deleteColumn(SugarBean $bean, $fieldDefs)
1296
+    {
1297
+        $tablename = $bean->getTableName();
1298
+        $sql = $this->dropColumnSQL($tablename, $fieldDefs);
1299
+        $msg = "Error deleting column(s) on table: $tablename:";
1300
+        return $this->query($sql,true,$msg);
1301
+    }
1302 1302
 
1303 1303
     /**
1304 1304
      * Generate a set of Insert statements based on the bean given
@@ -1313,233 +1313,233 @@  discard block
 block discarded – undo
1313 1313
      * @param bool $is_related_query
1314 1314
      * @return string SQL insert statement
1315 1315
      */
1316
-	public function generateInsertSQL(SugarBean $bean, $select_query, $start, $count = -1, $table = '', $is_related_query = false)
1317
-	{
1318
-		$this->log->info('call to DBManager::generateInsertSQL() is deprecated');
1319
-
1320
-		if (!$table) {
1321
-			$GLOBALS['log']->fatal('empty table name');
1322
-		}
1323
-
1324
-		global $sugar_config;
1325
-
1326
-		$rows_found = 0;
1327
-		$count_query = $bean->create_list_count_query($select_query);
1328
-		if(!empty($count_query))
1329
-		{
1330
-			// We have a count query.  Run it and get the results.
1331
-			$result = $this->query($count_query, true, "Error running count query for $this->object_name List: ");
1332
-			$assoc = $this->fetchByAssoc($result);
1333
-			if(!empty($assoc['c']))
1334
-			{
1335
-				$rows_found = $assoc['c'];
1336
-			}
1337
-		}
1338
-		if($count == -1){
1339
-			$count 	= $sugar_config['list_max_entries_per_page'];
1340
-		}
1341
-		$next_offset = $start + $count;
1342
-
1343
-		$result = $this->limitQuery($select_query, $start, $count);
1344
-		// get basic insert
1345
-		$sql = "INSERT INTO ".$table;
1346
-		$custom_sql = "INSERT INTO ".$table."_cstm";
1347
-
1348
-		// get field definitions
1349
-		$fields = $bean->getFieldDefinitions();
1350
-		$custom_fields = array();
1351
-
1352
-		if($bean->hasCustomFields()){
1353
-			foreach ($fields as $fieldDef){
1354
-				if($fieldDef['source'] == 'custom_fields'){
1355
-					$custom_fields[$fieldDef['name']] = $fieldDef['name'];
1356
-				}
1357
-			}
1358
-			if(!empty($custom_fields)){
1359
-				$custom_fields['id_c'] = 'id_c';
1360
-				$id_field = array('name' => 'id_c', 'custom_type' => 'id',);
1361
-				$fields[] = $id_field;
1362
-			}
1363
-		}
1364
-
1365
-		// get column names and values
1366
-		$row_array = array();
1367
-		$columns = array();
1368
-		$cstm_row_array = array();
1369
-		$cstm_columns = array();
1370
-		$built_columns = false;
1371
-		while(($row = $this->fetchByAssoc($result)) != null)
1372
-		{
1373
-			$values = array();
1374
-			$cstm_values = array();
1375
-			if(!$is_related_query){
1376
-				foreach ($fields as $fieldDef)
1377
-				{
1378
-					if(isset($fieldDef['source']) && $fieldDef['source'] != 'db' && $fieldDef['source'] != 'custom_fields') continue;
1379
-					$val = $row[$fieldDef['name']];
1380
-
1381
-					//handle auto increment values here only need to do this on insert not create
1382
-					if ($fieldDef['name'] == 'deleted'){
1383
-							$values['deleted'] = $val;
1384
-							if(!$built_columns){
1385
-							$columns[] = 'deleted';
1386
-						}
1387
-					}
1388
-					else
1389
-					{
1390
-						$type = $fieldDef['type'];
1391
-						if(!empty($fieldDef['custom_type'])){
1392
-							$type = $fieldDef['custom_type'];
1393
-						}
1394
-						// need to do some thing about types of values
1395
-						if($this->dbType == 'mysql' && $val == '' && ($type == 'datetime' ||  $type == 'date' || $type == 'int' || $type == 'currency' || $type == 'decimal')){
1396
-							if(!empty($custom_fields[$fieldDef['name']]))
1397
-								$cstm_values[$fieldDef['name']] = 'null';
1398
-							else
1399
-								$values[$fieldDef['name']] = 'null';
1400
-						}else{
1401
-							if(isset($type) && $type=='int') {
1402
-								if(!empty($custom_fields[$fieldDef['name']]))
1403
-									$cstm_values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1404
-								else
1405
-									$values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1406
-							} else {
1407
-								if(!empty($custom_fields[$fieldDef['name']]))
1408
-									$cstm_values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1409
-								else
1410
-									$values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1411
-							}
1412
-						}
1413
-						if(!$built_columns){
1414
-							if(!empty($custom_fields[$fieldDef['name']]))
1415
-								$cstm_columns[] = $fieldDef['name'];
1416
-							else
1417
-								$columns[] = $fieldDef['name'];
1418
-						}
1419
-					}
1420
-
1421
-				}
1422
-			} else {
1423
-			foreach ($row as $key=>$val)
1424
-			{
1425
-					if($key != 'orc_row'){
1426
-						$values[$key] = "'$val'";
1427
-						if(!$built_columns){
1428
-							$columns[] = $key;
1429
-						}
1430
-					}
1431
-			}
1432
-			}
1433
-			$built_columns = true;
1434
-			if(!empty($values)){
1435
-				$row_array[] = $values;
1436
-			}
1437
-			if(!empty($cstm_values) && !empty($cstm_values['id_c']) && (strlen($cstm_values['id_c']) > 7)){
1438
-				$cstm_row_array[] = $cstm_values;
1439
-			}
1440
-		}
1441
-
1442
-		//if (sizeof ($values) == 0) return ""; // no columns set
1443
-
1444
-		// get the entire sql
1445
-		$sql .= "(".implode(",", $columns).") ";
1446
-		$sql .= "VALUES";
1447
-		for($i = 0; $i < count($row_array); $i++){
1448
-			$sql .= " (".implode(",", $row_array[$i]).")";
1449
-			if($i < (count($row_array) - 1)){
1450
-				$sql .= ", ";
1451
-			}
1452
-		}
1453
-		//custom
1454
-		// get the entire sql
1455
-		$custom_sql .= "(".implode(",", $cstm_columns).") ";
1456
-		$custom_sql .= "VALUES";
1457
-
1458
-		for($i = 0; $i < count($cstm_row_array); $i++){
1459
-			$custom_sql .= " (".implode(",", $cstm_row_array[$i]).")";
1460
-			if($i < (count($cstm_row_array) - 1)){
1461
-				$custom_sql .= ", ";
1462
-			}
1463
-		}
1464
-		return array('data' => $sql, 'cstm_sql' => $custom_sql, /*'result_count' => $row_count, */ 'total_count' => $rows_found, 'next_offset' => $next_offset);
1465
-	}
1466
-
1467
-	/**
1468
-	 * @deprecated
1469
-	 * Disconnects all instances
1470
-	 */
1471
-	public function disconnectAll()
1472
-	{
1473
-		DBManagerFactory::disconnectAll();
1474
-	}
1475
-
1476
-	/**
1477
-	 * This function sets the query threshold limit
1478
-	 *
1479
-	 * @param int $limit value of query threshold limit
1480
-	 */
1481
-	public static function setQueryLimit($limit)
1482
-	{
1483
-		//reset the queryCount
1484
-		self::$queryCount = 0;
1485
-		self::$queryLimit = $limit;
1486
-	}
1487
-
1488
-	/**
1489
-	 * Returns the static queryCount value
1490
-	 *
1491
-	 * @return int value of the queryCount static variable
1492
-	 */
1493
-	public static function getQueryCount()
1494
-	{
1495
-		return self::$queryCount;
1496
-	}
1497
-
1498
-
1499
-	/**
1500
-	 * Resets the queryCount value to 0
1501
-	 *
1502
-	 */
1503
-	public static function resetQueryCount()
1504
-	{
1505
-		self::$queryCount = 0;
1506
-	}
1507
-
1508
-	/**
1509
-	 * This function increments the global $sql_queries variable
1510
-	 */
1511
-	public function countQuery()
1512
-	{
1513
-		if (self::$queryLimit != 0 && ++self::$queryCount > self::$queryLimit
1514
-			&&(empty($GLOBALS['current_user']) || !is_admin($GLOBALS['current_user']))) {
1316
+    public function generateInsertSQL(SugarBean $bean, $select_query, $start, $count = -1, $table = '', $is_related_query = false)
1317
+    {
1318
+        $this->log->info('call to DBManager::generateInsertSQL() is deprecated');
1319
+
1320
+        if (!$table) {
1321
+            $GLOBALS['log']->fatal('empty table name');
1322
+        }
1323
+
1324
+        global $sugar_config;
1325
+
1326
+        $rows_found = 0;
1327
+        $count_query = $bean->create_list_count_query($select_query);
1328
+        if(!empty($count_query))
1329
+        {
1330
+            // We have a count query.  Run it and get the results.
1331
+            $result = $this->query($count_query, true, "Error running count query for $this->object_name List: ");
1332
+            $assoc = $this->fetchByAssoc($result);
1333
+            if(!empty($assoc['c']))
1334
+            {
1335
+                $rows_found = $assoc['c'];
1336
+            }
1337
+        }
1338
+        if($count == -1){
1339
+            $count 	= $sugar_config['list_max_entries_per_page'];
1340
+        }
1341
+        $next_offset = $start + $count;
1342
+
1343
+        $result = $this->limitQuery($select_query, $start, $count);
1344
+        // get basic insert
1345
+        $sql = "INSERT INTO ".$table;
1346
+        $custom_sql = "INSERT INTO ".$table."_cstm";
1347
+
1348
+        // get field definitions
1349
+        $fields = $bean->getFieldDefinitions();
1350
+        $custom_fields = array();
1351
+
1352
+        if($bean->hasCustomFields()){
1353
+            foreach ($fields as $fieldDef){
1354
+                if($fieldDef['source'] == 'custom_fields'){
1355
+                    $custom_fields[$fieldDef['name']] = $fieldDef['name'];
1356
+                }
1357
+            }
1358
+            if(!empty($custom_fields)){
1359
+                $custom_fields['id_c'] = 'id_c';
1360
+                $id_field = array('name' => 'id_c', 'custom_type' => 'id',);
1361
+                $fields[] = $id_field;
1362
+            }
1363
+        }
1364
+
1365
+        // get column names and values
1366
+        $row_array = array();
1367
+        $columns = array();
1368
+        $cstm_row_array = array();
1369
+        $cstm_columns = array();
1370
+        $built_columns = false;
1371
+        while(($row = $this->fetchByAssoc($result)) != null)
1372
+        {
1373
+            $values = array();
1374
+            $cstm_values = array();
1375
+            if(!$is_related_query){
1376
+                foreach ($fields as $fieldDef)
1377
+                {
1378
+                    if(isset($fieldDef['source']) && $fieldDef['source'] != 'db' && $fieldDef['source'] != 'custom_fields') continue;
1379
+                    $val = $row[$fieldDef['name']];
1380
+
1381
+                    //handle auto increment values here only need to do this on insert not create
1382
+                    if ($fieldDef['name'] == 'deleted'){
1383
+                            $values['deleted'] = $val;
1384
+                            if(!$built_columns){
1385
+                            $columns[] = 'deleted';
1386
+                        }
1387
+                    }
1388
+                    else
1389
+                    {
1390
+                        $type = $fieldDef['type'];
1391
+                        if(!empty($fieldDef['custom_type'])){
1392
+                            $type = $fieldDef['custom_type'];
1393
+                        }
1394
+                        // need to do some thing about types of values
1395
+                        if($this->dbType == 'mysql' && $val == '' && ($type == 'datetime' ||  $type == 'date' || $type == 'int' || $type == 'currency' || $type == 'decimal')){
1396
+                            if(!empty($custom_fields[$fieldDef['name']]))
1397
+                                $cstm_values[$fieldDef['name']] = 'null';
1398
+                            else
1399
+                                $values[$fieldDef['name']] = 'null';
1400
+                        }else{
1401
+                            if(isset($type) && $type=='int') {
1402
+                                if(!empty($custom_fields[$fieldDef['name']]))
1403
+                                    $cstm_values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1404
+                                else
1405
+                                    $values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1406
+                            } else {
1407
+                                if(!empty($custom_fields[$fieldDef['name']]))
1408
+                                    $cstm_values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1409
+                                else
1410
+                                    $values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1411
+                            }
1412
+                        }
1413
+                        if(!$built_columns){
1414
+                            if(!empty($custom_fields[$fieldDef['name']]))
1415
+                                $cstm_columns[] = $fieldDef['name'];
1416
+                            else
1417
+                                $columns[] = $fieldDef['name'];
1418
+                        }
1419
+                    }
1420
+
1421
+                }
1422
+            } else {
1423
+            foreach ($row as $key=>$val)
1424
+            {
1425
+                    if($key != 'orc_row'){
1426
+                        $values[$key] = "'$val'";
1427
+                        if(!$built_columns){
1428
+                            $columns[] = $key;
1429
+                        }
1430
+                    }
1431
+            }
1432
+            }
1433
+            $built_columns = true;
1434
+            if(!empty($values)){
1435
+                $row_array[] = $values;
1436
+            }
1437
+            if(!empty($cstm_values) && !empty($cstm_values['id_c']) && (strlen($cstm_values['id_c']) > 7)){
1438
+                $cstm_row_array[] = $cstm_values;
1439
+            }
1440
+        }
1441
+
1442
+        //if (sizeof ($values) == 0) return ""; // no columns set
1443
+
1444
+        // get the entire sql
1445
+        $sql .= "(".implode(",", $columns).") ";
1446
+        $sql .= "VALUES";
1447
+        for($i = 0; $i < count($row_array); $i++){
1448
+            $sql .= " (".implode(",", $row_array[$i]).")";
1449
+            if($i < (count($row_array) - 1)){
1450
+                $sql .= ", ";
1451
+            }
1452
+        }
1453
+        //custom
1454
+        // get the entire sql
1455
+        $custom_sql .= "(".implode(",", $cstm_columns).") ";
1456
+        $custom_sql .= "VALUES";
1457
+
1458
+        for($i = 0; $i < count($cstm_row_array); $i++){
1459
+            $custom_sql .= " (".implode(",", $cstm_row_array[$i]).")";
1460
+            if($i < (count($cstm_row_array) - 1)){
1461
+                $custom_sql .= ", ";
1462
+            }
1463
+        }
1464
+        return array('data' => $sql, 'cstm_sql' => $custom_sql, /*'result_count' => $row_count, */ 'total_count' => $rows_found, 'next_offset' => $next_offset);
1465
+    }
1466
+
1467
+    /**
1468
+     * @deprecated
1469
+     * Disconnects all instances
1470
+     */
1471
+    public function disconnectAll()
1472
+    {
1473
+        DBManagerFactory::disconnectAll();
1474
+    }
1475
+
1476
+    /**
1477
+     * This function sets the query threshold limit
1478
+     *
1479
+     * @param int $limit value of query threshold limit
1480
+     */
1481
+    public static function setQueryLimit($limit)
1482
+    {
1483
+        //reset the queryCount
1484
+        self::$queryCount = 0;
1485
+        self::$queryLimit = $limit;
1486
+    }
1487
+
1488
+    /**
1489
+     * Returns the static queryCount value
1490
+     *
1491
+     * @return int value of the queryCount static variable
1492
+     */
1493
+    public static function getQueryCount()
1494
+    {
1495
+        return self::$queryCount;
1496
+    }
1497
+
1498
+
1499
+    /**
1500
+     * Resets the queryCount value to 0
1501
+     *
1502
+     */
1503
+    public static function resetQueryCount()
1504
+    {
1505
+        self::$queryCount = 0;
1506
+    }
1507
+
1508
+    /**
1509
+     * This function increments the global $sql_queries variable
1510
+     */
1511
+    public function countQuery()
1512
+    {
1513
+        if (self::$queryLimit != 0 && ++self::$queryCount > self::$queryLimit
1514
+            &&(empty($GLOBALS['current_user']) || !is_admin($GLOBALS['current_user']))) {
1515 1515
             require_once('include/resource/ResourceManager.php');
1516 1516
             $resourceManager = ResourceManager::getInstance();
1517 1517
             $resourceManager->notifyObservers('ERR_QUERY_LIMIT');
1518
-		}
1519
-	}
1518
+        }
1519
+    }
1520
+
1521
+    /**
1522
+     * Pre-process string for quoting
1523
+     * @internal
1524
+     * @param string $string
1525
+     * @return string
1526
+     */
1527
+    protected function quoteInternal($string)
1528
+    {
1529
+        return from_html($string);
1530
+    }
1520 1531
 
1521
-	/**
1522
-	 * Pre-process string for quoting
1523
-	 * @internal
1524
-	 * @param string $string
1532
+    /**
1533
+     * Return string properly quoted with ''
1534
+     * @param string $string
1525 1535
      * @return string
1526 1536
      */
1527
-	protected function quoteInternal($string)
1528
-	{
1529
-		return from_html($string);
1530
-	}
1531
-
1532
-	/**
1533
-	 * Return string properly quoted with ''
1534
-	 * @param string $string
1535
-	 * @return string
1536
-	 */
1537
-	public function quoted($string)
1538
-	{
1539
-		return "'".$this->quote($string)."'";
1540
-	}
1541
-
1542
-	/**
1537
+    public function quoted($string)
1538
+    {
1539
+        return "'".$this->quote($string)."'";
1540
+    }
1541
+
1542
+    /**
1543 1543
      * Quote value according to type
1544 1544
      * Numerics aren't quoted
1545 1545
      * Dates are converted and quoted
@@ -1549,13 +1549,13 @@  discard block
 block discarded – undo
1549 1549
      * @return string Quoted value
1550 1550
      */
1551 1551
     public function quoteType($type, $value)
1552
-	{
1553
-	    if($type == 'date') {
1554
-	        return $this->convert($this->quoted($value), "date");
1555
-	    }
1556
-	    if($type == 'time') {
1557
-	        return $this->convert($this->quoted($value), "time");
1558
-	    }
1552
+    {
1553
+        if($type == 'date') {
1554
+            return $this->convert($this->quoted($value), "date");
1555
+        }
1556
+        if($type == 'time') {
1557
+            return $this->convert($this->quoted($value), "time");
1558
+        }
1559 1559
         if(isset($this->type_class[$type]) &&  $this->type_class[$type] == "date") {
1560 1560
             return $this->convert($this->quoted($value), "datetime");
1561 1561
         }
@@ -1564,7 +1564,7 @@  discard block
 block discarded – undo
1564 1564
         }
1565 1565
 
1566 1566
         return $this->quoted($value);
1567
-	}
1567
+    }
1568 1568
 
1569 1569
     /**
1570 1570
      * Quote the strings of the passed in array
@@ -1574,177 +1574,177 @@  discard block
 block discarded – undo
1574 1574
      * @param array $array
1575 1575
      * @return array Quoted strings
1576 1576
      */
1577
-	public function arrayQuote(array &$array)
1578
-	{
1579
-		foreach($array as &$val) {
1580
-			$val = $this->quote($val);
1581
-		}
1582
-		return $array;
1583
-	}
1577
+    public function arrayQuote(array &$array)
1578
+    {
1579
+        foreach($array as &$val) {
1580
+            $val = $this->quote($val);
1581
+        }
1582
+        return $array;
1583
+    }
1584 1584
 
1585 1585
     /**
1586 1586
      * Frees out previous results
1587 1587
      *
1588 1588
      * @param resource|bool $result optional, pass if you want to free a single result instead of all results
1589 1589
      */
1590
-	protected function freeResult($result = false)
1591
-	{
1592
-		if($result) {
1593
-			$this->freeDbResult($result);
1594
-		}
1595
-		if($this->lastResult) {
1596
-			$this->freeDbResult($this->lastResult);
1597
-			$this->lastResult = null;
1598
-		}
1599
-	}
1600
-
1601
-	/**
1602
-	 * @abstract
1603
-	 * Check if query has LIMIT clause
1604
-	 * Relevant for now only for Mysql
1605
-	 * @param string $sql
1606
-	 * @return bool
1607
-	 */
1608
-	protected function hasLimit($sql)
1609
-	{
1610
-	    return false;
1611
-	}
1612
-
1613
-	/**
1614
-	 * Runs a query and returns a single row containing single value
1615
-	 *
1616
-	 * @param  string   $sql        SQL Statement to execute
1617
-	 * @param  bool     $dieOnError True if we want to call die if the query returns errors
1618
-	 * @param  string   $msg        Message to log if error occurs
1619
-	 * @return array    single value from the query
1620
-	 */
1621
-	public function getOne($sql, $dieOnError = false, $msg = '')
1622
-	{
1623
-		$this->log->info("Get One: |$sql|");
1624
-		if(!$this->hasLimit($sql)) {
1625
-		    $queryresult = $this->limitQuery($sql, 0, 1, $dieOnError, $msg);
1626
-		} else {
1627
-		    // support old code that passes LIMIT to sql
1628
-		    // works only for mysql, so do not rely on this
1629
-		    $queryresult = $this->query($sql, $dieOnError, $msg);
1630
-		}
1631
-		$this->checkError($msg.' Get One Failed:' . $sql, $dieOnError);
1632
-		if (!$queryresult) return false;
1633
-		$row = $this->fetchByAssoc($queryresult);
1634
-		if(!empty($row)) {
1635
-			return array_shift($row);
1636
-		}
1637
-		return false;
1638
-	}
1639
-
1640
-	/**
1641
-	 * Runs a query and returns a single row
1642
-	 *
1643
-	 * @param  string   $sql        SQL Statement to execute
1644
-	 * @param  bool     $dieOnError True if we want to call die if the query returns errors
1645
-	 * @param  string   $msg        Message to log if error occurs
1646
-	 * @param  bool     $suppress   Message to log if error occurs
1647
-	 * @return array    single row from the query
1648
-	 */
1649
-	public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false)
1650
-	{
1651
-		$this->log->info("Fetch One: |$sql|");
1652
-		$this->checkConnection();
1653
-		$queryresult = $this->query($sql, $dieOnError, $msg);
1654
-		$this->checkError($msg.' Fetch One Failed:' . $sql, $dieOnError);
1655
-
1656
-		if (!$queryresult) return false;
1657
-
1658
-		$row = $this->fetchByAssoc($queryresult);
1659
-		if ( !$row ) return false;
1660
-
1661
-		$this->freeResult($queryresult);
1662
-		return $row;
1663
-	}
1590
+    protected function freeResult($result = false)
1591
+    {
1592
+        if($result) {
1593
+            $this->freeDbResult($result);
1594
+        }
1595
+        if($this->lastResult) {
1596
+            $this->freeDbResult($this->lastResult);
1597
+            $this->lastResult = null;
1598
+        }
1599
+    }
1664 1600
 
1665 1601
     /**
1666
-     * Returns the number of rows affected by the last query
1667 1602
      * @abstract
1668
-	 * See also affected_rows capability, will return 0 unless the DB supports it
1669
-     * @param resource $result query result resource
1670
-     * @return int
1603
+     * Check if query has LIMIT clause
1604
+     * Relevant for now only for Mysql
1605
+     * @param string $sql
1606
+     * @return bool
1607
+     */
1608
+    protected function hasLimit($sql)
1609
+    {
1610
+        return false;
1611
+    }
1612
+
1613
+    /**
1614
+     * Runs a query and returns a single row containing single value
1615
+     *
1616
+     * @param  string   $sql        SQL Statement to execute
1617
+     * @param  bool     $dieOnError True if we want to call die if the query returns errors
1618
+     * @param  string   $msg        Message to log if error occurs
1619
+     * @return array    single value from the query
1620
+     */
1621
+    public function getOne($sql, $dieOnError = false, $msg = '')
1622
+    {
1623
+        $this->log->info("Get One: |$sql|");
1624
+        if(!$this->hasLimit($sql)) {
1625
+            $queryresult = $this->limitQuery($sql, 0, 1, $dieOnError, $msg);
1626
+        } else {
1627
+            // support old code that passes LIMIT to sql
1628
+            // works only for mysql, so do not rely on this
1629
+            $queryresult = $this->query($sql, $dieOnError, $msg);
1630
+        }
1631
+        $this->checkError($msg.' Get One Failed:' . $sql, $dieOnError);
1632
+        if (!$queryresult) return false;
1633
+        $row = $this->fetchByAssoc($queryresult);
1634
+        if(!empty($row)) {
1635
+            return array_shift($row);
1636
+        }
1637
+        return false;
1638
+    }
1639
+
1640
+    /**
1641
+     * Runs a query and returns a single row
1642
+     *
1643
+     * @param  string   $sql        SQL Statement to execute
1644
+     * @param  bool     $dieOnError True if we want to call die if the query returns errors
1645
+     * @param  string   $msg        Message to log if error occurs
1646
+     * @param  bool     $suppress   Message to log if error occurs
1647
+     * @return array    single row from the query
1671 1648
      */
1672
-	public function getAffectedRowCount($result)
1673
-	{
1674
-		return 0;
1675
-	}
1676
-
1677
-	/**
1678
-	 * Returns the number of rows returned by the result
1679
-	 *
1680
-	 * This function can't be reliably implemented on most DB, do not use it.
1681
-	 * @abstract
1682
-	 * @deprecated
1683
-	 * @param  resource $result
1684
-	 * @return int
1685
-	 */
1686
-	public function getRowCount($result)
1687
-	{
1688
-	    return 0;
1689
-	}
1690
-
1691
-	/**
1649
+    public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false)
1650
+    {
1651
+        $this->log->info("Fetch One: |$sql|");
1652
+        $this->checkConnection();
1653
+        $queryresult = $this->query($sql, $dieOnError, $msg);
1654
+        $this->checkError($msg.' Fetch One Failed:' . $sql, $dieOnError);
1655
+
1656
+        if (!$queryresult) return false;
1657
+
1658
+        $row = $this->fetchByAssoc($queryresult);
1659
+        if ( !$row ) return false;
1660
+
1661
+        $this->freeResult($queryresult);
1662
+        return $row;
1663
+    }
1664
+
1665
+    /**
1666
+     * Returns the number of rows affected by the last query
1667
+     * @abstract
1668
+     * See also affected_rows capability, will return 0 unless the DB supports it
1669
+     * @param resource $result query result resource
1670
+     * @return int
1671
+     */
1672
+    public function getAffectedRowCount($result)
1673
+    {
1674
+        return 0;
1675
+    }
1676
+
1677
+    /**
1678
+     * Returns the number of rows returned by the result
1679
+     *
1680
+     * This function can't be reliably implemented on most DB, do not use it.
1681
+     * @abstract
1682
+     * @deprecated
1683
+     * @param  resource $result
1684
+     * @return int
1685
+     */
1686
+    public function getRowCount($result)
1687
+    {
1688
+        return 0;
1689
+    }
1690
+
1691
+    /**
1692 1692
      * Get table description
1693 1693
      * @param string $tablename
1694 1694
      * @param bool $reload true means load from DB, false allows using cache
1695 1695
      * @return array Vardef-format table description
1696 1696
      *
1697 1697
      */
1698
-	public function getTableDescription($tablename, $reload = false)
1699
-	{
1700
-		if($reload || empty(self::$table_descriptions[$tablename])) {
1701
-			self::$table_descriptions[$tablename] = $this->get_columns($tablename);
1702
-		}
1703
-		return self::$table_descriptions[$tablename];
1704
-	}
1705
-
1706
-	/**
1707
-	 * Returns the field description for a given field in table
1708
-	 *
1709
-	 * @param  string $name
1710
-	 * @param  string $tablename
1711
-	 * @return array
1712
-	 */
1713
-	protected function describeField($name, $tablename)
1714
-	{
1715
-		$table = $this->getTableDescription($tablename);
1716
-		if(!empty($table) && isset($table[$name]))
1717
-			return 	$table[$name];
1718
-
1719
-		$table = $this->getTableDescription($tablename, true);
1720
-
1721
-		if(isset($table[$name]))
1722
-		return $table[$name];
1723
-
1724
-		return array();
1725
-	}
1726
-
1727
-	/**
1728
-	 * Returns the index description for a given index in table
1729
-	 *
1730
-	 * @param  string $name
1731
-	 * @param  string $tablename
1732
-	 * @return array
1733
-	 */
1734
-	protected function describeIndex($name, $tablename)
1735
-	{
1736
-		if(isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename][$name])){
1737
-			return 	self::$index_descriptions[$tablename][$name];
1738
-		}
1739
-
1740
-		self::$index_descriptions[$tablename] = $this->get_indices($tablename);
1741
-
1742
-		if(isset(self::$index_descriptions[$tablename][$name])){
1743
-			return 	self::$index_descriptions[$tablename][$name];
1744
-		}
1745
-
1746
-		return array();
1747
-	}
1698
+    public function getTableDescription($tablename, $reload = false)
1699
+    {
1700
+        if($reload || empty(self::$table_descriptions[$tablename])) {
1701
+            self::$table_descriptions[$tablename] = $this->get_columns($tablename);
1702
+        }
1703
+        return self::$table_descriptions[$tablename];
1704
+    }
1705
+
1706
+    /**
1707
+     * Returns the field description for a given field in table
1708
+     *
1709
+     * @param  string $name
1710
+     * @param  string $tablename
1711
+     * @return array
1712
+     */
1713
+    protected function describeField($name, $tablename)
1714
+    {
1715
+        $table = $this->getTableDescription($tablename);
1716
+        if(!empty($table) && isset($table[$name]))
1717
+            return 	$table[$name];
1718
+
1719
+        $table = $this->getTableDescription($tablename, true);
1720
+
1721
+        if(isset($table[$name]))
1722
+        return $table[$name];
1723
+
1724
+        return array();
1725
+    }
1726
+
1727
+    /**
1728
+     * Returns the index description for a given index in table
1729
+     *
1730
+     * @param  string $name
1731
+     * @param  string $tablename
1732
+     * @return array
1733
+     */
1734
+    protected function describeIndex($name, $tablename)
1735
+    {
1736
+        if(isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename][$name])){
1737
+            return 	self::$index_descriptions[$tablename][$name];
1738
+        }
1739
+
1740
+        self::$index_descriptions[$tablename] = $this->get_indices($tablename);
1741
+
1742
+        if(isset(self::$index_descriptions[$tablename][$name])){
1743
+            return 	self::$index_descriptions[$tablename][$name];
1744
+        }
1745
+
1746
+        return array();
1747
+    }
1748 1748
 
1749 1749
     /**
1750 1750
      * Truncates a string to a given length
@@ -1754,14 +1754,14 @@  discard block
 block discarded – undo
1754 1754
      * @return string
1755 1755
      *
1756 1756
      */
1757
-	public function truncate($string, $len)
1758
-	{
1759
-		if ( is_numeric($len) && $len > 0)
1760
-		{
1761
-			$string = mb_substr($string,0,(int) $len, "UTF-8");
1762
-		}
1763
-		return $string;
1764
-	}
1757
+    public function truncate($string, $len)
1758
+    {
1759
+        if ( is_numeric($len) && $len > 0)
1760
+        {
1761
+            $string = mb_substr($string,0,(int) $len, "UTF-8");
1762
+        }
1763
+        return $string;
1764
+    }
1765 1765
 
1766 1766
     /**
1767 1767
      * Returns the database string needed for concatinating multiple database strings together
@@ -1771,121 +1771,121 @@  discard block
 block discarded – undo
1771 1771
      * @param string $space Separator between strings, default is single space
1772 1772
      * @return string
1773 1773
      */
1774
-	public function concat($table, array $fields, $space = ' ')
1775
-	{
1776
-		if(empty($fields)) return '';
1777
-		$elems = array();
1778
-		$space = $this->quoted($space);
1779
-		foreach ( $fields as $field ) {
1780
-			if(!empty($elems)) $elems[] = $space;
1781
-			$elems[] = $this->convert("$table.$field", 'IFNULL', array("''"));
1782
-		}
1783
-		$first = array_shift($elems);
1784
-		return "LTRIM(RTRIM(".$this->convert($first, 'CONCAT', $elems)."))";
1785
-	}
1786
-
1787
-	/**
1788
-	 * Given a sql stmt attempt to parse it into the sql and the tokens. Then return the index of this prepared statement
1789
-	 * Tokens can come in the following forms:
1790
-	 * ? - a scalar which will be quoted
1791
-	 * ! - a literal which will not be quoted
1792
-	 * & - binary data to read from a file
1793
-	 *
1794
-	 * @param  string	$sql        The sql to parse
1795
-	 * @return int index of the prepared statement to be used with execute
1796
-	 */
1797
-	public function prepareQuery($sql)
1798
-	{
1799
-		//parse out the tokens
1800
-		$tokens = preg_split('/((?<!\\\)[&?!])/', $sql, -1, PREG_SPLIT_DELIM_CAPTURE);
1801
-
1802
-		//maintain a count of the actual tokens for quick reference in execute
1803
-		$count = 0;
1804
-
1805
-		$sqlStr = '';
1806
-		foreach ($tokens as $key => $val) {
1807
-			switch ($val) {
1808
-				case '?' :
1809
-				case '!' :
1810
-				case '&' :
1811
-					$count++;
1812
-					$sqlStr .= '?';
1813
-					break;
1814
-
1815
-				default :
1816
-					//escape any special characters
1817
-					$tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val);
1818
-					$sqlStr .= $tokens[$key];
1819
-					break;
1820
-			} // switch
1821
-		} // foreach
1822
-
1823
-		$this->preparedTokens[] = array('tokens' => $tokens, 'tokenCount' => $count, 'sqlString' => $sqlStr);
1824
-		end($this->preparedTokens);
1825
-		return key($this->preparedTokens);
1826
-	}
1827
-
1828
-	/**
1829
-	 * Takes a prepared stmt index and the data to replace and creates the query and runs it.
1830
-	 *
1831
-	 * @param  int		$stmt       The index of the prepared statement from preparedTokens
1832
-	 * @param  array    $data 		The array of data to replace the tokens with.
1833
-	 * @return resource result set or false on error
1834
-	 */
1835
-	public function executePreparedQuery($stmt, $data = array())
1836
-	{
1837
-		if(!empty($this->preparedTokens[$stmt])){
1838
-			if(!is_array($data)){
1839
-				$data = array($data);
1840
-			}
1841
-
1842
-			$pTokens = $this->preparedTokens[$stmt];
1843
-
1844
-			//ensure that the number of data elements matches the number of replacement tokens
1845
-			//we found in prepare().
1846
-			if(count($data) != $pTokens['tokenCount']){
1847
-				//error the data count did not match the token count
1848
-				return false;
1849
-			}
1850
-
1851
-			$query = '';
1852
-			$dataIndex = 0;
1853
-			$tokens = $pTokens['tokens'];
1854
-			foreach ($tokens as $val) {
1855
-				switch ($val) {
1856
-					case '?':
1857
-						$query .= $this->quote($data[$dataIndex++]);
1858
-						break;
1859
-					case '&':
1860
-						$filename = $data[$dataIndex++];
1861
-						$query .= file_get_contents($filename);
1862
-						break;
1863
-					case '!':
1864
-						$query .= $data[$dataIndex++];
1865
-						break;
1866
-					default:
1867
-						$query .= $val;
1868
-						break;
1869
-				}//switch
1870
-			}//foreach
1871
-			return $this->query($query);
1872
-		}else{
1873
-			return false;
1874
-		}
1875
-	}
1876
-
1877
-	/**
1878
-	 * Run both prepare and execute without the client having to run both individually.
1879
-	 *
1880
-	 * @param  string	$sql        The sql to parse
1881
-	 * @param  array    $data 		The array of data to replace the tokens with.
1882
-	 * @return resource result set or false on error
1883
-	 */
1884
-	public function pQuery($sql, $data = array())
1885
-	{
1886
-		$stmt = $this->prepareQuery($sql);
1887
-		return $this->executePreparedQuery($stmt, $data);
1888
-	}
1774
+    public function concat($table, array $fields, $space = ' ')
1775
+    {
1776
+        if(empty($fields)) return '';
1777
+        $elems = array();
1778
+        $space = $this->quoted($space);
1779
+        foreach ( $fields as $field ) {
1780
+            if(!empty($elems)) $elems[] = $space;
1781
+            $elems[] = $this->convert("$table.$field", 'IFNULL', array("''"));
1782
+        }
1783
+        $first = array_shift($elems);
1784
+        return "LTRIM(RTRIM(".$this->convert($first, 'CONCAT', $elems)."))";
1785
+    }
1786
+
1787
+    /**
1788
+     * Given a sql stmt attempt to parse it into the sql and the tokens. Then return the index of this prepared statement
1789
+     * Tokens can come in the following forms:
1790
+     * ? - a scalar which will be quoted
1791
+     * ! - a literal which will not be quoted
1792
+     * & - binary data to read from a file
1793
+     *
1794
+     * @param  string	$sql        The sql to parse
1795
+     * @return int index of the prepared statement to be used with execute
1796
+     */
1797
+    public function prepareQuery($sql)
1798
+    {
1799
+        //parse out the tokens
1800
+        $tokens = preg_split('/((?<!\\\)[&?!])/', $sql, -1, PREG_SPLIT_DELIM_CAPTURE);
1801
+
1802
+        //maintain a count of the actual tokens for quick reference in execute
1803
+        $count = 0;
1804
+
1805
+        $sqlStr = '';
1806
+        foreach ($tokens as $key => $val) {
1807
+            switch ($val) {
1808
+                case '?' :
1809
+                case '!' :
1810
+                case '&' :
1811
+                    $count++;
1812
+                    $sqlStr .= '?';
1813
+                    break;
1814
+
1815
+                default :
1816
+                    //escape any special characters
1817
+                    $tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val);
1818
+                    $sqlStr .= $tokens[$key];
1819
+                    break;
1820
+            } // switch
1821
+        } // foreach
1822
+
1823
+        $this->preparedTokens[] = array('tokens' => $tokens, 'tokenCount' => $count, 'sqlString' => $sqlStr);
1824
+        end($this->preparedTokens);
1825
+        return key($this->preparedTokens);
1826
+    }
1827
+
1828
+    /**
1829
+     * Takes a prepared stmt index and the data to replace and creates the query and runs it.
1830
+     *
1831
+     * @param  int		$stmt       The index of the prepared statement from preparedTokens
1832
+     * @param  array    $data 		The array of data to replace the tokens with.
1833
+     * @return resource result set or false on error
1834
+     */
1835
+    public function executePreparedQuery($stmt, $data = array())
1836
+    {
1837
+        if(!empty($this->preparedTokens[$stmt])){
1838
+            if(!is_array($data)){
1839
+                $data = array($data);
1840
+            }
1841
+
1842
+            $pTokens = $this->preparedTokens[$stmt];
1843
+
1844
+            //ensure that the number of data elements matches the number of replacement tokens
1845
+            //we found in prepare().
1846
+            if(count($data) != $pTokens['tokenCount']){
1847
+                //error the data count did not match the token count
1848
+                return false;
1849
+            }
1850
+
1851
+            $query = '';
1852
+            $dataIndex = 0;
1853
+            $tokens = $pTokens['tokens'];
1854
+            foreach ($tokens as $val) {
1855
+                switch ($val) {
1856
+                    case '?':
1857
+                        $query .= $this->quote($data[$dataIndex++]);
1858
+                        break;
1859
+                    case '&':
1860
+                        $filename = $data[$dataIndex++];
1861
+                        $query .= file_get_contents($filename);
1862
+                        break;
1863
+                    case '!':
1864
+                        $query .= $data[$dataIndex++];
1865
+                        break;
1866
+                    default:
1867
+                        $query .= $val;
1868
+                        break;
1869
+                }//switch
1870
+            }//foreach
1871
+            return $this->query($query);
1872
+        }else{
1873
+            return false;
1874
+        }
1875
+    }
1876
+
1877
+    /**
1878
+     * Run both prepare and execute without the client having to run both individually.
1879
+     *
1880
+     * @param  string	$sql        The sql to parse
1881
+     * @param  array    $data 		The array of data to replace the tokens with.
1882
+     * @return resource result set or false on error
1883
+     */
1884
+    public function pQuery($sql, $data = array())
1885
+    {
1886
+        $stmt = $this->prepareQuery($sql);
1887
+        return $this->executePreparedQuery($stmt, $data);
1888
+    }
1889 1889
 
1890 1890
 /********************** SQL FUNCTIONS ****************************/
1891 1891
     /**
@@ -1895,938 +1895,938 @@  discard block
 block discarded – undo
1895 1895
      * @param SugarBean $bean SugarBean instance
1896 1896
      * @return string SQL Create Table statement
1897 1897
      */
1898
-	public function createTableSQL(SugarBean $bean)
1899
-	{
1900
-		$tablename = $bean->getTableName();
1901
-		$fieldDefs = $bean->getFieldDefinitions();
1902
-		$indices = $bean->getIndices();
1903
-		return $this->createTableSQLParams($tablename, $fieldDefs, $indices);
1904
-	}
1905
-
1906
-	/**
1907
-	 * Generates SQL for insert statement.
1908
-	 *
1909
-	 * @param  SugarBean $bean SugarBean instance
1910
-	 * @return string SQL Create Table statement
1911
-	 */
1912
-	public function insertSQL(SugarBean $bean)
1913
-	{
1914
-		// get column names and values
1915
-		$sql = $this->insertParams($bean->getTableName(), $bean->getFieldDefinitions(), get_object_vars($bean),
1916
-		        isset($bean->field_name_map)?$bean->field_name_map:null, false);
1917
-		return $sql;
1918
-	}
1919
-
1920
-	/**
1921
-	 * Generates SQL for update statement.
1922
-	 *
1923
-	 * @param  SugarBean $bean SugarBean instance
1924
-	 * @param  array  $where Optional, where conditions in an array
1925
-	 * @return string SQL Create Table statement
1926
-	 */
1927
-	public function updateSQL(SugarBean $bean, array $where = array())
1928
-	{
1929
-		$primaryField = $bean->getPrimaryFieldDefinition();
1930
-		$columns = array();
1898
+    public function createTableSQL(SugarBean $bean)
1899
+    {
1900
+        $tablename = $bean->getTableName();
1901
+        $fieldDefs = $bean->getFieldDefinitions();
1902
+        $indices = $bean->getIndices();
1903
+        return $this->createTableSQLParams($tablename, $fieldDefs, $indices);
1904
+    }
1905
+
1906
+    /**
1907
+     * Generates SQL for insert statement.
1908
+     *
1909
+     * @param  SugarBean $bean SugarBean instance
1910
+     * @return string SQL Create Table statement
1911
+     */
1912
+    public function insertSQL(SugarBean $bean)
1913
+    {
1914
+        // get column names and values
1915
+        $sql = $this->insertParams($bean->getTableName(), $bean->getFieldDefinitions(), get_object_vars($bean),
1916
+                isset($bean->field_name_map)?$bean->field_name_map:null, false);
1917
+        return $sql;
1918
+    }
1919
+
1920
+    /**
1921
+     * Generates SQL for update statement.
1922
+     *
1923
+     * @param  SugarBean $bean SugarBean instance
1924
+     * @param  array  $where Optional, where conditions in an array
1925
+     * @return string SQL Create Table statement
1926
+     */
1927
+    public function updateSQL(SugarBean $bean, array $where = array())
1928
+    {
1929
+        $primaryField = $bean->getPrimaryFieldDefinition();
1930
+        $columns = array();
1931 1931
         $fields = $bean->getFieldDefinitions();
1932
-		// get column names and values
1933
-		foreach ($fields as $field => $fieldDef) {
1934
-			if (isset($fieldDef['source']) && $fieldDef['source'] != 'db')  continue;
1935
-			// Do not write out the id field on the update statement.
1936
-    		// We are not allowed to change ids.
1937
-    		if (empty($fieldDef['name']) || $fieldDef['name'] == $primaryField['name']) continue;
1938
-
1939
-    		// If the field is an auto_increment field, then we shouldn't be setting it.  This was added
1940
-    		// specially for Bugs and Cases which have a number associated with them.
1941
-    		if (!empty($bean->field_name_map[$field]['auto_increment'])) continue;
1942
-
1943
-    		//custom fields handle their save separately
1944
-    		if(isset($bean->field_name_map) && !empty($bean->field_name_map[$field]['custom_type']))  continue;
1945
-
1946
-    		// no need to clear deleted since we only update not deleted records anyway
1947
-    		if($fieldDef['name'] == 'deleted' && empty($bean->deleted)) continue;
1948
-
1949
-    		if(isset($bean->$field)) {
1950
-    			$val = from_html($bean->$field);
1951
-    		} else {
1952
-    			continue;
1953
-    		}
1954
-
1955
-    		if(!empty($fieldDef['type']) && $fieldDef['type'] == 'bool'){
1956
-    			$val = $bean->getFieldValue($field);
1957
-    		}
1958
-
1959
-    		if(strlen($val) == 0) {
1960
-    			if(isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) {
1961
-    				$val = $fieldDef['default'];
1962
-    			} else {
1963
-    				$val = null;
1964
-    			}
1965
-    		}
1966
-
1967
-    		if(!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) {
1968
-			    $val = $this->truncate($val, $fieldDef['len']);
1969
-			}
1970
-		$columnName = $this->quoteIdentifier($fieldDef['name']);
1971
-    		if(!is_null($val) || !empty($fieldDef['required'])) {
1972
-    			$columns[] = "{$columnName}=".$this->massageValue($val, $fieldDef);
1973
-    		} elseif($this->isNullable($fieldDef)) {
1974
-    			$columns[] = "{$columnName}=NULL";
1975
-    		} else {
1976
-    		    $columns[] = "{$columnName}=".$this->emptyValue($fieldDef['type']);
1977
-    		}
1978
-		}
1979
-
1980
-		if ( sizeof($columns) == 0 )
1981
-			return ""; // no columns set
1982
-
1983
-		// build where clause
1984
-		$where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
1985
-		if(isset($fields['deleted'])) {
1986
-		    $where .= " AND deleted=0";
1987
-		}
1988
-
1989
-		return "UPDATE ".$bean->getTableName()."
1932
+        // get column names and values
1933
+        foreach ($fields as $field => $fieldDef) {
1934
+            if (isset($fieldDef['source']) && $fieldDef['source'] != 'db')  continue;
1935
+            // Do not write out the id field on the update statement.
1936
+            // We are not allowed to change ids.
1937
+            if (empty($fieldDef['name']) || $fieldDef['name'] == $primaryField['name']) continue;
1938
+
1939
+            // If the field is an auto_increment field, then we shouldn't be setting it.  This was added
1940
+            // specially for Bugs and Cases which have a number associated with them.
1941
+            if (!empty($bean->field_name_map[$field]['auto_increment'])) continue;
1942
+
1943
+            //custom fields handle their save separately
1944
+            if(isset($bean->field_name_map) && !empty($bean->field_name_map[$field]['custom_type']))  continue;
1945
+
1946
+            // no need to clear deleted since we only update not deleted records anyway
1947
+            if($fieldDef['name'] == 'deleted' && empty($bean->deleted)) continue;
1948
+
1949
+            if(isset($bean->$field)) {
1950
+                $val = from_html($bean->$field);
1951
+            } else {
1952
+                continue;
1953
+            }
1954
+
1955
+            if(!empty($fieldDef['type']) && $fieldDef['type'] == 'bool'){
1956
+                $val = $bean->getFieldValue($field);
1957
+            }
1958
+
1959
+            if(strlen($val) == 0) {
1960
+                if(isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) {
1961
+                    $val = $fieldDef['default'];
1962
+                } else {
1963
+                    $val = null;
1964
+                }
1965
+            }
1966
+
1967
+            if(!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) {
1968
+                $val = $this->truncate($val, $fieldDef['len']);
1969
+            }
1970
+        $columnName = $this->quoteIdentifier($fieldDef['name']);
1971
+            if(!is_null($val) || !empty($fieldDef['required'])) {
1972
+                $columns[] = "{$columnName}=".$this->massageValue($val, $fieldDef);
1973
+            } elseif($this->isNullable($fieldDef)) {
1974
+                $columns[] = "{$columnName}=NULL";
1975
+            } else {
1976
+                $columns[] = "{$columnName}=".$this->emptyValue($fieldDef['type']);
1977
+            }
1978
+        }
1979
+
1980
+        if ( sizeof($columns) == 0 )
1981
+            return ""; // no columns set
1982
+
1983
+        // build where clause
1984
+        $where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
1985
+        if(isset($fields['deleted'])) {
1986
+            $where .= " AND deleted=0";
1987
+        }
1988
+
1989
+        return "UPDATE ".$bean->getTableName()."
1990 1990
 					SET ".implode(",", $columns)."
1991 1991
 					$where";
1992
-	}
1993
-
1994
-	/**
1995
-	 * This method returns a where array so that it has id entry if
1996
-	 * where is not an array or is empty
1997
-	 *
1998
-	 * @param  SugarBean $bean SugarBean instance
1999
-	 * @param  array  $where Optional, where conditions in an array
2000
-	 * @return array
2001
-	 */
2002
-	protected function updateWhereArray(SugarBean $bean, array $where = array())
2003
-	{
2004
-		if (count($where) == 0) {
2005
-			$fieldDef = $bean->getPrimaryFieldDefinition();
2006
-			$primaryColumn = $fieldDef['name'];
2007
-
2008
-			$val = $bean->getFieldValue($fieldDef['name']);
2009
-			if ($val != FALSE){
2010
-				$where[$primaryColumn] = $val;
2011
-			}
2012
-		}
2013
-
2014
-		return $where;
2015
-	}
2016
-
2017
-	/**
2018
-	 * Returns a where clause without the 'where' key word
2019
-	 *
2020
-	 * The clause returned does not have an 'and' at the beginning and the columns
2021
-	 * are joined by 'and'.
2022
-	 *
2023
-	 * @param  string $table table name
2024
-	 * @param  array  $whereArray Optional, where conditions in an array
2025
-	 * @return string
2026
-	 */
2027
-	protected function getColumnWhereClause($table, array $whereArray = array())
2028
-	{
2029
-		$where = array();
2030
-		foreach ($whereArray as $name => $val) {
2031
-			$op = "=";
2032
-			if (is_array($val)) {
2033
-				$op = "IN";
2034
-				$temp = array();
2035
-				foreach ($val as $tval){
2036
-					$temp[] = $this->quoted($tval);
2037
-				}
2038
-				$val = implode(",", $temp);
2039
-				$val = "($val)";
2040
-			} else {
2041
-				$val = $this->quoted($val);
2042
-			}
2043
-
2044
-			$where[] = " $table.$name $op $val";
2045
-		}
2046
-
2047
-		if (!empty($where))
2048
-			return implode(" AND ", $where);
2049
-
2050
-		return '';
2051
-	}
2052
-
2053
-	/**
2054
-	 * This method returns a complete where clause built from the
2055
-	 * where values specified.
2056
-	 *
2057
-	 * @param  SugarBean $bean SugarBean that describes the table
2058
-	 * @param  array  $whereArray Optional, where conditions in an array
2059
-	 * @return string
2060
-	 */
2061
-	protected function getWhereClause(SugarBean $bean, array $whereArray=array())
2062
-	{
2063
-	    return " WHERE " . $this->getColumnWhereClause($bean->getTableName(), $whereArray);
2064
-	}
2065
-
2066
-	/**
2067
-	 * Outputs a correct string for the sql statement according to value
2068
-	 *
2069
-	 * @param  mixed $val
2070
-	 * @param  array $fieldDef field definition
2071
-	 * @return mixed
2072
-	 */
2073
-	public function massageValue($val, $fieldDef)
2074
-	{
2075
-		$type = $this->getFieldType($fieldDef);
2076
-
2077
-		if(isset($this->type_class[$type])) {
2078
-			// handle some known types
2079
-			switch($this->type_class[$type]) {
2080
-				case 'bool':
2081
-				case 'int':
2082
-					if (!empty($fieldDef['required']) && $val == ''){
2083
-						if (isset($fieldDef['default'])){
2084
-							return $fieldDef['default'];
2085
-						}
2086
-						return 0;
2087
-					}
2088
-					return intval($val);
1992
+    }
1993
+
1994
+    /**
1995
+     * This method returns a where array so that it has id entry if
1996
+     * where is not an array or is empty
1997
+     *
1998
+     * @param  SugarBean $bean SugarBean instance
1999
+     * @param  array  $where Optional, where conditions in an array
2000
+     * @return array
2001
+     */
2002
+    protected function updateWhereArray(SugarBean $bean, array $where = array())
2003
+    {
2004
+        if (count($where) == 0) {
2005
+            $fieldDef = $bean->getPrimaryFieldDefinition();
2006
+            $primaryColumn = $fieldDef['name'];
2007
+
2008
+            $val = $bean->getFieldValue($fieldDef['name']);
2009
+            if ($val != FALSE){
2010
+                $where[$primaryColumn] = $val;
2011
+            }
2012
+        }
2013
+
2014
+        return $where;
2015
+    }
2016
+
2017
+    /**
2018
+     * Returns a where clause without the 'where' key word
2019
+     *
2020
+     * The clause returned does not have an 'and' at the beginning and the columns
2021
+     * are joined by 'and'.
2022
+     *
2023
+     * @param  string $table table name
2024
+     * @param  array  $whereArray Optional, where conditions in an array
2025
+     * @return string
2026
+     */
2027
+    protected function getColumnWhereClause($table, array $whereArray = array())
2028
+    {
2029
+        $where = array();
2030
+        foreach ($whereArray as $name => $val) {
2031
+            $op = "=";
2032
+            if (is_array($val)) {
2033
+                $op = "IN";
2034
+                $temp = array();
2035
+                foreach ($val as $tval){
2036
+                    $temp[] = $this->quoted($tval);
2037
+                }
2038
+                $val = implode(",", $temp);
2039
+                $val = "($val)";
2040
+            } else {
2041
+                $val = $this->quoted($val);
2042
+            }
2043
+
2044
+            $where[] = " $table.$name $op $val";
2045
+        }
2046
+
2047
+        if (!empty($where))
2048
+            return implode(" AND ", $where);
2049
+
2050
+        return '';
2051
+    }
2052
+
2053
+    /**
2054
+     * This method returns a complete where clause built from the
2055
+     * where values specified.
2056
+     *
2057
+     * @param  SugarBean $bean SugarBean that describes the table
2058
+     * @param  array  $whereArray Optional, where conditions in an array
2059
+     * @return string
2060
+     */
2061
+    protected function getWhereClause(SugarBean $bean, array $whereArray=array())
2062
+    {
2063
+        return " WHERE " . $this->getColumnWhereClause($bean->getTableName(), $whereArray);
2064
+    }
2065
+
2066
+    /**
2067
+     * Outputs a correct string for the sql statement according to value
2068
+     *
2069
+     * @param  mixed $val
2070
+     * @param  array $fieldDef field definition
2071
+     * @return mixed
2072
+     */
2073
+    public function massageValue($val, $fieldDef)
2074
+    {
2075
+        $type = $this->getFieldType($fieldDef);
2076
+
2077
+        if(isset($this->type_class[$type])) {
2078
+            // handle some known types
2079
+            switch($this->type_class[$type]) {
2080
+                case 'bool':
2081
+                case 'int':
2082
+                    if (!empty($fieldDef['required']) && $val == ''){
2083
+                        if (isset($fieldDef['default'])){
2084
+                            return $fieldDef['default'];
2085
+                        }
2086
+                        return 0;
2087
+                    }
2088
+                    return intval($val);
2089 2089
                 case 'bigint' :
2090 2090
                     $val = (float)$val;
2091
-					if (!empty($fieldDef['required']) && $val == false){
2092
-						if (isset($fieldDef['default'])){
2093
-							return $fieldDef['default'];
2094
-						}
2095
-						return 0;
2096
-					}
2091
+                    if (!empty($fieldDef['required']) && $val == false){
2092
+                        if (isset($fieldDef['default'])){
2093
+                            return $fieldDef['default'];
2094
+                        }
2095
+                        return 0;
2096
+                    }
2097 2097
                     return $val;
2098
-				case 'float':
2099
-					if (!empty($fieldDef['required'])  && $val == ''){
2100
-						if (isset($fieldDef['default'])){
2101
-							return $fieldDef['default'];
2102
-						}
2103
-						return 0;
2104
-					}
2105
-					return floatval($val);
2106
-				case 'time':
2107
-				case 'date':
2108
-					// empty date can't be '', so convert it to either NULL or empty date value
2109
-					if($val == '') {
2110
-						if (!empty($fieldDef['required'])) {
2111
-							if (isset($fieldDef['default'])) {
2112
-								return $fieldDef['default'];
2113
-							}
2114
-							return $this->emptyValue($type);
2115
-						}
2116
-						return "NULL";
2117
-					}
2118
-					break;
2119
-			}
2120
-		} else {
2121
-		    if(!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) {
2122
-			    $val = $this->truncate($val, $fieldDef['len']);
2123
-			}
2124
-		}
2125
-
2126
-		if ( is_null($val) ) {
2127
-			if(!empty($fieldDef['required'])) {
2128
-				if (isset($fieldDef['default'])  && $fieldDef['default'] != ''){
2129
-					return $fieldDef['default'];
2130
-				}
2131
-				return $this->emptyValue($type);
2132
-			} else {
2133
-				return "NULL";
2134
-			}
2135
-		}
2098
+                case 'float':
2099
+                    if (!empty($fieldDef['required'])  && $val == ''){
2100
+                        if (isset($fieldDef['default'])){
2101
+                            return $fieldDef['default'];
2102
+                        }
2103
+                        return 0;
2104
+                    }
2105
+                    return floatval($val);
2106
+                case 'time':
2107
+                case 'date':
2108
+                    // empty date can't be '', so convert it to either NULL or empty date value
2109
+                    if($val == '') {
2110
+                        if (!empty($fieldDef['required'])) {
2111
+                            if (isset($fieldDef['default'])) {
2112
+                                return $fieldDef['default'];
2113
+                            }
2114
+                            return $this->emptyValue($type);
2115
+                        }
2116
+                        return "NULL";
2117
+                    }
2118
+                    break;
2119
+            }
2120
+        } else {
2121
+            if(!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) {
2122
+                $val = $this->truncate($val, $fieldDef['len']);
2123
+            }
2124
+        }
2125
+
2126
+        if ( is_null($val) ) {
2127
+            if(!empty($fieldDef['required'])) {
2128
+                if (isset($fieldDef['default'])  && $fieldDef['default'] != ''){
2129
+                    return $fieldDef['default'];
2130
+                }
2131
+                return $this->emptyValue($type);
2132
+            } else {
2133
+                return "NULL";
2134
+            }
2135
+        }
2136 2136
         if($type == "datetimecombo") {
2137 2137
             $type = "datetime";
2138 2138
         }
2139
-		return $this->convert($this->quoted($val), $type);
2140
-	}
2141
-
2142
-	/**
2143
-	 * Massages the field defintions to fill in anything else the DB backend may add
2144
-	 *
2145
-	 * @param  array  $fieldDef
2146
-	 * @param  string $tablename
2147
-	 * @return array
2148
-	 */
2149
-	public function massageFieldDef(&$fieldDef, $tablename)
2150
-	{
2151
-		if ( !isset($fieldDef['dbType']) ) {
2152
-			if ( isset($fieldDef['dbtype']) )
2153
-				$fieldDef['dbType'] = $fieldDef['dbtype'];
2154
-			else
2155
-				$fieldDef['dbType'] = $fieldDef['type'];
2156
-		}
2157
-		$type = $this->getColumnType($fieldDef['dbType'],$fieldDef['name'],$tablename);
2158
-		$matches = array();
2139
+        return $this->convert($this->quoted($val), $type);
2140
+    }
2141
+
2142
+    /**
2143
+     * Massages the field defintions to fill in anything else the DB backend may add
2144
+     *
2145
+     * @param  array  $fieldDef
2146
+     * @param  string $tablename
2147
+     * @return array
2148
+     */
2149
+    public function massageFieldDef(&$fieldDef, $tablename)
2150
+    {
2151
+        if ( !isset($fieldDef['dbType']) ) {
2152
+            if ( isset($fieldDef['dbtype']) )
2153
+                $fieldDef['dbType'] = $fieldDef['dbtype'];
2154
+            else
2155
+                $fieldDef['dbType'] = $fieldDef['type'];
2156
+        }
2157
+        $type = $this->getColumnType($fieldDef['dbType'],$fieldDef['name'],$tablename);
2158
+        $matches = array();
2159 2159
         // len can be a number or a string like 'max', for example, nvarchar(max)
2160 2160
         preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*|\w+)\)|)/i', $type, $matches);
2161
-		if ( isset($matches[1][0]) )
2162
-			$fieldDef['type'] = $matches[1][0];
2163
-		if ( isset($matches[2][0]) && empty($fieldDef['len']) )
2164
-			$fieldDef['len'] = $matches[2][0];
2165
-		if ( !empty($fieldDef['precision']) && is_numeric($fieldDef['precision']) && !strstr($fieldDef['len'],',') )
2166
-			$fieldDef['len'] .= ",{$fieldDef['precision']}";
2167
-		if (!empty($fieldDef['required']) || ($fieldDef['name'] == 'id' && !isset($fieldDef['required'])) ) {
2168
-			$fieldDef['required'] = 'true';
2169
-		}
2170
-	}
2171
-
2172
-	/**
2173
-	 * Take an SQL statement and produce a list of fields used in that select
2174
-	 * @param string $selectStatement
2175
-	 * @return array
2176
-	 */
2177
-	public function getSelectFieldsFromQuery($selectStatement)
2178
-	{
2179
-		$selectStatement = trim($selectStatement);
2180
-		if (strtoupper(substr($selectStatement, 0, 6)) == "SELECT")
2181
-			$selectStatement = trim(substr($selectStatement, 6));
2182
-
2183
-		//Due to sql functions existing in many selects, we can't use php explode
2184
-		$fields = array();
2185
-		$level = 0;
2186
-		$selectField = "";
2187
-		$strLen = strlen($selectStatement);
2188
-		for($i = 0; $i < $strLen; $i++)
2189
-		{
2190
-			$char = $selectStatement[$i];
2191
-
2192
-			if ($char == "," && $level == 0)
2193
-			{
2194
-				$field = $this->getFieldNameFromSelect(trim($selectField));
2195
-				$fields[$field] = $selectField;
2196
-				$selectField = "";
2197
-			}
2198
-			else if ($char == "("){
2199
-				$level++;
2200
-				$selectField .= $char;
2201
-			}
2202
-			else if($char == ")"){
2203
-				$level--;
2204
-				$selectField .= $char;
2205
-
2206
-
2207
-			}else{
2208
-				$selectField .= $char;
2209
-			}
2210
-
2211
-		}
2212
-		$fields[$this->getFieldNameFromSelect($selectField)] = $selectField;
2213
-		return $fields;
2214
-	}
2215
-
2216
-	/**
2217
-	 * returns the field name used in a select
2218
-	 * @param string $string SELECT query
2161
+        if ( isset($matches[1][0]) )
2162
+            $fieldDef['type'] = $matches[1][0];
2163
+        if ( isset($matches[2][0]) && empty($fieldDef['len']) )
2164
+            $fieldDef['len'] = $matches[2][0];
2165
+        if ( !empty($fieldDef['precision']) && is_numeric($fieldDef['precision']) && !strstr($fieldDef['len'],',') )
2166
+            $fieldDef['len'] .= ",{$fieldDef['precision']}";
2167
+        if (!empty($fieldDef['required']) || ($fieldDef['name'] == 'id' && !isset($fieldDef['required'])) ) {
2168
+            $fieldDef['required'] = 'true';
2169
+        }
2170
+    }
2171
+
2172
+    /**
2173
+     * Take an SQL statement and produce a list of fields used in that select
2174
+     * @param string $selectStatement
2175
+     * @return array
2176
+     */
2177
+    public function getSelectFieldsFromQuery($selectStatement)
2178
+    {
2179
+        $selectStatement = trim($selectStatement);
2180
+        if (strtoupper(substr($selectStatement, 0, 6)) == "SELECT")
2181
+            $selectStatement = trim(substr($selectStatement, 6));
2182
+
2183
+        //Due to sql functions existing in many selects, we can't use php explode
2184
+        $fields = array();
2185
+        $level = 0;
2186
+        $selectField = "";
2187
+        $strLen = strlen($selectStatement);
2188
+        for($i = 0; $i < $strLen; $i++)
2189
+        {
2190
+            $char = $selectStatement[$i];
2191
+
2192
+            if ($char == "," && $level == 0)
2193
+            {
2194
+                $field = $this->getFieldNameFromSelect(trim($selectField));
2195
+                $fields[$field] = $selectField;
2196
+                $selectField = "";
2197
+            }
2198
+            else if ($char == "("){
2199
+                $level++;
2200
+                $selectField .= $char;
2201
+            }
2202
+            else if($char == ")"){
2203
+                $level--;
2204
+                $selectField .= $char;
2205
+
2206
+
2207
+            }else{
2208
+                $selectField .= $char;
2209
+            }
2210
+
2211
+        }
2212
+        $fields[$this->getFieldNameFromSelect($selectField)] = $selectField;
2213
+        return $fields;
2214
+    }
2215
+
2216
+    /**
2217
+     * returns the field name used in a select
2218
+     * @param string $string SELECT query
2219 2219
      * @return string
2220 2220
      */
2221
-	protected function getFieldNameFromSelect($string)
2222
-	{
2223
-		if(strncasecmp($string, "DISTINCT ", 9) == 0) {
2224
-			$string = substr($string, 9);
2225
-		}
2226
-		if (stripos($string, " as ") !== false)
2227
-			//"as" used for an alias
2228
-			return trim(substr($string, strripos($string, " as ") + 4));
2229
-		else if (strrpos($string, " ") != 0)
2230
-			//Space used as a delimiter for an alias
2231
-			return trim(substr($string, strrpos($string, " ")));
2232
-		else if (strpos($string, ".") !== false)
2233
-			//No alias, but a table.field format was used
2234
-			return substr($string, strpos($string, ".") + 1);
2235
-		else
2236
-			//Give up and assume the whole thing is the field name
2237
-			return $string;
2238
-	}
2239
-
2240
-	/**
2241
-	 * Generates SQL for delete statement identified by id.
2242
-	 *
2243
-	 * @param  SugarBean $bean SugarBean instance
2244
-	 * @param  array  $where where conditions in an array
2245
-	 * @return string SQL Update Statement
2246
-	 */
2247
-	public function deleteSQL(SugarBean $bean, array $where)
2248
-	{
2249
-		$where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
2250
-		return "UPDATE ".$bean->getTableName()." SET deleted=1 $where";
2251
-	}
2221
+    protected function getFieldNameFromSelect($string)
2222
+    {
2223
+        if(strncasecmp($string, "DISTINCT ", 9) == 0) {
2224
+            $string = substr($string, 9);
2225
+        }
2226
+        if (stripos($string, " as ") !== false)
2227
+            //"as" used for an alias
2228
+            return trim(substr($string, strripos($string, " as ") + 4));
2229
+        else if (strrpos($string, " ") != 0)
2230
+            //Space used as a delimiter for an alias
2231
+            return trim(substr($string, strrpos($string, " ")));
2232
+        else if (strpos($string, ".") !== false)
2233
+            //No alias, but a table.field format was used
2234
+            return substr($string, strpos($string, ".") + 1);
2235
+        else
2236
+            //Give up and assume the whole thing is the field name
2237
+            return $string;
2238
+    }
2239
+
2240
+    /**
2241
+     * Generates SQL for delete statement identified by id.
2242
+     *
2243
+     * @param  SugarBean $bean SugarBean instance
2244
+     * @param  array  $where where conditions in an array
2245
+     * @return string SQL Update Statement
2246
+     */
2247
+    public function deleteSQL(SugarBean $bean, array $where)
2248
+    {
2249
+        $where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
2250
+        return "UPDATE ".$bean->getTableName()." SET deleted=1 $where";
2251
+    }
2252
+
2253
+    /**
2254
+     * Generates SQL for select statement for any bean identified by id.
2255
+     *
2256
+     * @param  SugarBean $bean SugarBean instance
2257
+     * @param  array  $where where conditions in an array
2258
+     * @return string SQL Select Statement
2259
+     */
2260
+    public function retrieveSQL(SugarBean $bean, array $where)
2261
+    {
2262
+        $where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
2263
+        return "SELECT * FROM ".$bean->getTableName()." $where AND deleted=0";
2264
+    }
2265
+
2266
+    /**
2267
+     * This method implements a generic sql for a collection of beans.
2268
+     *
2269
+     * Currently, this function does not support outer joins.
2270
+     *
2271
+     * @param array $beans Array of values returned by get_class method as the keys and a bean as
2272
+     *      the value for that key. These beans will be joined in the sql by the key
2273
+     *      attribute of field defs.
2274
+     * @param  array $cols Optional, columns to be returned with the keys as names of bean
2275
+     *      as identified by get_class of bean. Values of this array is the array of fieldDefs
2276
+     *      to be returned for a bean. If an empty array is passed, all columns are selected.
2277
+     * @param  array $whereClause Optional, values with the keys as names of bean as identified
2278
+     *      by get_class of bean. Each value at the first level is an array of values for that
2279
+     *      bean identified by name of fields. If we want to pass multiple values for a name,
2280
+     *      pass it as an array. If where is not passed, all the rows will be returned.
2281
+     *
2282
+     * @return string SQL Select Statement
2283
+     */
2284
+    public function retrieveViewSQL(array $beans, array $cols = array(), array $whereClause = array())
2285
+    {
2286
+        $relations = array(); // stores relations between tables as they are discovered
2287
+        $where = $select = array();
2288
+        foreach ($beans as $beanID => $bean) {
2289
+            $tableName = $bean->getTableName();
2290
+            $beanTables[$beanID] = $tableName;
2291
+
2292
+            $table = $beanID;
2293
+            $tables[$table] = $tableName;
2294
+            $aliases[$tableName][] = $table;
2295
+
2296
+            // build part of select for this table
2297
+            if (is_array($cols[$beanID]))
2298
+                foreach ($cols[$beanID] as $def) $select[] = $table.".".$def['name'];
2299
+
2300
+            // build part of where clause
2301
+            if (is_array($whereClause[$beanID])){
2302
+                $where[] = $this->getColumnWhereClause($table, $whereClause[$beanID]);
2303
+            }
2304
+            // initialize so that it can be used properly in form clause generation
2305
+            $table_used_in_from[$table] = false;
2306
+
2307
+            $indices = $bean->getIndices();
2308
+            foreach ($indices as $index){
2309
+                if ($index['type'] == 'foreign') {
2310
+                    $relationship[$table][] = array('foreignTable'=> $index['foreignTable']
2311
+                                                ,'foreignColumn'=>$index['foreignField']
2312
+                                                ,'localColumn'=> $index['fields']
2313
+                                                );
2314
+                }
2315
+            }
2316
+            $where[] = " $table.deleted = 0";
2317
+        }
2318
+
2319
+        // join these clauses
2320
+        $select = !empty($select) ? implode(",", $select) : "*";
2321
+        $where = implode(" AND ", $where);
2322
+
2323
+        // generate the from clause. Use relations array to generate outer joins
2324
+        // all the rest of the tables will be used as a simple from
2325
+        // relations table define relations between table1 and table2 through column on table 1
2326
+        // table2 is assumed to joining through primary key called id
2327
+        $separator = "";
2328
+        $from = ''; $table_used_in_from = array();
2329
+        foreach ($relations as $table1 => $rightsidearray){
2330
+            if ($table_used_in_from[$table1]) continue; // table has been joined
2331
+
2332
+            $from .= $separator." ".$table1;
2333
+            $table_used_in_from[$table1] = true;
2334
+            foreach ($rightsidearray as $tablearray){
2335
+                $table2 = $tablearray['foreignTable']; // get foreign table
2336
+                $tableAlias = $aliases[$table2]; // get a list of aliases for this table
2337
+                foreach ($tableAlias as $table2) {
2338
+                    //choose first alias that does not match
2339
+                    // we are doing this because of self joins.
2340
+                    // in case of self joins, the same table will have many aliases.
2341
+                    if ($table2 != $table1) break;
2342
+                }
2343
+
2344
+                $col = $tablearray['foreingColumn'];
2345
+                $name = $tablearray['localColumn'];
2346
+                $from .= " LEFT JOIN $table on ($table1.$name = $table2.$col)";
2347
+                $table_used_in_from[$table2] = true;
2348
+            }
2349
+            $separator = ",";
2350
+        }
2351
+
2352
+        return "SELECT $select FROM $from WHERE $where";
2353
+    }
2354
+
2355
+    /**
2356
+     * Generates SQL for create index statement for a bean.
2357
+     *
2358
+     * @param  SugarBean $bean SugarBean instance
2359
+     * @param  array  $fields fields used in the index
2360
+     * @param  string $name index name
2361
+     * @param  bool   $unique Optional, set to true if this is an unique index
2362
+     * @return string SQL Select Statement
2363
+     */
2364
+    public function createIndexSQL(SugarBean $bean, array $fields, $name, $unique = true)
2365
+    {
2366
+        $unique = ($unique) ? "unique" : "";
2367
+        $tablename = $bean->getTableName();
2368
+        $columns = array();
2369
+        // get column names
2370
+        foreach ($fields as $fieldDef)
2371
+            $columns[] = $fieldDef['name'];
2372
+
2373
+        if (empty($columns))
2374
+            return "";
2375
+
2376
+        $columns = implode(",", $columns);
2377
+
2378
+        return "CREATE $unique INDEX $name ON $tablename ($columns)";
2379
+    }
2380
+
2381
+    /**
2382
+     * Returns the type of the variable in the field
2383
+     *
2384
+     * @param  array $fieldDef Vardef-format field def
2385
+     * @return string
2386
+     */
2387
+    public function getFieldType($fieldDef)
2388
+    {
2389
+        // get the type for db type. if that is not set,
2390
+        // get it from type. This is done so that
2391
+        // we do not have change a lot of existing code
2392
+        // and add dbtype where type is being used for some special
2393
+        // purposes like referring to foreign table etc.
2394
+        if(!empty($fieldDef['dbType']))
2395
+            return  $fieldDef['dbType'];
2396
+        if(!empty($fieldDef['dbtype']))
2397
+            return  $fieldDef['dbtype'];
2398
+        if (!empty($fieldDef['type']))
2399
+            return  $fieldDef['type'];
2400
+        if (!empty($fieldDef['Type']))
2401
+            return  $fieldDef['Type'];
2402
+        if (!empty($fieldDef['data_type']))
2403
+            return  $fieldDef['data_type'];
2404
+
2405
+        return null;
2406
+    }
2407
+
2408
+    /**
2409
+     * retrieves the different components from the passed column type as it is used in the type mapping and vardefs
2410
+     * type format: <baseType>[(<len>[,<scale>])]
2411
+     * @param string $type Column type
2412
+     * @return array|bool array containing the different components of the passed in type or false in case the type contains illegal characters
2413
+     */
2414
+    public function getTypeParts($type)
2415
+    {
2416
+        if(preg_match("#(?P<type>\w+)\s*(?P<arg>\((?P<len>\w+)\s*(,\s*(?P<scale>\d+))*\))*#", $type, $matches))
2417
+        {
2418
+            $return = array();  // Not returning matches array as such as we don't want to expose the regex make up on the interface
2419
+            $return['baseType'] = $matches['type'];
2420
+            if( isset($matches['arg'])) {
2421
+                $return['arg'] = $matches['arg'];
2422
+            }
2423
+            if( isset($matches['len'])) {
2424
+                $return['len'] = $matches['len'];
2425
+            }
2426
+            if( isset($matches['scale'])) {
2427
+                $return['scale'] = $matches['scale'];
2428
+            }
2429
+            return $return;
2430
+        } else {
2431
+            return false;
2432
+        }
2433
+    }
2434
+
2435
+    /**
2436
+     * Returns the defintion for a single column
2437
+     *
2438
+     * @param  array  $fieldDef Vardef-format field def
2439
+     * @param  bool   $ignoreRequired  Optional, true if we should ignore this being a required field
2440
+     * @param  string $table           Optional, table name
2441
+     * @param  bool   $return_as_array Optional, true if we should return the result as an array instead of sql
2442
+     * @return string or array if $return_as_array is true
2443
+     */
2444
+    protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
2445
+    {
2446
+        $name = $fieldDef['name'];
2447
+        $type = $this->getFieldType($fieldDef);
2448
+        $colType = $this->getColumnType($type);
2449
+
2450
+        if($parts = $this->getTypeParts($colType))
2451
+        {
2452
+            $colBaseType = $parts['baseType'];
2453
+            $defLen =  isset($parts['len']) ? $parts['len'] : '255'; // Use the mappings length (precision) as default if it exists
2454
+        }
2455
+
2456
+        if(!empty($fieldDef['len'])) {
2457
+            if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char',
2458
+                                            'clob', 'blob', 'text'))) {
2459
+                    $colType = "$colBaseType(${fieldDef['len']})";
2460
+            } elseif(($colBaseType == 'decimal' || $colBaseType == 'float')){
2461
+                    if(!empty($fieldDef['precision']) && is_numeric($fieldDef['precision']))
2462
+                        if(strpos($fieldDef['len'],',') === false){
2463
+                            $colType = $colBaseType . "(".$fieldDef['len'].",".$fieldDef['precision'].")";
2464
+                        }else{
2465
+                            $colType = $colBaseType . "(".$fieldDef['len'].")";
2466
+                        }
2467
+                    else
2468
+                            $colType = $colBaseType . "(".$fieldDef['len'].")";
2469
+                }
2470
+        } else {
2471
+            if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char'))) {
2472
+                $colType = "$colBaseType($defLen)";
2473
+            }
2474
+        }
2475
+
2476
+        $default = '';
2477
+
2478
+        // Bug #52610 We should have ability don't add DEFAULT part to query for boolean fields
2479
+        if (!empty($fieldDef['no_default']))
2480
+        {
2481
+            // nothing to do
2482
+        }
2483
+        elseif (isset($fieldDef['default']) && strlen($fieldDef['default']) > 0)
2484
+        {
2485
+            $default = " DEFAULT ".$this->quoted($fieldDef['default']);
2486
+        }
2487
+        elseif (!isset($default) && $type == 'bool')
2488
+        {
2489
+            $default = " DEFAULT 0 ";
2490
+        }
2491
+
2492
+        $auto_increment = '';
2493
+        if(!empty($fieldDef['auto_increment']) && $fieldDef['auto_increment'])
2494
+            $auto_increment = $this->setAutoIncrement($table , $fieldDef['name']);
2495
+
2496
+        $required = 'NULL';  // MySQL defaults to NULL, SQL Server defaults to NOT NULL -- must specify
2497
+        //Starting in 6.0, only ID and auto_increment fields will be NOT NULL in the DB.
2498
+        if ((empty($fieldDef['isnull']) || strtolower($fieldDef['isnull']) == 'false') &&
2499
+            (!empty($auto_increment) || $name == 'id' || ($fieldDef['type'] == 'id' && !empty($fieldDef['required'])))) {
2500
+            $required =  "NOT NULL";
2501
+        }
2502
+        // If the field is marked both required & isnull=>false - alwqys make it not null
2503
+        // Use this to ensure primary key fields never defined as null
2504
+        if(isset($fieldDef['isnull']) && (strtolower($fieldDef['isnull']) == 'false' || $fieldDef['isnull'] === false)
2505
+            && !empty($fieldDef['required'])) {
2506
+            $required =  "NOT NULL";
2507
+        }
2508
+        if ($ignoreRequired)
2509
+            $required = "";
2510
+
2511
+        if ( $return_as_array ) {
2512
+            return array(
2513
+                'name' => $name,
2514
+                'colType' => $colType,
2515
+                'colBaseType' => $colBaseType,  // Adding base type for easier processing in derived classes
2516
+                'default' => $default,
2517
+                'required' => $required,
2518
+                'auto_increment' => $auto_increment,
2519
+                'full' => "$name $colType $default $required $auto_increment",
2520
+                );
2521
+        } else {
2522
+            return "$name $colType $default $required $auto_increment";
2523
+        }
2524
+    }
2525
+
2526
+    /**
2527
+     * Returns SQL defintions for all columns in a table
2528
+     *
2529
+     * @param  array  $fieldDefs  Vardef-format field def
2530
+     * @param  bool   $ignoreRequired Optional, true if we should ignor this being a required field
2531
+     * @param  string $tablename      Optional, table name
2532
+     * @return string SQL column definitions
2533
+     */
2534
+    protected function columnSQLRep($fieldDefs, $ignoreRequired, $tablename)
2535
+    {
2536
+        // set $ignoreRequired = false by default
2537
+        if (!is_bool($ignoreRequired)) {
2538
+            $ignoreRequired = false;
2539
+        }
2540
+
2541
+        $columns = array();
2542
+
2543
+        if ($this->isFieldArray($fieldDefs)) {
2544
+            foreach ($fieldDefs as $fieldDef) {
2545
+                if(!isset($fieldDef['source']) || $fieldDef['source'] == 'db') {
2546
+                    $columns[] = $this->oneColumnSQLRep($fieldDef,false, $tablename);
2547
+                }
2548
+            }
2549
+            $columns = implode(",", $columns);
2550
+        }
2551
+        else {
2552
+            $columns = $this->oneColumnSQLRep($fieldDefs,$ignoreRequired, $tablename);
2553
+        }
2554
+
2555
+        return $columns;
2556
+    }
2557
+
2558
+    /**
2559
+     * Returns the next value for an auto increment
2560
+     * @abstract
2561
+     * @param  string $table Table name
2562
+     * @param  string $field_name Field name
2563
+     * @return string
2564
+     */
2565
+    public function getAutoIncrement($table, $field_name)
2566
+    {
2567
+        return "";
2568
+    }
2569
+
2570
+    /**
2571
+     * Returns the sql for the next value in a sequence
2572
+     * @abstract
2573
+     * @param  string $table  Table name
2574
+     * @param  string $field_name  Field name
2575
+     * @return string
2576
+     */
2577
+    public function getAutoIncrementSQL($table, $field_name)
2578
+    {
2579
+        return "";
2580
+    }
2581
+
2582
+    /**
2583
+     * Either creates an auto increment through queries or returns sql for auto increment
2584
+     * that can be appended to the end of column defination (mysql)
2585
+     * @abstract
2586
+     * @param  string $table Table name
2587
+     * @param  string $field_name Field name
2588
+     * @return string
2589
+     */
2590
+    protected function setAutoIncrement($table, $field_name)
2591
+    {
2592
+        $this->deleteAutoIncrement($table, $field_name);
2593
+        return "";
2594
+    }
2595
+
2596
+    /**
2597
+     * Sets the next auto-increment value of a column to a specific value.
2598
+     * @abstract
2599
+     * @param  string $table Table name
2600
+     * @param  string $field_name Field name
2601
+     * @param  int $start_value  Starting autoincrement value
2602
+     * @return string
2603
+     *
2604
+     */
2605
+    public function setAutoIncrementStart($table, $field_name, $start_value)
2606
+    {
2607
+        return "";
2608
+    }
2609
+
2610
+    /**
2611
+     * Deletes an auto increment
2612
+     * @abstract
2613
+     * @param string $table tablename
2614
+     * @param string $field_name
2615
+     */
2616
+    public function deleteAutoIncrement($table, $field_name)
2617
+    {
2618
+        return;
2619
+    }
2620
+
2621
+    /**
2622
+     * This method generates sql for adding a column to table identified by field def.
2623
+     *
2624
+     * @param  string $tablename
2625
+     * @param  array  $fieldDefs
2626
+     * @return string SQL statement
2627
+     */
2628
+    public function addColumnSQL($tablename, $fieldDefs)
2629
+    {
2630
+        return $this->changeColumnSQL($tablename, $fieldDefs, 'add');
2631
+    }
2632
+
2633
+    /**
2634
+     * This method genrates sql for altering old column identified by oldFieldDef to new fieldDef.
2635
+     *
2636
+     * @param  string $tablename
2637
+     * @param  array  $newFieldDefs
2638
+     * @param  bool  $ignorerequired Optional, true if we should ignor this being a required field
2639
+     * @return string|array SQL statement(s)
2640
+     */
2641
+    public function alterColumnSQL($tablename, $newFieldDefs, $ignorerequired = false)
2642
+    {
2643
+        return $this->changeColumnSQL($tablename, $newFieldDefs, 'modify', $ignorerequired);
2644
+    }
2252 2645
 
2253 2646
     /**
2254
-     * Generates SQL for select statement for any bean identified by id.
2647
+     * Generates SQL for dropping a table.
2255 2648
      *
2256
-     * @param  SugarBean $bean SugarBean instance
2257
-     * @param  array  $where where conditions in an array
2258
-     * @return string SQL Select Statement
2649
+     * @param  SugarBean $bean Sugarbean instance
2650
+     * @return string SQL statement
2259 2651
      */
2260
-	public function retrieveSQL(SugarBean $bean, array $where)
2261
-	{
2262
-		$where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
2263
-		return "SELECT * FROM ".$bean->getTableName()." $where AND deleted=0";
2264
-	}
2652
+    public function dropTableSQL(SugarBean $bean)
2653
+    {
2654
+        return $this->dropTableNameSQL($bean->getTableName());
2655
+    }
2265 2656
 
2266 2657
     /**
2267
-     * This method implements a generic sql for a collection of beans.
2658
+     * Generates SQL for dropping a table.
2268 2659
      *
2269
-     * Currently, this function does not support outer joins.
2660
+     * @param  string $name table name
2661
+     * @return string SQL statement
2662
+     */
2663
+    public function dropTableNameSQL($name)
2664
+    {
2665
+        return "DROP TABLE ".$name;
2666
+    }
2667
+
2668
+    /**
2669
+     * Generates SQL for truncating a table.
2670
+     * @param  string $name  table name
2671
+     * @return string
2672
+     */
2673
+    public function truncateTableSQL($name)
2674
+    {
2675
+        return "TRUNCATE $name";
2676
+    }
2677
+
2678
+    /**
2679
+     * This method generates sql that deletes a column identified by fieldDef.
2270 2680
      *
2271
-     * @param array $beans Array of values returned by get_class method as the keys and a bean as
2272
-     *      the value for that key. These beans will be joined in the sql by the key
2273
-     *      attribute of field defs.
2274
-     * @param  array $cols Optional, columns to be returned with the keys as names of bean
2275
-     *      as identified by get_class of bean. Values of this array is the array of fieldDefs
2276
-     *      to be returned for a bean. If an empty array is passed, all columns are selected.
2277
-     * @param  array $whereClause Optional, values with the keys as names of bean as identified
2278
-     *      by get_class of bean. Each value at the first level is an array of values for that
2279
-     *      bean identified by name of fields. If we want to pass multiple values for a name,
2280
-     *      pass it as an array. If where is not passed, all the rows will be returned.
2681
+     * @param  SugarBean $bean      Sugarbean instance
2682
+     * @param  array  $fieldDefs
2683
+     * @return string SQL statement
2684
+     */
2685
+    public function deleteColumnSQL(SugarBean $bean, $fieldDefs)
2686
+    {
2687
+        return $this->dropColumnSQL($bean->getTableName(), $fieldDefs);
2688
+    }
2689
+
2690
+    /**
2691
+     * This method generates sql that drops a column identified by fieldDef.
2692
+     * Designed to work like the other addColumnSQL() and alterColumnSQL() functions
2281 2693
      *
2282
-     * @return string SQL Select Statement
2694
+     * @param  string $tablename
2695
+     * @param  array  $fieldDefs
2696
+     * @return string SQL statement
2283 2697
      */
2284
-	public function retrieveViewSQL(array $beans, array $cols = array(), array $whereClause = array())
2285
-	{
2286
-		$relations = array(); // stores relations between tables as they are discovered
2287
-		$where = $select = array();
2288
-		foreach ($beans as $beanID => $bean) {
2289
-			$tableName = $bean->getTableName();
2290
-			$beanTables[$beanID] = $tableName;
2291
-
2292
-			$table = $beanID;
2293
-			$tables[$table] = $tableName;
2294
-			$aliases[$tableName][] = $table;
2295
-
2296
-			// build part of select for this table
2297
-			if (is_array($cols[$beanID]))
2298
-				foreach ($cols[$beanID] as $def) $select[] = $table.".".$def['name'];
2299
-
2300
-			// build part of where clause
2301
-			if (is_array($whereClause[$beanID])){
2302
-				$where[] = $this->getColumnWhereClause($table, $whereClause[$beanID]);
2303
-			}
2304
-			// initialize so that it can be used properly in form clause generation
2305
-			$table_used_in_from[$table] = false;
2306
-
2307
-			$indices = $bean->getIndices();
2308
-			foreach ($indices as $index){
2309
-				if ($index['type'] == 'foreign') {
2310
-					$relationship[$table][] = array('foreignTable'=> $index['foreignTable']
2311
-												,'foreignColumn'=>$index['foreignField']
2312
-												,'localColumn'=> $index['fields']
2313
-												);
2314
-				}
2315
-			}
2316
-			$where[] = " $table.deleted = 0";
2317
-		}
2318
-
2319
-		// join these clauses
2320
-		$select = !empty($select) ? implode(",", $select) : "*";
2321
-		$where = implode(" AND ", $where);
2322
-
2323
-		// generate the from clause. Use relations array to generate outer joins
2324
-		// all the rest of the tables will be used as a simple from
2325
-		// relations table define relations between table1 and table2 through column on table 1
2326
-		// table2 is assumed to joining through primary key called id
2327
-		$separator = "";
2328
-		$from = ''; $table_used_in_from = array();
2329
-		foreach ($relations as $table1 => $rightsidearray){
2330
-			if ($table_used_in_from[$table1]) continue; // table has been joined
2331
-
2332
-			$from .= $separator." ".$table1;
2333
-			$table_used_in_from[$table1] = true;
2334
-			foreach ($rightsidearray as $tablearray){
2335
-				$table2 = $tablearray['foreignTable']; // get foreign table
2336
-				$tableAlias = $aliases[$table2]; // get a list of aliases for this table
2337
-				foreach ($tableAlias as $table2) {
2338
-					//choose first alias that does not match
2339
-					// we are doing this because of self joins.
2340
-					// in case of self joins, the same table will have many aliases.
2341
-					if ($table2 != $table1) break;
2342
-				}
2343
-
2344
-				$col = $tablearray['foreingColumn'];
2345
-				$name = $tablearray['localColumn'];
2346
-				$from .= " LEFT JOIN $table on ($table1.$name = $table2.$col)";
2347
-				$table_used_in_from[$table2] = true;
2348
-			}
2349
-			$separator = ",";
2350
-		}
2351
-
2352
-		return "SELECT $select FROM $from WHERE $where";
2353
-	}
2354
-
2355
-	/**
2356
-	 * Generates SQL for create index statement for a bean.
2357
-	 *
2358
-	 * @param  SugarBean $bean SugarBean instance
2359
-	 * @param  array  $fields fields used in the index
2360
-	 * @param  string $name index name
2361
-	 * @param  bool   $unique Optional, set to true if this is an unique index
2362
-	 * @return string SQL Select Statement
2363
-	 */
2364
-	public function createIndexSQL(SugarBean $bean, array $fields, $name, $unique = true)
2365
-	{
2366
-		$unique = ($unique) ? "unique" : "";
2367
-		$tablename = $bean->getTableName();
2368
-		$columns = array();
2369
-		// get column names
2370
-		foreach ($fields as $fieldDef)
2371
-			$columns[] = $fieldDef['name'];
2372
-
2373
-		if (empty($columns))
2374
-			return "";
2375
-
2376
-		$columns = implode(",", $columns);
2377
-
2378
-		return "CREATE $unique INDEX $name ON $tablename ($columns)";
2379
-	}
2380
-
2381
-	/**
2382
-	 * Returns the type of the variable in the field
2383
-	 *
2384
-	 * @param  array $fieldDef Vardef-format field def
2385
-	 * @return string
2386
-	 */
2387
-	public function getFieldType($fieldDef)
2388
-	{
2389
-		// get the type for db type. if that is not set,
2390
-		// get it from type. This is done so that
2391
-		// we do not have change a lot of existing code
2392
-		// and add dbtype where type is being used for some special
2393
-		// purposes like referring to foreign table etc.
2394
-		if(!empty($fieldDef['dbType']))
2395
-			return  $fieldDef['dbType'];
2396
-		if(!empty($fieldDef['dbtype']))
2397
-			return  $fieldDef['dbtype'];
2398
-		if (!empty($fieldDef['type']))
2399
-			return  $fieldDef['type'];
2400
-		if (!empty($fieldDef['Type']))
2401
-			return  $fieldDef['Type'];
2402
-		if (!empty($fieldDef['data_type']))
2403
-			return  $fieldDef['data_type'];
2404
-
2405
-		return null;
2406
-	}
2698
+    public function dropColumnSQL($tablename, $fieldDefs)
2699
+    {
2700
+        return $this->changeColumnSQL($tablename, $fieldDefs, 'drop');
2701
+    }
2407 2702
 
2408 2703
     /**
2409
-     * retrieves the different components from the passed column type as it is used in the type mapping and vardefs
2410
-     * type format: <baseType>[(<len>[,<scale>])]
2411
-     * @param string $type Column type
2412
-     * @return array|bool array containing the different components of the passed in type or false in case the type contains illegal characters
2704
+     * Return a version of $proposed that can be used as a column name in any of our supported databases
2705
+     * Practically this means no longer than 25 characters as the smallest identifier length for our supported DBs is 30 chars for Oracle plus we add on at least four characters in some places (for indicies for example)
2706
+     * @param string|array $name Proposed name for the column
2707
+     * @param bool|string $ensureUnique Ensure the name is unique
2708
+     * @param string $type Name type (table, column)
2709
+     * @param bool $force Force new name
2710
+     * @return string|array Valid column name trimmed to right length and with invalid characters removed
2413 2711
      */
2414
-    public function getTypeParts($type)
2712
+    public function getValidDBName($name, $ensureUnique = false, $type = 'column', $force = false)
2415 2713
     {
2416
-        if(preg_match("#(?P<type>\w+)\s*(?P<arg>\((?P<len>\w+)\s*(,\s*(?P<scale>\d+))*\))*#", $type, $matches))
2417
-        {
2418
-            $return = array();  // Not returning matches array as such as we don't want to expose the regex make up on the interface
2419
-            $return['baseType'] = $matches['type'];
2420
-            if( isset($matches['arg'])) {
2421
-                $return['arg'] = $matches['arg'];
2714
+        if(is_array($name)) {
2715
+            $result = array();
2716
+            foreach($name as $field) {
2717
+                $result[] = $this->getValidDBName($field, $ensureUnique, $type);
2422 2718
             }
2423
-            if( isset($matches['len'])) {
2424
-                $return['len'] = $matches['len'];
2719
+            return $result;
2720
+        } else {
2721
+            if(strchr($name, ".")) {
2722
+                // this is a compound name with dots, handle separately
2723
+                $parts = explode(".", $name);
2724
+                if(count($parts) > 2) {
2725
+                    // some weird name, cut to table.name
2726
+                    array_splice($parts, 0, count($parts)-2);
2727
+                }
2728
+                $parts = $this->getValidDBName($parts, $ensureUnique, $type, $force);
2729
+                return join(".", $parts);
2425 2730
             }
2426
-            if( isset($matches['scale'])) {
2427
-                $return['scale'] = $matches['scale'];
2731
+            // first strip any invalid characters - all but word chars (which is alphanumeric and _)
2732
+            $name = preg_replace( '/[^\w]+/i', '', $name ) ;
2733
+            $len = strlen( $name ) ;
2734
+            $maxLen = empty($this->maxNameLengths[$type]) ? $this->maxNameLengths[$type]['column'] : $this->maxNameLengths[$type];
2735
+            if ($len <= $maxLen && !$force) {
2736
+                return strtolower($name);
2737
+            }
2738
+            if ($ensureUnique) {
2739
+                $md5str = md5($name);
2740
+                $tail = substr ( $name, -11) ;
2741
+                $temp = substr($md5str , strlen($md5str)-4 );
2742
+                $result = substr( $name, 0, 10) . $temp . $tail ;
2743
+            } else {
2744
+                $result = substr( $name, 0, 11) . substr( $name, 11 - $maxLen);
2428 2745
             }
2429
-            return $return;
2430
-        } else {
2431
-            return false;
2432
-        }
2433
-    }
2434
-
2435
-	/**
2436
-	 * Returns the defintion for a single column
2437
-	 *
2438
-	 * @param  array  $fieldDef Vardef-format field def
2439
-	 * @param  bool   $ignoreRequired  Optional, true if we should ignore this being a required field
2440
-	 * @param  string $table           Optional, table name
2441
-	 * @param  bool   $return_as_array Optional, true if we should return the result as an array instead of sql
2442
-	 * @return string or array if $return_as_array is true
2443
-	 */
2444
-	protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
2445
-	{
2446
-		$name = $fieldDef['name'];
2447
-		$type = $this->getFieldType($fieldDef);
2448
-        $colType = $this->getColumnType($type);
2449 2746
 
2450
-        if($parts = $this->getTypeParts($colType))
2451
-        {
2452
-            $colBaseType = $parts['baseType'];
2453
-            $defLen =  isset($parts['len']) ? $parts['len'] : '255'; // Use the mappings length (precision) as default if it exists
2747
+            return strtolower( $result ) ;
2454 2748
         }
2749
+    }
2455 2750
 
2456
-        if(!empty($fieldDef['len'])) {
2457
-            if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char',
2458
-                                          'clob', 'blob', 'text'))) {
2459
-          	    $colType = "$colBaseType(${fieldDef['len']})";
2460
-            } elseif(($colBaseType == 'decimal' || $colBaseType == 'float')){
2461
-                  if(!empty($fieldDef['precision']) && is_numeric($fieldDef['precision']))
2462
-                      if(strpos($fieldDef['len'],',') === false){
2463
-                          $colType = $colBaseType . "(".$fieldDef['len'].",".$fieldDef['precision'].")";
2464
-                      }else{
2465
-                          $colType = $colBaseType . "(".$fieldDef['len'].")";
2466
-                      }
2467
-                  else
2468
-                          $colType = $colBaseType . "(".$fieldDef['len'].")";
2469
-              }
2470
-        } else {
2471
-            if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char'))) {
2472
-                $colType = "$colBaseType($defLen)";
2473
-            }
2474
-        }
2751
+    /**
2752
+     * Returns the valid type for a column given the type in fieldDef
2753
+     *
2754
+     * @param  string $type field type
2755
+     * @return string valid type for the given field
2756
+     */
2757
+    public function getColumnType($type)
2758
+    {
2759
+        return isset($this->type_map[$type])?$this->type_map[$type]:$type;
2760
+    }
2475 2761
 
2476
-        $default = '';
2762
+    /**
2763
+     * Checks to see if passed array is truely an array of defitions
2764
+     *
2765
+     * Such an array may have type as a key but it will point to an array
2766
+     * for a true array of definitions an to a col type for a definition only
2767
+     *
2768
+     * @param  mixed $defArray
2769
+     * @return bool
2770
+     */
2771
+    public function isFieldArray($defArray)
2772
+    {
2773
+        if ( !is_array($defArray) )
2774
+            return false;
2477 2775
 
2478
-        // Bug #52610 We should have ability don't add DEFAULT part to query for boolean fields
2479
-        if (!empty($fieldDef['no_default']))
2480
-        {
2481
-            // nothing to do
2482
-        }
2483
-        elseif (isset($fieldDef['default']) && strlen($fieldDef['default']) > 0)
2484
-        {
2485
-            $default = " DEFAULT ".$this->quoted($fieldDef['default']);
2486
-        }
2487
-        elseif (!isset($default) && $type == 'bool')
2488
-        {
2489
-            $default = " DEFAULT 0 ";
2776
+        if ( isset($defArray['type']) ){
2777
+            // type key exists. May be an array of defs or a simple definition
2778
+            return is_array($defArray['type']); // type is not an array => definition else array
2490 2779
         }
2491 2780
 
2492
-		$auto_increment = '';
2493
-		if(!empty($fieldDef['auto_increment']) && $fieldDef['auto_increment'])
2494
-			$auto_increment = $this->setAutoIncrement($table , $fieldDef['name']);
2495
-
2496
-		$required = 'NULL';  // MySQL defaults to NULL, SQL Server defaults to NOT NULL -- must specify
2497
-		//Starting in 6.0, only ID and auto_increment fields will be NOT NULL in the DB.
2498
-		if ((empty($fieldDef['isnull']) || strtolower($fieldDef['isnull']) == 'false') &&
2499
-			(!empty($auto_increment) || $name == 'id' || ($fieldDef['type'] == 'id' && !empty($fieldDef['required'])))) {
2500
-			$required =  "NOT NULL";
2501
-		}
2502
-		// If the field is marked both required & isnull=>false - alwqys make it not null
2503
-		// Use this to ensure primary key fields never defined as null
2504
-		if(isset($fieldDef['isnull']) && (strtolower($fieldDef['isnull']) == 'false' || $fieldDef['isnull'] === false)
2505
-			&& !empty($fieldDef['required'])) {
2506
-			$required =  "NOT NULL";
2507
-		}
2508
-		if ($ignoreRequired)
2509
-			$required = "";
2510
-
2511
-		if ( $return_as_array ) {
2512
-			return array(
2513
-				'name' => $name,
2514
-				'colType' => $colType,
2515
-                'colBaseType' => $colBaseType,  // Adding base type for easier processing in derived classes
2516
-				'default' => $default,
2517
-				'required' => $required,
2518
-				'auto_increment' => $auto_increment,
2519
-				'full' => "$name $colType $default $required $auto_increment",
2520
-				);
2521
-		} else {
2522
-			return "$name $colType $default $required $auto_increment";
2523
-		}
2524
-	}
2525
-
2526
-	/**
2527
-	 * Returns SQL defintions for all columns in a table
2528
-	 *
2529
-	 * @param  array  $fieldDefs  Vardef-format field def
2530
-	 * @param  bool   $ignoreRequired Optional, true if we should ignor this being a required field
2531
-	 * @param  string $tablename      Optional, table name
2532
-	 * @return string SQL column definitions
2533
-	 */
2534
-	protected function columnSQLRep($fieldDefs, $ignoreRequired, $tablename)
2535
-	{
2536
-		// set $ignoreRequired = false by default
2537
-		if (!is_bool($ignoreRequired)) {
2538
-			$ignoreRequired = false;
2539
-		}
2540
-
2541
-		$columns = array();
2542
-
2543
-		if ($this->isFieldArray($fieldDefs)) {
2544
-			foreach ($fieldDefs as $fieldDef) {
2545
-				if(!isset($fieldDef['source']) || $fieldDef['source'] == 'db') {
2546
-					$columns[] = $this->oneColumnSQLRep($fieldDef,false, $tablename);
2547
-				}
2548
-			}
2549
-			$columns = implode(",", $columns);
2550
-		}
2551
-		else {
2552
-			$columns = $this->oneColumnSQLRep($fieldDefs,$ignoreRequired, $tablename);
2553
-		}
2554
-
2555
-		return $columns;
2556
-	}
2557
-
2558
-	/**
2559
-	 * Returns the next value for an auto increment
2560
-	 * @abstract
2561
-	 * @param  string $table Table name
2562
-	 * @param  string $field_name Field name
2563
-	 * @return string
2564
-	 */
2565
-	public function getAutoIncrement($table, $field_name)
2566
-	{
2567
-		return "";
2568
-	}
2569
-
2570
-	/**
2571
-	 * Returns the sql for the next value in a sequence
2572
-	 * @abstract
2573
-	 * @param  string $table  Table name
2574
-	 * @param  string $field_name  Field name
2575
-	 * @return string
2576
-	 */
2577
-	public function getAutoIncrementSQL($table, $field_name)
2578
-	{
2579
-		return "";
2580
-	}
2581
-
2582
-	/**
2583
-	 * Either creates an auto increment through queries or returns sql for auto increment
2584
-	 * that can be appended to the end of column defination (mysql)
2585
-	 * @abstract
2586
-	 * @param  string $table Table name
2587
-	 * @param  string $field_name Field name
2588
-	 * @return string
2589
-	 */
2590
-	protected function setAutoIncrement($table, $field_name)
2591
-	{
2592
-		$this->deleteAutoIncrement($table, $field_name);
2593
-		return "";
2594
-	}
2781
+        // type does not exist. Must be array of definitions
2782
+        return true;
2783
+    }
2595 2784
 
2596 2785
     /**
2597
-     * Sets the next auto-increment value of a column to a specific value.
2598
-     * @abstract
2599
-     * @param  string $table Table name
2600
-     * @param  string $field_name Field name
2601
-     * @param  int $start_value  Starting autoincrement value
2602
-     * @return string
2786
+     * returns true if the type can be mapped to a valid column type
2603 2787
      *
2788
+     * @param  string $type
2789
+     * @return bool
2604 2790
      */
2605
-	public function setAutoIncrementStart($table, $field_name, $start_value)
2606
-	{
2607
-		return "";
2608
-	}
2609
-
2610
-	/**
2611
-	 * Deletes an auto increment
2612
-	 * @abstract
2613
-	 * @param string $table tablename
2614
-	 * @param string $field_name
2615
-	 */
2616
-	public function deleteAutoIncrement($table, $field_name)
2617
-	{
2618
-		return;
2619
-	}
2620
-
2621
-	/**
2622
-	 * This method generates sql for adding a column to table identified by field def.
2623
-	 *
2624
-	 * @param  string $tablename
2625
-	 * @param  array  $fieldDefs
2626
-	 * @return string SQL statement
2627
-	 */
2628
-	public function addColumnSQL($tablename, $fieldDefs)
2629
-	{
2630
-	    return $this->changeColumnSQL($tablename, $fieldDefs, 'add');
2631
-	}
2632
-
2633
-	/**
2634
-	 * This method genrates sql for altering old column identified by oldFieldDef to new fieldDef.
2635
-	 *
2636
-	 * @param  string $tablename
2637
-	 * @param  array  $newFieldDefs
2638
-	 * @param  bool  $ignorerequired Optional, true if we should ignor this being a required field
2639
-	 * @return string|array SQL statement(s)
2640
-	 */
2641
-	public function alterColumnSQL($tablename, $newFieldDefs, $ignorerequired = false)
2642
-	{
2643
-		return $this->changeColumnSQL($tablename, $newFieldDefs, 'modify', $ignorerequired);
2644
-	}
2645
-
2646
-	/**
2647
-	 * Generates SQL for dropping a table.
2648
-	 *
2649
-	 * @param  SugarBean $bean Sugarbean instance
2650
-	 * @return string SQL statement
2651
-	 */
2652
-	public function dropTableSQL(SugarBean $bean)
2653
-	{
2654
-		return $this->dropTableNameSQL($bean->getTableName());
2655
-	}
2656
-
2657
-	/**
2658
-	 * Generates SQL for dropping a table.
2659
-	 *
2660
-	 * @param  string $name table name
2661
-	 * @return string SQL statement
2662
-	 */
2663
-	public function dropTableNameSQL($name)
2664
-	{
2665
-		return "DROP TABLE ".$name;
2666
-	}
2667
-
2668
-	/**
2669
-	 * Generates SQL for truncating a table.
2670
-	 * @param  string $name  table name
2671
-	 * @return string
2672
-	 */
2673
-	public function truncateTableSQL($name)
2674
-	{
2675
-		return "TRUNCATE $name";
2676
-	}
2677
-
2678
-	/**
2679
-	 * This method generates sql that deletes a column identified by fieldDef.
2680
-	 *
2681
-	 * @param  SugarBean $bean      Sugarbean instance
2682
-	 * @param  array  $fieldDefs
2683
-	 * @return string SQL statement
2684
-	 */
2685
-	public function deleteColumnSQL(SugarBean $bean, $fieldDefs)
2686
-	{
2687
-		return $this->dropColumnSQL($bean->getTableName(), $fieldDefs);
2688
-	}
2689
-
2690
-	/**
2691
-	 * This method generates sql that drops a column identified by fieldDef.
2692
-	 * Designed to work like the other addColumnSQL() and alterColumnSQL() functions
2693
-	 *
2694
-	 * @param  string $tablename
2695
-	 * @param  array  $fieldDefs
2696
-	 * @return string SQL statement
2697
-	 */
2698
-	public function dropColumnSQL($tablename, $fieldDefs)
2699
-	{
2700
-		return $this->changeColumnSQL($tablename, $fieldDefs, 'drop');
2701
-	}
2791
+    protected function validColumnType($type)
2792
+    {
2793
+        $type = $this->getColumnType($type);
2794
+        return !empty($type);
2795
+    }
2702 2796
 
2703 2797
     /**
2704
-     * Return a version of $proposed that can be used as a column name in any of our supported databases
2705
-     * Practically this means no longer than 25 characters as the smallest identifier length for our supported DBs is 30 chars for Oracle plus we add on at least four characters in some places (for indicies for example)
2706
-     * @param string|array $name Proposed name for the column
2707
-     * @param bool|string $ensureUnique Ensure the name is unique
2708
-     * @param string $type Name type (table, column)
2709
-     * @param bool $force Force new name
2710
-     * @return string|array Valid column name trimmed to right length and with invalid characters removed
2711
-     */
2712
-	public function getValidDBName($name, $ensureUnique = false, $type = 'column', $force = false)
2713
-	{
2714
-		if(is_array($name)) {
2715
-			$result = array();
2716
-			foreach($name as $field) {
2717
-				$result[] = $this->getValidDBName($field, $ensureUnique, $type);
2718
-			}
2719
-			return $result;
2720
-		} else {
2721
-		    if(strchr($name, ".")) {
2722
-		        // this is a compound name with dots, handle separately
2723
-		        $parts = explode(".", $name);
2724
-		        if(count($parts) > 2) {
2725
-		            // some weird name, cut to table.name
2726
-		            array_splice($parts, 0, count($parts)-2);
2727
-		        }
2728
-		        $parts = $this->getValidDBName($parts, $ensureUnique, $type, $force);
2729
-                return join(".", $parts);
2730
-		    }
2731
-			// first strip any invalid characters - all but word chars (which is alphanumeric and _)
2732
-			$name = preg_replace( '/[^\w]+/i', '', $name ) ;
2733
-			$len = strlen( $name ) ;
2734
-			$maxLen = empty($this->maxNameLengths[$type]) ? $this->maxNameLengths[$type]['column'] : $this->maxNameLengths[$type];
2735
-			if ($len <= $maxLen && !$force) {
2736
-				return strtolower($name);
2737
-			}
2738
-			if ($ensureUnique) {
2739
-				$md5str = md5($name);
2740
-				$tail = substr ( $name, -11) ;
2741
-				$temp = substr($md5str , strlen($md5str)-4 );
2742
-				$result = substr( $name, 0, 10) . $temp . $tail ;
2743
-			} else {
2744
-				$result = substr( $name, 0, 11) . substr( $name, 11 - $maxLen);
2745
-			}
2746
-
2747
-			return strtolower( $result ) ;
2748
-		}
2749
-	}
2750
-
2751
-	/**
2752
-	 * Returns the valid type for a column given the type in fieldDef
2753
-	 *
2754
-	 * @param  string $type field type
2755
-	 * @return string valid type for the given field
2756
-	 */
2757
-	public function getColumnType($type)
2758
-	{
2759
-		return isset($this->type_map[$type])?$this->type_map[$type]:$type;
2760
-	}
2761
-
2762
-	/**
2763
-	 * Checks to see if passed array is truely an array of defitions
2764
-	 *
2765
-	 * Such an array may have type as a key but it will point to an array
2766
-	 * for a true array of definitions an to a col type for a definition only
2767
-	 *
2768
-	 * @param  mixed $defArray
2769
-	 * @return bool
2770
-	 */
2771
-	public function isFieldArray($defArray)
2772
-	{
2773
-		if ( !is_array($defArray) )
2774
-			return false;
2775
-
2776
-		if ( isset($defArray['type']) ){
2777
-			// type key exists. May be an array of defs or a simple definition
2778
-			return is_array($defArray['type']); // type is not an array => definition else array
2779
-		}
2780
-
2781
-		// type does not exist. Must be array of definitions
2782
-		return true;
2783
-	}
2784
-
2785
-	/**
2786
-	 * returns true if the type can be mapped to a valid column type
2787
-	 *
2788
-	 * @param  string $type
2789
-	 * @return bool
2790
-	 */
2791
-	protected function validColumnType($type)
2792
-	{
2793
-		$type = $this->getColumnType($type);
2794
-		return !empty($type);
2795
-	}
2796
-
2797
-	/**
2798
-	 * Generate query for audit table
2799
-	 * @param SugarBean $bean SugarBean that was changed
2800
-	 * @param array $changes List of changes, contains 'before' and 'after'
2798
+     * Generate query for audit table
2799
+     * @param SugarBean $bean SugarBean that was changed
2800
+     * @param array $changes List of changes, contains 'before' and 'after'
2801 2801
      * @return string  Audit table INSERT query
2802 2802
      */
2803
-	protected function auditSQL(SugarBean $bean, $changes)
2804
-	{
2805
-		global $current_user;
2806
-		$sql = "INSERT INTO ".$bean->get_audit_table_name();
2807
-		//get field defs for the audit table.
2808
-		require('metadata/audit_templateMetaData.php');
2809
-		$fieldDefs = $dictionary['audit']['fields'];
2810
-
2811
-		$values=array();
2812
-		$values['id'] = $this->massageValue(create_guid(), $fieldDefs['id']);
2813
-		$values['parent_id']= $this->massageValue($bean->id, $fieldDefs['parent_id']);
2814
-		$values['field_name']= $this->massageValue($changes['field_name'], $fieldDefs['field_name']);
2815
-		$values['data_type'] = $this->massageValue($changes['data_type'], $fieldDefs['data_type']);
2816
-		if ($changes['data_type']=='text') {
2817
-			$values['before_value_text'] = $this->massageValue($changes['before'], $fieldDefs['before_value_text']);
2818
-			$values['after_value_text'] = $this->massageValue($changes['after'], $fieldDefs['after_value_text']);
2819
-		} else {
2820
-			$values['before_value_string'] = $this->massageValue($changes['before'], $fieldDefs['before_value_string']);
2821
-			$values['after_value_string'] = $this->massageValue($changes['after'], $fieldDefs['after_value_string']);
2822
-		}
2823
-		$values['date_created'] = $this->massageValue(TimeDate::getInstance()->nowDb(), $fieldDefs['date_created'] );
2824
-		$values['created_by'] = $this->massageValue($current_user->id, $fieldDefs['created_by']);
2825
-
2826
-		$sql .= "(".implode(",", array_keys($values)).") ";
2827
-		$sql .= "VALUES(".implode(",", $values).")";
2828
-		return $sql;
2829
-	}
2803
+    protected function auditSQL(SugarBean $bean, $changes)
2804
+    {
2805
+        global $current_user;
2806
+        $sql = "INSERT INTO ".$bean->get_audit_table_name();
2807
+        //get field defs for the audit table.
2808
+        require('metadata/audit_templateMetaData.php');
2809
+        $fieldDefs = $dictionary['audit']['fields'];
2810
+
2811
+        $values=array();
2812
+        $values['id'] = $this->massageValue(create_guid(), $fieldDefs['id']);
2813
+        $values['parent_id']= $this->massageValue($bean->id, $fieldDefs['parent_id']);
2814
+        $values['field_name']= $this->massageValue($changes['field_name'], $fieldDefs['field_name']);
2815
+        $values['data_type'] = $this->massageValue($changes['data_type'], $fieldDefs['data_type']);
2816
+        if ($changes['data_type']=='text') {
2817
+            $values['before_value_text'] = $this->massageValue($changes['before'], $fieldDefs['before_value_text']);
2818
+            $values['after_value_text'] = $this->massageValue($changes['after'], $fieldDefs['after_value_text']);
2819
+        } else {
2820
+            $values['before_value_string'] = $this->massageValue($changes['before'], $fieldDefs['before_value_string']);
2821
+            $values['after_value_string'] = $this->massageValue($changes['after'], $fieldDefs['after_value_string']);
2822
+        }
2823
+        $values['date_created'] = $this->massageValue(TimeDate::getInstance()->nowDb(), $fieldDefs['date_created'] );
2824
+        $values['created_by'] = $this->massageValue($current_user->id, $fieldDefs['created_by']);
2825
+
2826
+        $sql .= "(".implode(",", array_keys($values)).") ";
2827
+        $sql .= "VALUES(".implode(",", $values).")";
2828
+        return $sql;
2829
+    }
2830 2830
 
2831 2831
     /**
2832 2832
      * Saves changes to module's audit table
@@ -2836,10 +2836,10 @@  discard block
 block discarded – undo
2836 2836
      * @return bool query result
2837 2837
      *
2838 2838
      */
2839
-	public function save_audit_records(SugarBean $bean, $changes)
2840
-	{
2841
-		return $this->query($this->auditSQL($bean, $changes));
2842
-	}
2839
+    public function save_audit_records(SugarBean $bean, $changes)
2840
+    {
2841
+        return $this->query($this->auditSQL($bean, $changes));
2842
+    }
2843 2843
 
2844 2844
     /**
2845 2845
      * Finds fields whose value has changed.
@@ -2851,7 +2851,7 @@  discard block
 block discarded – undo
2851 2851
      * @return array
2852 2852
      */
2853 2853
     public function getDataChanges(SugarBean &$bean, array $field_filter = null)
2854
-	{
2854
+    {
2855 2855
         $changed_values=array();
2856 2856
 
2857 2857
         $fetched_row = array();
@@ -2928,10 +2928,10 @@  discard block
 block discarded – undo
2928 2928
                         }
2929 2929
                     }
2930 2930
                 }
2931
-			}
2932
-		}
2933
-		return $changed_values;
2934
-	}
2931
+            }
2932
+        }
2933
+        return $changed_values;
2934
+    }
2935 2935
 
2936 2936
     /**
2937 2937
      * Uses the audit enabled fields array to find fields whose value has changed.
@@ -2947,40 +2947,40 @@  discard block
 block discarded – undo
2947 2947
         return $this->getDataChanges($bean, array_keys($audit_fields));
2948 2948
     }
2949 2949
 
2950
-	/**
2951
-	 * Setup FT indexing
2952
-	 * @abstract
2953
-	 */
2954
-	public function full_text_indexing_setup()
2955
-	{
2956
-		// Most DBs have nothing to setup, so provide default empty function
2957
-	}
2958
-
2959
-	/**
2960
-	 * Quotes a string for storing in the database
2961
-	 * @deprecated
2962
-	 * Return value will be not surrounded by quotes
2963
-	 *
2964
-	 * @param  string $string
2965
-	 * @return string
2966
-	 */
2967
-	public function escape_quote($string)
2968
-	{
2969
-		return $this->quote($string);
2970
-	}
2971
-
2972
-	/**
2973
-	 * Quotes a string for storing in the database
2974
-	 * @deprecated
2975
-	 * Return value will be not surrounded by quotes
2976
-	 *
2977
-	 * @param  string $string
2978
-	 * @return string
2979
-	 */
2980
-	public function quoteFormEmail($string)
2981
-	{
2982
-		return $this->quote($string);
2983
-	}
2950
+    /**
2951
+     * Setup FT indexing
2952
+     * @abstract
2953
+     */
2954
+    public function full_text_indexing_setup()
2955
+    {
2956
+        // Most DBs have nothing to setup, so provide default empty function
2957
+    }
2958
+
2959
+    /**
2960
+     * Quotes a string for storing in the database
2961
+     * @deprecated
2962
+     * Return value will be not surrounded by quotes
2963
+     *
2964
+     * @param  string $string
2965
+     * @return string
2966
+     */
2967
+    public function escape_quote($string)
2968
+    {
2969
+        return $this->quote($string);
2970
+    }
2971
+
2972
+    /**
2973
+     * Quotes a string for storing in the database
2974
+     * @deprecated
2975
+     * Return value will be not surrounded by quotes
2976
+     *
2977
+     * @param  string $string
2978
+     * @return string
2979
+     */
2980
+    public function quoteFormEmail($string)
2981
+    {
2982
+        return $this->quote($string);
2983
+    }
2984 2984
 
2985 2985
     /**
2986 2986
      * Renames an index using fields definition
@@ -2990,49 +2990,49 @@  discard block
 block discarded – undo
2990 2990
      * @param  string $table_name
2991 2991
      * @return string SQL statement
2992 2992
      */
2993
-	public function renameIndexDefs($old_definition, $new_definition, $table_name)
2994
-	{
2995
-		return array($this->add_drop_constraint($table_name,$old_definition,true),
2996
-				$this->add_drop_constraint($table_name,$new_definition), false);
2997
-	}
2993
+    public function renameIndexDefs($old_definition, $new_definition, $table_name)
2994
+    {
2995
+        return array($this->add_drop_constraint($table_name,$old_definition,true),
2996
+                $this->add_drop_constraint($table_name,$new_definition), false);
2997
+    }
2998 2998
 
2999
-	/**
3000
-	 * Check if type is boolean
3001
-	 * @param string $type
2999
+    /**
3000
+     * Check if type is boolean
3001
+     * @param string $type
3002 3002
      * @return bool
3003 3003
      */
3004
-	public function isBooleanType($type)
3005
-	{
3006
-		return 'bool' == $type;
3007
-	}
3004
+    public function isBooleanType($type)
3005
+    {
3006
+        return 'bool' == $type;
3007
+    }
3008 3008
 
3009
-	/**
3010
-	 * Get truth value for boolean type
3011
-	 * Allows 'off' to mean false, along with all 'empty' values
3012
-	 * @param mixed $val
3009
+    /**
3010
+     * Get truth value for boolean type
3011
+     * Allows 'off' to mean false, along with all 'empty' values
3012
+     * @param mixed $val
3013 3013
      * @return bool
3014
-	 */
3015
-	protected function _getBooleanValue($val)
3016
-	{
3017
-		//need to put the === sign here otherwise true == 'non empty string'
3018
-		if (empty($val) or $val==='off')
3019
-			return false;
3020
-
3021
-		return true;
3022
-	}
3023
-
3024
-	/**
3025
-	 * Check if type is a number
3026
-	 * @param string $type
3014
+     */
3015
+    protected function _getBooleanValue($val)
3016
+    {
3017
+        //need to put the === sign here otherwise true == 'non empty string'
3018
+        if (empty($val) or $val==='off')
3019
+            return false;
3020
+
3021
+        return true;
3022
+    }
3023
+
3024
+    /**
3025
+     * Check if type is a number
3026
+     * @param string $type
3027 3027
      * @return bool
3028
-	 */
3029
-	public function isNumericType($type)
3030
-	{
3031
-	    if(isset($this->type_class[$type]) && ($this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) {
3032
-	        return true;
3033
-	    }
3034
-		return false;
3035
-	}
3028
+     */
3029
+    public function isNumericType($type)
3030
+    {
3031
+        if(isset($this->type_class[$type]) && ($this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) {
3032
+            return true;
3033
+        }
3034
+        return false;
3035
+    }
3036 3036
 
3037 3037
     /**
3038 3038
      * Check if the value is empty value for this type
@@ -3040,272 +3040,272 @@  discard block
 block discarded – undo
3040 3040
      * @param string $type Type (one of vardef types)
3041 3041
      * @return bool true if the value if empty
3042 3042
      */
3043
-	protected function _emptyValue($val, $type)
3044
-	{
3045
-		if (empty($val))
3046
-			return true;
3047
-
3048
-		if($this->emptyValue($type) == $val) {
3049
-			return true;
3050
-		}
3051
-		switch ($type) {
3052
-			case 'decimal':
3053
-			case 'decimal2':
3054
-			case 'int':
3055
-			case 'double':
3056
-			case 'float':
3057
-			case 'uint':
3058
-			case 'ulong':
3059
-			case 'long':
3060
-			case 'short':
3061
-				return ($val == 0);
3062
-			case 'date':
3063
-				if ($val == '0000-00-00')
3064
-					return true;
3065
-				if ($val == 'NULL')
3066
-					return true;
3067
-				return false;
3068
-		}
3069
-
3070
-		return false;
3071
-	}
3072
-
3073
-	/**
3043
+    protected function _emptyValue($val, $type)
3044
+    {
3045
+        if (empty($val))
3046
+            return true;
3047
+
3048
+        if($this->emptyValue($type) == $val) {
3049
+            return true;
3050
+        }
3051
+        switch ($type) {
3052
+            case 'decimal':
3053
+            case 'decimal2':
3054
+            case 'int':
3055
+            case 'double':
3056
+            case 'float':
3057
+            case 'uint':
3058
+            case 'ulong':
3059
+            case 'long':
3060
+            case 'short':
3061
+                return ($val == 0);
3062
+            case 'date':
3063
+                if ($val == '0000-00-00')
3064
+                    return true;
3065
+                if ($val == 'NULL')
3066
+                    return true;
3067
+                return false;
3068
+        }
3069
+
3070
+        return false;
3071
+    }
3072
+
3073
+    /**
3074 3074
      * @abstract
3075
-	 * Does this type represent text (i.e., non-varchar) value?
3076
-	 * @param string $type
3075
+     * Does this type represent text (i.e., non-varchar) value?
3076
+     * @param string $type
3077 3077
      * @return bool
3078
-	 */
3079
-	public function isTextType($type)
3080
-	{
3081
-		return false;
3082
-	}
3083
-
3084
-	/**
3085
-	 * Check if this DB supports certain capability
3086
-	 * See $this->capabilities for the list
3087
-	 * @param string $cap
3078
+     */
3079
+    public function isTextType($type)
3080
+    {
3081
+        return false;
3082
+    }
3083
+
3084
+    /**
3085
+     * Check if this DB supports certain capability
3086
+     * See $this->capabilities for the list
3087
+     * @param string $cap
3088 3088
      * @return bool
3089
-	 */
3090
-	public function supports($cap)
3091
-	{
3092
-		return !empty($this->capabilities[$cap]);
3093
-	}
3094
-
3095
-	/**
3096
-	 * Create ORDER BY clause for ENUM type field
3097
-	 * @param string $order_by Field name
3098
-	 * @param array $values Possible enum value
3099
-	 * @param string $order_dir Order direction, ASC or DESC
3089
+     */
3090
+    public function supports($cap)
3091
+    {
3092
+        return !empty($this->capabilities[$cap]);
3093
+    }
3094
+
3095
+    /**
3096
+     * Create ORDER BY clause for ENUM type field
3097
+     * @param string $order_by Field name
3098
+     * @param array $values Possible enum value
3099
+     * @param string $order_dir Order direction, ASC or DESC
3100 3100
      * @return string
3101 3101
      */
3102
-	public function orderByEnum($order_by, $values, $order_dir)
3103
-	{
3104
-		$i = 0;
3105
-		$order_by_arr = array();
3106
-		foreach ($values as $key => $value) {
3107
-			if($key == '') {
3108
-				$order_by_arr[] = "WHEN ($order_by='' OR $order_by IS NULL) THEN $i";
3109
-			} else {
3110
-				$order_by_arr[] = "WHEN $order_by=".$this->quoted($key)." THEN $i";
3111
-			}
3112
-			$i++;
3113
-		}
3114
-		return "CASE ".implode("\n", $order_by_arr)." ELSE $i END $order_dir\n";
3115
-	}
3116
-
3117
-	/**
3118
-	 * Return representation of an empty value depending on type
3119
-	 * The value is fully quoted, converted, etc.
3120
-	 * @param string $type
3102
+    public function orderByEnum($order_by, $values, $order_dir)
3103
+    {
3104
+        $i = 0;
3105
+        $order_by_arr = array();
3106
+        foreach ($values as $key => $value) {
3107
+            if($key == '') {
3108
+                $order_by_arr[] = "WHEN ($order_by='' OR $order_by IS NULL) THEN $i";
3109
+            } else {
3110
+                $order_by_arr[] = "WHEN $order_by=".$this->quoted($key)." THEN $i";
3111
+            }
3112
+            $i++;
3113
+        }
3114
+        return "CASE ".implode("\n", $order_by_arr)." ELSE $i END $order_dir\n";
3115
+    }
3116
+
3117
+    /**
3118
+     * Return representation of an empty value depending on type
3119
+     * The value is fully quoted, converted, etc.
3120
+     * @param string $type
3121 3121
      * @return mixed Empty value
3122 3122
      */
3123
-	public function emptyValue($type)
3124
-	{
3125
-		if(isset($this->type_class[$type]) && ($this->type_class[$type] == 'bool' || $this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) {
3126
-			return 0;
3127
-		}
3123
+    public function emptyValue($type)
3124
+    {
3125
+        if(isset($this->type_class[$type]) && ($this->type_class[$type] == 'bool' || $this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) {
3126
+            return 0;
3127
+        }
3128 3128
 
3129
-		return "''";
3130
-	}
3129
+        return "''";
3130
+    }
3131 3131
 
3132
-	/**
3133
-	 * List of available collation settings
3132
+    /**
3133
+     * List of available collation settings
3134 3134
      * @abstract
3135
-	 * @return string
3136
-	 */
3137
-	public function getDefaultCollation()
3138
-	{
3139
-		return null;
3140
-	}
3141
-
3142
-	/**
3143
-	 * List of available collation settings
3135
+     * @return string
3136
+     */
3137
+    public function getDefaultCollation()
3138
+    {
3139
+        return null;
3140
+    }
3141
+
3142
+    /**
3143
+     * List of available collation settings
3144 3144
      * @abstract
3145
-	 * @return array
3146
-	 */
3147
-	public function getCollationList()
3148
-	{
3149
-		return null;
3150
-	}
3151
-
3152
-	/**
3153
-	 * Returns the number of columns in a table
3154
-	 *
3155
-	 * @param  string $table_name
3156
-	 * @return int
3157
-	 */
3158
-	public function number_of_columns($table_name)
3159
-	{
3160
-		$table = $this->getTableDescription($table_name);
3161
-		return count($table);
3162
-	}
3163
-
3164
-	/**
3165
-	 * Return limit query based on given query
3166
-	 * @param string $sql
3167
-	 * @param int $start
3168
-	 * @param int $count
3169
-	 * @param bool $dieOnError
3170
-	 * @param string $msg
3145
+     * @return array
3146
+     */
3147
+    public function getCollationList()
3148
+    {
3149
+        return null;
3150
+    }
3151
+
3152
+    /**
3153
+     * Returns the number of columns in a table
3154
+     *
3155
+     * @param  string $table_name
3156
+     * @return int
3157
+     */
3158
+    public function number_of_columns($table_name)
3159
+    {
3160
+        $table = $this->getTableDescription($table_name);
3161
+        return count($table);
3162
+    }
3163
+
3164
+    /**
3165
+     * Return limit query based on given query
3166
+     * @param string $sql
3167
+     * @param int $start
3168
+     * @param int $count
3169
+     * @param bool $dieOnError
3170
+     * @param string $msg
3171 3171
      * @return resource|bool query result
3172 3172
      * @see DBManager::limitQuery()
3173
-	 */
3174
-	public function limitQuerySql($sql, $start, $count, $dieOnError=false, $msg='')
3175
-	{
3176
-		return $this->limitQuery($sql,$start,$count,$dieOnError,$msg,false);
3177
-	}
3178
-
3179
-	/**
3180
-	 * Return current time in format fit for insertion into DB (with quotes)
3181
-	 * @return string
3182
-	 */
3183
-	public function now()
3184
-	{
3185
-		return $this->convert($this->quoted(TimeDate::getInstance()->nowDb()), "datetime");
3186
-	}
3187
-
3188
-	/**
3189
-	 * Check if connecting user has certain privilege
3190
-	 * @param string $privilege
3173
+     */
3174
+    public function limitQuerySql($sql, $start, $count, $dieOnError=false, $msg='')
3175
+    {
3176
+        return $this->limitQuery($sql,$start,$count,$dieOnError,$msg,false);
3177
+    }
3178
+
3179
+    /**
3180
+     * Return current time in format fit for insertion into DB (with quotes)
3181
+     * @return string
3182
+     */
3183
+    public function now()
3184
+    {
3185
+        return $this->convert($this->quoted(TimeDate::getInstance()->nowDb()), "datetime");
3186
+    }
3187
+
3188
+    /**
3189
+     * Check if connecting user has certain privilege
3190
+     * @param string $privilege
3191 3191
      * @return bool Privilege allowed?
3192 3192
      */
3193
-	public function checkPrivilege($privilege)
3194
-	{
3195
-		switch($privilege) {
3196
-			case "CREATE TABLE":
3197
-				$this->query("CREATE TABLE temp (id varchar(36))");
3198
-				break;
3199
-			case "DROP TABLE":
3200
-				$sql = $this->dropTableNameSQL("temp");
3201
-				$this->query($sql);
3202
-				break;
3203
-			case "INSERT":
3204
-				$this->query("INSERT INTO temp (id) VALUES ('abcdef0123456789abcdef0123456789abcd')");
3205
-				break;
3206
-			case "UPDATE":
3207
-				$this->query("UPDATE temp SET id = '100000000000000000000000000000000000' WHERE id = 'abcdef0123456789abcdef0123456789abcd'");
3208
-				break;
3209
-			case 'SELECT':
3210
-				return $this->getOne('SELECT id FROM temp WHERE id=\'100000000000000000000000000000000000\'', false);
3211
-			case 'DELETE':
3212
-				$this->query("DELETE FROM temp WHERE id = '100000000000000000000000000000000000'");
3213
-				break;
3214
-			case "ADD COLUMN":
3215
-				$test = array("test" => array("name" => "test", "type" => "varchar", "len" => 50));
3216
-				$sql = 	$this->changeColumnSQL("temp", $test, "add");
3217
-				$this->query($sql);
3218
-				break;
3219
-			case "CHANGE COLUMN":
3220
-				$test = array("test" => array("name" => "test", "type" => "varchar", "len" => 100));
3221
-				$sql = 	$this->changeColumnSQL("temp", $test, "modify");
3222
-				$this->query($sql);
3223
-				break;
3224
-			case "DROP COLUMN":
3225
-				$test = array("test" => array("name" => "test", "type" => "varchar", "len" => 100));
3226
-				$sql = 	$this->changeColumnSQL("temp", $test, "drop");
3227
-				$this->query($sql);
3228
-				break;
3229
-			default:
3230
-				return false;
3231
-		}
3232
-		if($this->checkError("Checking privileges")) {
3233
-			return false;
3234
-		}
3235
-		return true;
3236
-	}
3237
-
3238
-	/**
3239
-	 * Check if the query is a select query
3240
-	 * @param string $query
3193
+    public function checkPrivilege($privilege)
3194
+    {
3195
+        switch($privilege) {
3196
+            case "CREATE TABLE":
3197
+                $this->query("CREATE TABLE temp (id varchar(36))");
3198
+                break;
3199
+            case "DROP TABLE":
3200
+                $sql = $this->dropTableNameSQL("temp");
3201
+                $this->query($sql);
3202
+                break;
3203
+            case "INSERT":
3204
+                $this->query("INSERT INTO temp (id) VALUES ('abcdef0123456789abcdef0123456789abcd')");
3205
+                break;
3206
+            case "UPDATE":
3207
+                $this->query("UPDATE temp SET id = '100000000000000000000000000000000000' WHERE id = 'abcdef0123456789abcdef0123456789abcd'");
3208
+                break;
3209
+            case 'SELECT':
3210
+                return $this->getOne('SELECT id FROM temp WHERE id=\'100000000000000000000000000000000000\'', false);
3211
+            case 'DELETE':
3212
+                $this->query("DELETE FROM temp WHERE id = '100000000000000000000000000000000000'");
3213
+                break;
3214
+            case "ADD COLUMN":
3215
+                $test = array("test" => array("name" => "test", "type" => "varchar", "len" => 50));
3216
+                $sql = 	$this->changeColumnSQL("temp", $test, "add");
3217
+                $this->query($sql);
3218
+                break;
3219
+            case "CHANGE COLUMN":
3220
+                $test = array("test" => array("name" => "test", "type" => "varchar", "len" => 100));
3221
+                $sql = 	$this->changeColumnSQL("temp", $test, "modify");
3222
+                $this->query($sql);
3223
+                break;
3224
+            case "DROP COLUMN":
3225
+                $test = array("test" => array("name" => "test", "type" => "varchar", "len" => 100));
3226
+                $sql = 	$this->changeColumnSQL("temp", $test, "drop");
3227
+                $this->query($sql);
3228
+                break;
3229
+            default:
3230
+                return false;
3231
+        }
3232
+        if($this->checkError("Checking privileges")) {
3233
+            return false;
3234
+        }
3235
+        return true;
3236
+    }
3237
+
3238
+    /**
3239
+     * Check if the query is a select query
3240
+     * @param string $query
3241 3241
      * @return bool  Is query SELECT?
3242 3242
      */
3243
-	protected function isSelect($query)
3244
-	{
3245
-		$query = trim($query);
3246
-		$select_check = strpos(strtolower($query), strtolower("SELECT"));
3247
-		//Checks to see if there is union select which is valid
3248
-		$select_check2 = strpos(strtolower($query), strtolower("(SELECT"));
3249
-		if($select_check==0 || $select_check2==0){
3250
-			//Returning false means query is ok!
3251
-			return true;
3252
-		}
3253
-		return false;
3254
-	}
3255
-
3256
-	/**
3257
-	 * Parse fulltext search query with mysql syntax:
3258
-	 *  terms quoted by ""
3259
-	 *  + means the term must be included
3260
-	 *  - means the term must be excluded
3261
-	 *  * or % at the end means wildcard
3262
-	 * @param string $query
3263
-	 * @return array of 3 elements - query terms, mandatory terms and excluded terms
3264
-	 */
3265
-	public function parseFulltextQuery($query)
3266
-	{
3267
-		/* split on space or comma, double quotes with \ for escape */
3268
-		if(strpbrk($query, " ,")) {
3269
-			// ("([^"]*?)"|[^" ,]+)((, )+)?
3270
-			// '/([^" ,]+|".*?[^\\\\]")(,|\s)\s*/'
3271
-			if(!preg_match_all('/("([^"]*?)"|[^"\s,]+)((,\s)+)?/', $query, $m)) {
3272
-				return false;
3273
-			}
3274
-			$qterms = $m[1];
3275
-		} else {
3276
-			$qterms = array($query);
3277
-		}
3278
-		$terms = $must_terms = $not_terms = array();
3279
-		foreach($qterms as $item) {
3280
-			if($item[0] == '"') {
3281
-				$item = trim($item, '"');
3282
-			}
3283
-			if($item[0] == '+') {
3243
+    protected function isSelect($query)
3244
+    {
3245
+        $query = trim($query);
3246
+        $select_check = strpos(strtolower($query), strtolower("SELECT"));
3247
+        //Checks to see if there is union select which is valid
3248
+        $select_check2 = strpos(strtolower($query), strtolower("(SELECT"));
3249
+        if($select_check==0 || $select_check2==0){
3250
+            //Returning false means query is ok!
3251
+            return true;
3252
+        }
3253
+        return false;
3254
+    }
3255
+
3256
+    /**
3257
+     * Parse fulltext search query with mysql syntax:
3258
+     *  terms quoted by ""
3259
+     *  + means the term must be included
3260
+     *  - means the term must be excluded
3261
+     *  * or % at the end means wildcard
3262
+     * @param string $query
3263
+     * @return array of 3 elements - query terms, mandatory terms and excluded terms
3264
+     */
3265
+    public function parseFulltextQuery($query)
3266
+    {
3267
+        /* split on space or comma, double quotes with \ for escape */
3268
+        if(strpbrk($query, " ,")) {
3269
+            // ("([^"]*?)"|[^" ,]+)((, )+)?
3270
+            // '/([^" ,]+|".*?[^\\\\]")(,|\s)\s*/'
3271
+            if(!preg_match_all('/("([^"]*?)"|[^"\s,]+)((,\s)+)?/', $query, $m)) {
3272
+                return false;
3273
+            }
3274
+            $qterms = $m[1];
3275
+        } else {
3276
+            $qterms = array($query);
3277
+        }
3278
+        $terms = $must_terms = $not_terms = array();
3279
+        foreach($qterms as $item) {
3280
+            if($item[0] == '"') {
3281
+                $item = trim($item, '"');
3282
+            }
3283
+            if($item[0] == '+') {
3284 3284
                 if (strlen($item) > 1) {
3285 3285
                     $must_terms[] = substr($item, 1);
3286 3286
                 }
3287 3287
                 continue;
3288
-			}
3289
-			if($item[0] == '-') {
3288
+            }
3289
+            if($item[0] == '-') {
3290 3290
                 if (strlen($item) > 1) {
3291
-				    $not_terms[] = substr($item, 1);
3291
+                    $not_terms[] = substr($item, 1);
3292 3292
                 }
3293 3293
                 continue;
3294
-			}
3295
-			$terms[] = $item;
3296
-		}
3297
-		return array($terms, $must_terms, $not_terms);
3298
-	}
3294
+            }
3295
+            $terms[] = $item;
3296
+        }
3297
+        return array($terms, $must_terms, $not_terms);
3298
+    }
3299 3299
 
3300 3300
     // Methods to check respective queries
3301
-	protected $standardQueries = array(
3302
-		'ALTER TABLE' => 'verifyAlterTable',
3303
-		'DROP TABLE' => 'verifyDropTable',
3304
-		'CREATE TABLE' => 'verifyCreateTable',
3305
-		'INSERT INTO' => 'verifyInsertInto',
3306
-		'UPDATE' => 'verifyUpdate',
3307
-		'DELETE FROM' => 'verifyDeleteFrom',
3308
-	);
3301
+    protected $standardQueries = array(
3302
+        'ALTER TABLE' => 'verifyAlterTable',
3303
+        'DROP TABLE' => 'verifyDropTable',
3304
+        'CREATE TABLE' => 'verifyCreateTable',
3305
+        'INSERT INTO' => 'verifyInsertInto',
3306
+        'UPDATE' => 'verifyUpdate',
3307
+        'DELETE FROM' => 'verifyDeleteFrom',
3308
+    );
3309 3309
 
3310 3310
 
3311 3311
     /**
@@ -3313,8 +3313,8 @@  discard block
 block discarded – undo
3313 3313
      * @param string $query SQL query
3314 3314
      * @return string
3315 3315
      */
3316
-	protected function extractTableName($query)
3317
-	{
3316
+    protected function extractTableName($query)
3317
+    {
3318 3318
         $query = preg_replace('/[^A-Za-z0-9_\s]/', "", $query);
3319 3319
         $query = trim(str_replace(array_keys($this->standardQueries), '', $query));
3320 3320
 
@@ -3323,7 +3323,7 @@  discard block
 block discarded – undo
3323 3323
         $table = substr($query, 0, $end);
3324 3324
 
3325 3325
         return $table;
3326
-	}
3326
+    }
3327 3327
 
3328 3328
     /**
3329 3329
      * Verify SQl statement using per-DB verification function
@@ -3332,284 +3332,284 @@  discard block
 block discarded – undo
3332 3332
      * @param array $skipTables List of blacklisted tables that aren't checked
3333 3333
      * @return string
3334 3334
      */
3335
-	public function verifySQLStatement($query, $skipTables)
3336
-	{
3337
-		$query = trim($query);
3338
-		foreach($this->standardQueries as $qstart => $check) {
3339
-			if(strncasecmp($qstart, $query, strlen($qstart)) == 0) {
3340
-				if(is_callable(array($this, $check))) {
3341
-					$table = $this->extractTableName($query);
3342
-					if(!in_array($table, $skipTables)) {
3343
-						return call_user_func(array($this, $check), $table, $query);
3344
-					} else {
3345
-						$this->log->debug("Skipping table $table as blacklisted");
3346
-					}
3347
-				} else {
3348
-					$this->log->debug("No verification for $qstart on {$this->dbType}");
3349
-				}
3350
-				break;
3351
-			}
3352
-		}
3353
-		return "";
3354
-	}
3355
-
3356
-	/**
3357
-	 * Tests an CREATE TABLE query
3358
-	 * @param string $table The table name to get DDL
3359
-	 * @param string $query The query to test.
3360
-	 * @return string Non-empty if error found
3361
-	 */
3362
-	protected function verifyCreateTable($table, $query)
3363
-	{
3364
-		$this->log->debug('verifying CREATE statement...');
3365
-
3366
-		// rewrite DDL with _temp name
3367
-		$this->log->debug('testing query: ['.$query.']');
3368
-		$tempname = $table."__uw_temp";
3369
-		$tempTableQuery = str_replace("CREATE TABLE {$table}", "CREATE TABLE $tempname", $query);
3370
-
3371
-		if(strpos($tempTableQuery, '__uw_temp') === false) {
3372
-			return 'Could not use a temp table to test query!';
3373
-		}
3374
-
3375
-		$this->query($tempTableQuery, false, "Preflight Failed for: {$query}");
3376
-
3377
-		$error = $this->lastError(); // empty on no-errors
3378
-		if(!empty($error)) {
3379
-			return $error;
3380
-		}
3381
-
3382
-		// check if table exists
3383
-		$this->log->debug('testing for table: '.$table);
3384
-		if(!$this->tableExists($tempname)) {
3385
-			return "Failed to create temp table!";
3386
-		}
3387
-
3388
-		$this->dropTableName($tempname);
3389
-		return '';
3390
-	}
3391
-
3392
-	/**
3393
-	 * Execute multiple queries one after another
3394
-	 * @param array $sqls Queries
3395
-	 * @param bool $dieOnError Die on error, passed to query()
3396
-	 * @param string $msg Error message, passed to query()
3397
-	 * @param bool $suppress Supress errors, passed to query()
3398
-	 * @return resource|bool result set or success/failure bool
3399
-	 */
3400
-	public function queryArray(array $sqls, $dieOnError = false, $msg = '', $suppress = false)
3401
-	{
3402
-		$last = true;
3403
-		foreach($sqls as $sql) {
3404
-			if(!($last = $this->query($sql, $dieOnError, $msg, $suppress))) {
3405
-				break;
3406
-			}
3407
-		}
3408
-		return $last;
3409
-	}
3410
-
3411
-	/**
3412
-	 * Fetches the next row in the query result into an associative array
3413
-	 *
3414
-	 * @param  resource $result
3415
-	 * @param  bool $encode Need to HTML-encode the result?
3416
-	 * @return array    returns false if there are no more rows available to fetch
3417
-	 */
3418
-	public function fetchByAssoc($result, $encode = true)
3419
-	{
3420
-	    if (empty($result))	return false;
3421
-
3422
-	    if(is_int($encode) && func_num_args() == 3) {
3423
-	        // old API: $result, $rowNum, $encode
3424
-	        $GLOBALS['log']->deprecated("Using row number in fetchByAssoc is not portable and no longer supported. Please fix your code.");
3425
-	        $encode = func_get_arg(2);
3426
-	    }
3427
-	    $row = $this->fetchRow($result);
3428
-	    if (!empty($row) && $encode && $this->encode) {
3429
-	    	return array_map('to_html', $row);
3430
-	    } else {
3431
-	       return $row;
3432
-	    }
3433
-	}
3434
-
3435
-	/**
3436
-	 * Get DB driver name used for install/upgrade scripts
3437
-	 * @return string
3438
-	 */
3439
-	public function getScriptName()
3440
-	{
3441
-		// Usually the same name as dbType
3442
-		return $this->dbType;
3443
-	}
3444
-
3445
-	/**
3446
-	 * Set database options
3447
-	 * Options are usually db-dependant and derive from $config['dbconfigoption']
3448
-	 * @param array $options
3449
-	 * @return DBManager
3450
-	 */
3451
-	public function setOptions($options)
3452
-	{
3453
-	    $this->options = $options;
3454
-	    return $this;
3455
-	}
3456
-
3457
-	/**
3458
-	 * Get DB options
3459
-	 * @return array
3460
-	 */
3461
-	public function getOptions()
3462
-	{
3463
-	    return $this->options;
3464
-	}
3465
-
3466
-	/**
3467
-	 * Get DB option by name
3468
-	 * @param string $option Option name
3469
-	 * @return mixed Option value or null if doesn't exist
3470
-	 */
3471
-	public function getOption($option)
3472
-	{
3473
-	    if(isset($this->options[$option])) {
3474
-	        return $this->options[$option];
3475
-	    }
3476
-	    return null;
3477
-	}
3478
-
3479
-	/**
3480
-	 * Commits pending changes to the database when the driver is setup to support transactions.
3481
-	 * Note that the default implementation is applicable for transaction-less or auto commit scenarios.
3482
-	 * @abstract
3483
-	 * @return bool true if commit succeeded, false if it failed
3484
-	 */
3485
-	public function commit()
3486
-	{
3487
-		$this->log->info("DBManager.commit() stub");
3488
-		return true;
3489
-	}
3490
-
3491
-	/**
3492
-	 * Rollsback pending changes to the database when the driver is setup to support transactions.
3493
-	 * Note that the default implementation is applicable for transaction-less or auto commit scenarios.
3494
-	 * Since rollbacks cannot be done, this implementation always returns false.
3495
-	 * @abstract
3496
-	 * @return bool true if rollback succeeded, false if it failed
3497
-	 */
3498
-	public function rollback()
3499
-	{
3500
-		$this->log->info("DBManager.rollback() stub");
3501
-		return false;
3502
-	}
3503
-
3504
-	/**
3505
-	 * Check if this DB name is valid
3506
-	 *
3507
-	 * @param string $name
3508
-	 * @return bool
3509
-	 */
3510
-	public function isDatabaseNameValid($name)
3511
-	{
3512
-		// Generic case - no slashes, no dots
3513
-		return preg_match('#[/.\\\\]#', $name)==0;
3514
-	}
3515
-
3516
-	/**
3517
-	 * Check special requirements for DB installation.
3518
-	 * @abstract
3519
-	 * If everything is OK, return true.
3520
-	 * If something's wrong, return array of error code and parameters
3521
-	 * @return mixed
3522
-	 */
3523
-	public function canInstall()
3524
-	{
3525
-		return true;
3526
-	}
3527
-
3528
-	/**
3529
-	 * @abstract
3335
+    public function verifySQLStatement($query, $skipTables)
3336
+    {
3337
+        $query = trim($query);
3338
+        foreach($this->standardQueries as $qstart => $check) {
3339
+            if(strncasecmp($qstart, $query, strlen($qstart)) == 0) {
3340
+                if(is_callable(array($this, $check))) {
3341
+                    $table = $this->extractTableName($query);
3342
+                    if(!in_array($table, $skipTables)) {
3343
+                        return call_user_func(array($this, $check), $table, $query);
3344
+                    } else {
3345
+                        $this->log->debug("Skipping table $table as blacklisted");
3346
+                    }
3347
+                } else {
3348
+                    $this->log->debug("No verification for $qstart on {$this->dbType}");
3349
+                }
3350
+                break;
3351
+            }
3352
+        }
3353
+        return "";
3354
+    }
3355
+
3356
+    /**
3357
+     * Tests an CREATE TABLE query
3358
+     * @param string $table The table name to get DDL
3359
+     * @param string $query The query to test.
3360
+     * @return string Non-empty if error found
3361
+     */
3362
+    protected function verifyCreateTable($table, $query)
3363
+    {
3364
+        $this->log->debug('verifying CREATE statement...');
3365
+
3366
+        // rewrite DDL with _temp name
3367
+        $this->log->debug('testing query: ['.$query.']');
3368
+        $tempname = $table."__uw_temp";
3369
+        $tempTableQuery = str_replace("CREATE TABLE {$table}", "CREATE TABLE $tempname", $query);
3370
+
3371
+        if(strpos($tempTableQuery, '__uw_temp') === false) {
3372
+            return 'Could not use a temp table to test query!';
3373
+        }
3374
+
3375
+        $this->query($tempTableQuery, false, "Preflight Failed for: {$query}");
3376
+
3377
+        $error = $this->lastError(); // empty on no-errors
3378
+        if(!empty($error)) {
3379
+            return $error;
3380
+        }
3381
+
3382
+        // check if table exists
3383
+        $this->log->debug('testing for table: '.$table);
3384
+        if(!$this->tableExists($tempname)) {
3385
+            return "Failed to create temp table!";
3386
+        }
3387
+
3388
+        $this->dropTableName($tempname);
3389
+        return '';
3390
+    }
3391
+
3392
+    /**
3393
+     * Execute multiple queries one after another
3394
+     * @param array $sqls Queries
3395
+     * @param bool $dieOnError Die on error, passed to query()
3396
+     * @param string $msg Error message, passed to query()
3397
+     * @param bool $suppress Supress errors, passed to query()
3398
+     * @return resource|bool result set or success/failure bool
3399
+     */
3400
+    public function queryArray(array $sqls, $dieOnError = false, $msg = '', $suppress = false)
3401
+    {
3402
+        $last = true;
3403
+        foreach($sqls as $sql) {
3404
+            if(!($last = $this->query($sql, $dieOnError, $msg, $suppress))) {
3405
+                break;
3406
+            }
3407
+        }
3408
+        return $last;
3409
+    }
3410
+
3411
+    /**
3412
+     * Fetches the next row in the query result into an associative array
3413
+     *
3414
+     * @param  resource $result
3415
+     * @param  bool $encode Need to HTML-encode the result?
3416
+     * @return array    returns false if there are no more rows available to fetch
3417
+     */
3418
+    public function fetchByAssoc($result, $encode = true)
3419
+    {
3420
+        if (empty($result))	return false;
3421
+
3422
+        if(is_int($encode) && func_num_args() == 3) {
3423
+            // old API: $result, $rowNum, $encode
3424
+            $GLOBALS['log']->deprecated("Using row number in fetchByAssoc is not portable and no longer supported. Please fix your code.");
3425
+            $encode = func_get_arg(2);
3426
+        }
3427
+        $row = $this->fetchRow($result);
3428
+        if (!empty($row) && $encode && $this->encode) {
3429
+            return array_map('to_html', $row);
3430
+        } else {
3431
+            return $row;
3432
+        }
3433
+    }
3434
+
3435
+    /**
3436
+     * Get DB driver name used for install/upgrade scripts
3437
+     * @return string
3438
+     */
3439
+    public function getScriptName()
3440
+    {
3441
+        // Usually the same name as dbType
3442
+        return $this->dbType;
3443
+    }
3444
+
3445
+    /**
3446
+     * Set database options
3447
+     * Options are usually db-dependant and derive from $config['dbconfigoption']
3448
+     * @param array $options
3449
+     * @return DBManager
3450
+     */
3451
+    public function setOptions($options)
3452
+    {
3453
+        $this->options = $options;
3454
+        return $this;
3455
+    }
3456
+
3457
+    /**
3458
+     * Get DB options
3459
+     * @return array
3460
+     */
3461
+    public function getOptions()
3462
+    {
3463
+        return $this->options;
3464
+    }
3465
+
3466
+    /**
3467
+     * Get DB option by name
3468
+     * @param string $option Option name
3469
+     * @return mixed Option value or null if doesn't exist
3470
+     */
3471
+    public function getOption($option)
3472
+    {
3473
+        if(isset($this->options[$option])) {
3474
+            return $this->options[$option];
3475
+        }
3476
+        return null;
3477
+    }
3478
+
3479
+    /**
3480
+     * Commits pending changes to the database when the driver is setup to support transactions.
3481
+     * Note that the default implementation is applicable for transaction-less or auto commit scenarios.
3482
+     * @abstract
3483
+     * @return bool true if commit succeeded, false if it failed
3484
+     */
3485
+    public function commit()
3486
+    {
3487
+        $this->log->info("DBManager.commit() stub");
3488
+        return true;
3489
+    }
3490
+
3491
+    /**
3492
+     * Rollsback pending changes to the database when the driver is setup to support transactions.
3493
+     * Note that the default implementation is applicable for transaction-less or auto commit scenarios.
3494
+     * Since rollbacks cannot be done, this implementation always returns false.
3495
+     * @abstract
3496
+     * @return bool true if rollback succeeded, false if it failed
3497
+     */
3498
+    public function rollback()
3499
+    {
3500
+        $this->log->info("DBManager.rollback() stub");
3501
+        return false;
3502
+    }
3503
+
3504
+    /**
3505
+     * Check if this DB name is valid
3506
+     *
3507
+     * @param string $name
3508
+     * @return bool
3509
+     */
3510
+    public function isDatabaseNameValid($name)
3511
+    {
3512
+        // Generic case - no slashes, no dots
3513
+        return preg_match('#[/.\\\\]#', $name)==0;
3514
+    }
3515
+
3516
+    /**
3517
+     * Check special requirements for DB installation.
3518
+     * @abstract
3519
+     * If everything is OK, return true.
3520
+     * If something's wrong, return array of error code and parameters
3521
+     * @return mixed
3522
+     */
3523
+    public function canInstall()
3524
+    {
3525
+        return true;
3526
+    }
3527
+
3528
+    /**
3529
+     * @abstract
3530 3530
      * Code run on new database before installing
3531
-	 */
3532
-	public function preInstall()
3533
-	{
3534
-	}
3531
+     */
3532
+    public function preInstall()
3533
+    {
3534
+    }
3535
+
3536
+    /**
3537
+     * @abstract
3538
+     * Code run on new database after installing
3539
+     */
3540
+    public function postInstall()
3541
+    {
3542
+    }
3543
+
3544
+    /**
3545
+     * Disable keys on the table
3546
+     * @abstract
3547
+     * @param string $tableName
3548
+     */
3549
+    public function disableKeys($tableName)
3550
+    {
3551
+    }
3535 3552
 
3536
-	/**
3553
+    /**
3554
+     * Re-enable keys on the table
3537 3555
      * @abstract
3538
-	 * Code run on new database after installing
3539
-	 */
3540
-	public function postInstall()
3541
-	{
3542
-	}
3543
-
3544
-	/**
3545
-	 * Disable keys on the table
3546
-	 * @abstract
3547
-	 * @param string $tableName
3548
-	 */
3549
-	public function disableKeys($tableName)
3550
-	{
3551
-	}
3552
-
3553
-	/**
3554
-	 * Re-enable keys on the table
3555
-	 * @abstract
3556
-	 * @param string $tableName
3557
-	 */
3558
-	public function enableKeys($tableName)
3559
-	{
3560
-	}
3561
-
3562
-	/**
3563
-	 * Quote string in DB-specific manner
3564
-	 * @param string $string
3565
-	 * @return string
3566
-	 */
3567
-	abstract public function quote($string);
3556
+     * @param string $tableName
3557
+     */
3558
+    public function enableKeys($tableName)
3559
+    {
3560
+    }
3561
+
3562
+    /**
3563
+     * Quote string in DB-specific manner
3564
+     * @param string $string
3565
+     * @return string
3566
+     */
3567
+    abstract public function quote($string);
3568 3568
 
3569 3569
     abstract public function quoteIdentifier($string);
3570 3570
 
3571
-	/**
3572
-	 * Use when you need to convert a database string to a different value; this function does it in a
3573
-	 * database-backend aware way
3574
-	 * Supported conversions:
3575
-	 *      today		return current date
3576
-	 *      left		Take substring from the left
3577
-	 *      date_format	Format date as string, supports %Y-%m-%d, %Y-%m, %Y
3571
+    /**
3572
+     * Use when you need to convert a database string to a different value; this function does it in a
3573
+     * database-backend aware way
3574
+     * Supported conversions:
3575
+     *      today		return current date
3576
+     *      left		Take substring from the left
3577
+     *      date_format	Format date as string, supports %Y-%m-%d, %Y-%m, %Y
3578 3578
      *      time_format Format time as string
3579 3579
      *      date        Convert date string to datetime value
3580 3580
      *      time        Convert time string to datetime value
3581
-	 *      datetime	Convert datetime string to datetime value
3582
-	 *      ifnull		If var is null, use default value
3583
-	 *      concat		Concatenate strings
3584
-	 *      quarter		Quarter number of the date
3585
-	 *      length		Length of string
3586
-	 *      month		Month number of the date
3587
-	 *      add_date	Add specified interval to a date
3581
+     *      datetime	Convert datetime string to datetime value
3582
+     *      ifnull		If var is null, use default value
3583
+     *      concat		Concatenate strings
3584
+     *      quarter		Quarter number of the date
3585
+     *      length		Length of string
3586
+     *      month		Month number of the date
3587
+     *      add_date	Add specified interval to a date
3588 3588
      *      add_time    Add time interval to a date
3589 3589
      *      text2char   Convert text field to varchar
3590
-	 *
3591
-	 * @param string $string database string to convert
3592
-	 * @param string $type type of conversion to do
3593
-	 * @param array  $additional_parameters optional, additional parameters to pass to the db function
3594
-	 * @return string
3595
-	 */
3596
-	abstract public function convert($string, $type, array $additional_parameters = array());
3597
-
3598
-	/**
3599
-	 * Converts from Database data to app data
3600
-	 *
3601
-	 * Supported types
3602
-	 * - date
3603
-	 * - time
3604
-	 * - datetime
3590
+     *
3591
+     * @param string $string database string to convert
3592
+     * @param string $type type of conversion to do
3593
+     * @param array  $additional_parameters optional, additional parameters to pass to the db function
3594
+     * @return string
3595
+     */
3596
+    abstract public function convert($string, $type, array $additional_parameters = array());
3597
+
3598
+    /**
3599
+     * Converts from Database data to app data
3600
+     *
3601
+     * Supported types
3602
+     * - date
3603
+     * - time
3604
+     * - datetime
3605 3605
      * - datetimecombo
3606 3606
      * - timestamp
3607
-	 *
3608
-	 * @param string $string database string to convert
3609
-	 * @param string $type type of conversion to do
3610
-	 * @return string
3611
-	 */
3612
-	abstract public function fromConvert($string, $type);
3607
+     *
3608
+     * @param string $string database string to convert
3609
+     * @param string $type type of conversion to do
3610
+     * @return string
3611
+     */
3612
+    abstract public function fromConvert($string, $type);
3613 3613
 
3614 3614
     /**
3615 3615
      * Parses and runs queries
@@ -3621,7 +3621,7 @@  discard block
 block discarded – undo
3621 3621
      * @param  bool     $keepResult Keep query result in the object?
3622 3622
      * @return resource|bool result set or success/failure bool
3623 3623
      */
3624
-	abstract public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false);
3624
+    abstract public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false);
3625 3625
 
3626 3626
     /**
3627 3627
      * Runs a limit query: one where we specify where to start getting records and how many to get
@@ -3634,173 +3634,173 @@  discard block
 block discarded – undo
3634 3634
      * @param  bool     $execute Execute or return SQL?
3635 3635
      * @return resource query result
3636 3636
      */
3637
-	abstract function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true);
3638
-
3639
-
3640
-	/**
3641
-	 * Free Database result
3642
-	 * @param resource $dbResult
3643
-	 */
3644
-	abstract protected function freeDbResult($dbResult);
3645
-
3646
-	/**
3647
-	 * Rename column in the DB
3648
-	 * @param string $tablename
3649
-	 * @param string $column
3650
-	 * @param string $newname
3651
-	 */
3652
-	abstract function renameColumnSQL($tablename, $column, $newname);
3653
-
3654
-	/**
3655
-	 * Returns definitions of all indies for passed table.
3656
-	 *
3657
-	 * return will is a multi-dimensional array that
3658
-	 * categorizes the index definition by types, unique, primary and index.
3659
-	 * <code>
3660
-	 * <?php
3661
-	 * array(                                                              O
3662
-	 *       'index1'=> array (
3663
-	 *           'name'   => 'index1',
3664
-	 *           'type'   => 'primary',
3665
-	 *           'fields' => array('field1','field2')
3666
-	 *           )
3667
-	 *       )
3668
-	 * ?>
3669
-	 * </code>
3670
-	 * This format is similar to how indicies are defined in vardef file.
3671
-	 *
3672
-	 * @param  string $tablename
3673
-	 * @return array
3674
-	 */
3675
-	abstract public function get_indices($tablename);
3676
-
3677
-	/**
3678
-	 * Returns definitions of all indies for passed table.
3679
-	 *
3680
-	 * return will is a multi-dimensional array that
3681
-	 * categorizes the index definition by types, unique, primary and index.
3682
-	 * <code>
3683
-	 * <?php
3684
-	 * array(
3685
-	 *       'field1'=> array (
3686
-	 *           'name'   => 'field1',
3687
-	 *           'type'   => 'varchar',
3688
-	 *           'len' => '200'
3689
-	 *           )
3690
-	 *       )
3691
-	 * ?>
3692
-	 * </code>
3693
-	 * This format is similar to how indicies are defined in vardef file.
3694
-	 *
3695
-	 * @param  string $tablename
3696
-	 * @return array
3697
-	 */
3698
-	abstract public function get_columns($tablename);
3699
-
3700
-	/**
3701
-	 * Generates alter constraint statement given a table name and vardef definition.
3702
-	 *
3703
-	 * Supports both adding and droping a constraint.
3704
-	 *
3705
-	 * @param  string $table      tablename
3706
-	 * @param  array  $definition field definition
3707
-	 * @param  bool   $drop       true if we are dropping the constraint, false if we are adding it
3708
-	 * @return string SQL statement
3709
-	 */
3710
-	abstract public function add_drop_constraint($table, $definition, $drop = false);
3711
-
3712
-	/**
3713
-	 * Returns the description of fields based on the result
3714
-	 *
3715
-	 * @param  resource $result
3716
-	 * @param  boolean  $make_lower_case
3717
-	 * @return array field array
3718
-	 */
3719
-	abstract public function getFieldsArray($result, $make_lower_case = false);
3720
-
3721
-	/**
3722
-	 * Returns an array of tables for this database
3723
-	 *
3724
-	 * @return	array|false 	an array of with table names, false if no tables found
3725
-	 */
3726
-	abstract public function getTablesArray();
3727
-
3728
-	/**
3729
-	 * Return's the version of the database
3730
-	 *
3731
-	 * @return string
3732
-	 */
3733
-	abstract public function version();
3734
-
3735
-	/**
3736
-	 * Checks if a table with the name $tableName exists
3737
-	 * and returns true if it does or false otherwise
3738
-	 *
3739
-	 * @param  string $tableName
3740
-	 * @return bool
3741
-	 */
3742
-	abstract public function tableExists($tableName);
3743
-
3744
-	/**
3745
-	 * Fetches the next row in the query result into an associative array
3746
-	 *
3747
-	 * @param  resource $result
3748
-	 * @return array    returns false if there are no more rows available to fetch
3749
-	 */
3750
-	abstract public function fetchRow($result);
3751
-
3752
-	/**
3753
-	 * Connects to the database backend
3754
-	 *
3755
-	 * Takes in the database settings and opens a database connection based on those
3756
-	 * will open either a persistent or non-persistent connection.
3757
-	 * If a persistent connection is desired but not available it will defualt to non-persistent
3758
-	 *
3759
-	 * configOptions must include
3760
-	 * db_host_name - server ip
3761
-	 * db_user_name - database user name
3762
-	 * db_password - database password
3763
-	 *
3764
-	 * @param array   $configOptions
3765
-	 * @param boolean $dieOnError
3766
-	 */
3767
-	abstract public function connect(array $configOptions = null, $dieOnError = false);
3768
-
3769
-	/**
3770
-	 * Generates sql for create table statement for a bean.
3771
-	 *
3772
-	 * @param  string $tablename
3773
-	 * @param  array  $fieldDefs
3774
-	 * @param  array  $indices
3775
-	 * @return string SQL Create Table statement
3776
-	 */
3777
-	abstract public function createTableSQLParams($tablename, $fieldDefs, $indices);
3778
-
3779
-	/**
3780
-	 * Generates the SQL for changing columns
3781
-	 *
3782
-	 * @param string $tablename
3783
-	 * @param array  $fieldDefs
3784
-	 * @param string $action
3785
-	 * @param bool   $ignoreRequired Optional, true if we should ignor this being a required field
3786
-	 * @return string|array
3787
-	 */
3788
-	abstract protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false);
3789
-
3790
-	/**
3791
-	 * Disconnects from the database
3792
-	 *
3793
-	 * Also handles any cleanup needed
3794
-	 */
3795
-	abstract public function disconnect();
3796
-
3797
-	/**
3798
-	 * Get last database error
3799
-	 * This function should return last error as reported by DB driver
3800
-	 * and should return false if no error condition happened
3801
-	 * @return string|false Error message or false if no error happened
3802
-	 */
3803
-	abstract public function lastDbError();
3637
+    abstract function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true);
3638
+
3639
+
3640
+    /**
3641
+     * Free Database result
3642
+     * @param resource $dbResult
3643
+     */
3644
+    abstract protected function freeDbResult($dbResult);
3645
+
3646
+    /**
3647
+     * Rename column in the DB
3648
+     * @param string $tablename
3649
+     * @param string $column
3650
+     * @param string $newname
3651
+     */
3652
+    abstract function renameColumnSQL($tablename, $column, $newname);
3653
+
3654
+    /**
3655
+     * Returns definitions of all indies for passed table.
3656
+     *
3657
+     * return will is a multi-dimensional array that
3658
+     * categorizes the index definition by types, unique, primary and index.
3659
+     * <code>
3660
+     * <?php
3661
+     * array(                                                              O
3662
+     *       'index1'=> array (
3663
+     *           'name'   => 'index1',
3664
+     *           'type'   => 'primary',
3665
+     *           'fields' => array('field1','field2')
3666
+     *           )
3667
+     *       )
3668
+     * ?>
3669
+     * </code>
3670
+     * This format is similar to how indicies are defined in vardef file.
3671
+     *
3672
+     * @param  string $tablename
3673
+     * @return array
3674
+     */
3675
+    abstract public function get_indices($tablename);
3676
+
3677
+    /**
3678
+     * Returns definitions of all indies for passed table.
3679
+     *
3680
+     * return will is a multi-dimensional array that
3681
+     * categorizes the index definition by types, unique, primary and index.
3682
+     * <code>
3683
+     * <?php
3684
+     * array(
3685
+     *       'field1'=> array (
3686
+     *           'name'   => 'field1',
3687
+     *           'type'   => 'varchar',
3688
+     *           'len' => '200'
3689
+     *           )
3690
+     *       )
3691
+     * ?>
3692
+     * </code>
3693
+     * This format is similar to how indicies are defined in vardef file.
3694
+     *
3695
+     * @param  string $tablename
3696
+     * @return array
3697
+     */
3698
+    abstract public function get_columns($tablename);
3699
+
3700
+    /**
3701
+     * Generates alter constraint statement given a table name and vardef definition.
3702
+     *
3703
+     * Supports both adding and droping a constraint.
3704
+     *
3705
+     * @param  string $table      tablename
3706
+     * @param  array  $definition field definition
3707
+     * @param  bool   $drop       true if we are dropping the constraint, false if we are adding it
3708
+     * @return string SQL statement
3709
+     */
3710
+    abstract public function add_drop_constraint($table, $definition, $drop = false);
3711
+
3712
+    /**
3713
+     * Returns the description of fields based on the result
3714
+     *
3715
+     * @param  resource $result
3716
+     * @param  boolean  $make_lower_case
3717
+     * @return array field array
3718
+     */
3719
+    abstract public function getFieldsArray($result, $make_lower_case = false);
3720
+
3721
+    /**
3722
+     * Returns an array of tables for this database
3723
+     *
3724
+     * @return	array|false 	an array of with table names, false if no tables found
3725
+     */
3726
+    abstract public function getTablesArray();
3727
+
3728
+    /**
3729
+     * Return's the version of the database
3730
+     *
3731
+     * @return string
3732
+     */
3733
+    abstract public function version();
3734
+
3735
+    /**
3736
+     * Checks if a table with the name $tableName exists
3737
+     * and returns true if it does or false otherwise
3738
+     *
3739
+     * @param  string $tableName
3740
+     * @return bool
3741
+     */
3742
+    abstract public function tableExists($tableName);
3743
+
3744
+    /**
3745
+     * Fetches the next row in the query result into an associative array
3746
+     *
3747
+     * @param  resource $result
3748
+     * @return array    returns false if there are no more rows available to fetch
3749
+     */
3750
+    abstract public function fetchRow($result);
3751
+
3752
+    /**
3753
+     * Connects to the database backend
3754
+     *
3755
+     * Takes in the database settings and opens a database connection based on those
3756
+     * will open either a persistent or non-persistent connection.
3757
+     * If a persistent connection is desired but not available it will defualt to non-persistent
3758
+     *
3759
+     * configOptions must include
3760
+     * db_host_name - server ip
3761
+     * db_user_name - database user name
3762
+     * db_password - database password
3763
+     *
3764
+     * @param array   $configOptions
3765
+     * @param boolean $dieOnError
3766
+     */
3767
+    abstract public function connect(array $configOptions = null, $dieOnError = false);
3768
+
3769
+    /**
3770
+     * Generates sql for create table statement for a bean.
3771
+     *
3772
+     * @param  string $tablename
3773
+     * @param  array  $fieldDefs
3774
+     * @param  array  $indices
3775
+     * @return string SQL Create Table statement
3776
+     */
3777
+    abstract public function createTableSQLParams($tablename, $fieldDefs, $indices);
3778
+
3779
+    /**
3780
+     * Generates the SQL for changing columns
3781
+     *
3782
+     * @param string $tablename
3783
+     * @param array  $fieldDefs
3784
+     * @param string $action
3785
+     * @param bool   $ignoreRequired Optional, true if we should ignor this being a required field
3786
+     * @return string|array
3787
+     */
3788
+    abstract protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false);
3789
+
3790
+    /**
3791
+     * Disconnects from the database
3792
+     *
3793
+     * Also handles any cleanup needed
3794
+     */
3795
+    abstract public function disconnect();
3796
+
3797
+    /**
3798
+     * Get last database error
3799
+     * This function should return last error as reported by DB driver
3800
+     * and should return false if no error condition happened
3801
+     * @return string|false Error message or false if no error happened
3802
+     */
3803
+    abstract public function lastDbError();
3804 3804
 
3805 3805
     /**
3806 3806
      * Check if this query is valid
@@ -3808,82 +3808,82 @@  discard block
 block discarded – undo
3808 3808
      * @param string $query
3809 3809
      * @return bool
3810 3810
      */
3811
-	abstract public function validateQuery($query);
3812
-
3813
-	/**
3814
-	 * Check if this driver can be used
3815
-	 * @return bool
3816
-	 */
3817
-	abstract public function valid();
3818
-
3819
-	/**
3820
-	 * Check if certain database exists
3821
-	 * @param string $dbname
3822
-	 */
3823
-	abstract public function dbExists($dbname);
3824
-
3825
-	/**
3826
-	 * Get tables like expression
3827
-	 * @param string $like Expression describing tables
3828
-	 * @return array
3829
-	 */
3830
-	abstract public function tablesLike($like);
3831
-
3832
-	/**
3833
-	 * Create a database
3834
-	 * @param string $dbname
3835
-	 */
3836
-	abstract public function createDatabase($dbname);
3837
-
3838
-	/**
3839
-	 * Drop a database
3840
-	 * @param string $dbname
3841
-	 */
3842
-	abstract public function dropDatabase($dbname);
3843
-
3844
-	/**
3845
-	 * Get database configuration information (DB-dependent)
3846
-	 * @return array|null
3847
-	 */
3848
-	abstract public function getDbInfo();
3849
-
3850
-	/**
3851
-	 * Check if certain DB user exists
3852
-	 * @param string $username
3853
-	 */
3854
-	abstract public function userExists($username);
3855
-
3856
-	/**
3857
-	 * Create DB user
3858
-	 * @param string $database_name
3859
-	 * @param string $host_name
3860
-	 * @param string $user
3861
-	 * @param string $password
3862
-	 */
3863
-	abstract public function createDbUser($database_name, $host_name, $user, $password);
3864
-
3865
-	/**
3866
-	 * Check if the database supports fulltext indexing
3867
-	 * Note that database driver can be capable of supporting FT (see supports('fulltext))
3868
-	 * but particular instance can still have it disabled
3869
-	 * @return bool
3870
-	 */
3871
-	abstract public function full_text_indexing_installed();
3872
-
3873
-	/**
3874
-	 * Generate fulltext query from set of terms
3875
-	 * @param string $field Field to search against
3876
-	 * @param array $terms Search terms that may be or not be in the result
3877
-	 * @param array $must_terms Search terms that have to be in the result
3878
-	 * @param array $exclude_terms Search terms that have to be not in the result
3879
-	 */
3880
-	abstract public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array());
3881
-
3882
-	/**
3883
-	 * Get install configuration for this DB
3884
-	 * @return array
3885
-	 */
3886
-	abstract public function installConfig();
3811
+    abstract public function validateQuery($query);
3812
+
3813
+    /**
3814
+     * Check if this driver can be used
3815
+     * @return bool
3816
+     */
3817
+    abstract public function valid();
3818
+
3819
+    /**
3820
+     * Check if certain database exists
3821
+     * @param string $dbname
3822
+     */
3823
+    abstract public function dbExists($dbname);
3824
+
3825
+    /**
3826
+     * Get tables like expression
3827
+     * @param string $like Expression describing tables
3828
+     * @return array
3829
+     */
3830
+    abstract public function tablesLike($like);
3831
+
3832
+    /**
3833
+     * Create a database
3834
+     * @param string $dbname
3835
+     */
3836
+    abstract public function createDatabase($dbname);
3837
+
3838
+    /**
3839
+     * Drop a database
3840
+     * @param string $dbname
3841
+     */
3842
+    abstract public function dropDatabase($dbname);
3843
+
3844
+    /**
3845
+     * Get database configuration information (DB-dependent)
3846
+     * @return array|null
3847
+     */
3848
+    abstract public function getDbInfo();
3849
+
3850
+    /**
3851
+     * Check if certain DB user exists
3852
+     * @param string $username
3853
+     */
3854
+    abstract public function userExists($username);
3855
+
3856
+    /**
3857
+     * Create DB user
3858
+     * @param string $database_name
3859
+     * @param string $host_name
3860
+     * @param string $user
3861
+     * @param string $password
3862
+     */
3863
+    abstract public function createDbUser($database_name, $host_name, $user, $password);
3864
+
3865
+    /**
3866
+     * Check if the database supports fulltext indexing
3867
+     * Note that database driver can be capable of supporting FT (see supports('fulltext))
3868
+     * but particular instance can still have it disabled
3869
+     * @return bool
3870
+     */
3871
+    abstract public function full_text_indexing_installed();
3872
+
3873
+    /**
3874
+     * Generate fulltext query from set of terms
3875
+     * @param string $field Field to search against
3876
+     * @param array $terms Search terms that may be or not be in the result
3877
+     * @param array $must_terms Search terms that have to be in the result
3878
+     * @param array $exclude_terms Search terms that have to be not in the result
3879
+     */
3880
+    abstract public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array());
3881
+
3882
+    /**
3883
+     * Get install configuration for this DB
3884
+     * @return array
3885
+     */
3886
+    abstract public function installConfig();
3887 3887
 
3888 3888
     /**
3889 3889
      * Returns a DB specific FROM clause which can be used to select against functions.
@@ -3900,5 +3900,5 @@  discard block
 block discarded – undo
3900 3900
      * @abstract
3901 3901
      * @return string
3902 3902
      */
3903
-	abstract public function getGuidSQL();
3903
+    abstract public function getGuidSQL();
3904 3904
 }
Please login to merge, or discard this patch.
Spacing   +314 added lines, -314 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.
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 		}
315 315
 
316 316
 		$dberror = $this->lastDbError();
317
-		if($dberror === false) {
317
+		if ($dberror === false) {
318 318
     		$this->last_error = false;
319 319
 	    	return false;
320 320
 		}
@@ -332,16 +332,16 @@  discard block
 block discarded – undo
332 332
 	 */
333 333
 	protected function registerError($userMessage, $message, $dieOnError = false)
334 334
 	{
335
-		if(!empty($message)) {
336
-			if(!empty($userMessage)) {
335
+		if (!empty($message)) {
336
+			if (!empty($userMessage)) {
337 337
 				$message = "$userMessage: $message";
338 338
 			}
339
-			if(empty($message)) {
339
+			if (empty($message)) {
340 340
 			    $message = "Database error";
341 341
 			}
342 342
 			$this->log->fatal($message);
343 343
 			if ($dieOnError || $this->dieOnError) {
344
-				if(isset($GLOBALS['app_strings']['ERR_DB_FAIL'])) {
344
+				if (isset($GLOBALS['app_strings']['ERR_DB_FAIL'])) {
345 345
 					sugar_die($GLOBALS['app_strings']['ERR_DB_FAIL']);
346 346
 				} else {
347 347
 					sugar_die("Database error. Please check suitecrm.log for details.");
@@ -379,8 +379,8 @@  discard block
 block discarded – undo
379 379
 		$slow_query_time_msec = isset($sugar_config['slow_query_time_msec'])
380 380
 			? $sugar_config['slow_query_time_msec'] : 5000;
381 381
 
382
-		if($do_the_dump) {
383
-			if($slow_query_time_msec < ($this->query_time * 1000)) {
382
+		if ($do_the_dump) {
383
+			if ($slow_query_time_msec < ($this->query_time * 1000)) {
384 384
 				// Then log both the query and the query time
385 385
 				$this->log->fatal('Slow Query (time:'.$this->query_time."\n".$query);
386 386
 				return true;
@@ -412,20 +412,20 @@  discard block
 block discarded – undo
412 412
 		$indices = $GLOBALS['dictionary'][$object_name]['indices'];
413 413
 
414 414
 	if (empty($indices)) {
415
-		foreach ( $GLOBALS['dictionary'] as $current ) {
416
-			if ($current['table'] == $table){
415
+		foreach ($GLOBALS['dictionary'] as $current) {
416
+			if ($current['table'] == $table) {
417 417
 				$indices = $current['indices'];
418 418
 				break;
419 419
 			}
420 420
 		}
421 421
 	}
422 422
 	if (empty($indices)) {
423
-		$this->log->warn('CHECK QUERY: Could not find index definitions for table ' . $table);
423
+		$this->log->warn('CHECK QUERY: Could not find index definitions for table '.$table);
424 424
 		return false;
425 425
 	}
426 426
 	if (!empty($match[2][0])) {
427 427
 		$orderBys = explode(' ', $match[2][0]);
428
-		foreach ($orderBys as $orderBy){
428
+		foreach ($orderBys as $orderBy) {
429 429
 			$orderBy = trim($orderBy);
430 430
 			if (empty($orderBy))
431 431
 				continue;
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 			if ($orderBy == 'asc' || $orderBy == 'desc')
434 434
 				continue;
435 435
 
436
-			$orderBy = str_replace(array($table . '.', ','), '', $orderBy);
436
+			$orderBy = str_replace(array($table.'.', ','), '', $orderBy);
437 437
 
438 438
 			foreach ($indices as $index)
439 439
 				if (empty($index['db']) || $index['db'] == $this->dbType)
@@ -441,11 +441,11 @@  discard block
 block discarded – undo
441 441
 						if ($field == $orderBy)
442 442
 							return true;
443 443
 
444
-			$warning = 'Missing Index For Order By Table: ' . $table . ' Order By:' . $orderBy ;
444
+			$warning = 'Missing Index For Order By Table: '.$table.' Order By:'.$orderBy;
445 445
 			if (!empty($GLOBALS['sugar_config']['dump_slow_queries']))
446
-				$this->log->fatal('CHECK QUERY:' .$warning);
446
+				$this->log->fatal('CHECK QUERY:'.$warning);
447 447
 			else
448
-				$this->log->warn('CHECK QUERY:' .$warning);
448
+				$this->log->warn('CHECK QUERY:'.$warning);
449 449
 		}
450 450
 	}
451 451
 	return false;
@@ -491,9 +491,9 @@  discard block
 block discarded – undo
491 491
 	public function insert(SugarBean $bean)
492 492
 	{
493 493
 		$sql = $this->insertSQL($bean);
494
-		$tablename =  $bean->getTableName();
494
+		$tablename = $bean->getTableName();
495 495
 		$msg = "Error inserting into table: $tablename:";
496
-		return $this->query($sql,true,$msg);
496
+		return $this->query($sql, true, $msg);
497 497
 	}
498 498
 
499 499
 	/**
@@ -512,13 +512,13 @@  discard block
 block discarded – undo
512 512
 		{
513 513
 			if (isset($fieldDef['source']) && $fieldDef['source'] != 'db')  continue;
514 514
 			//custom fields handle there save seperatley
515
-			if(!empty($field_map) && !empty($field_map[$field]['custom_type'])) continue;
515
+			if (!empty($field_map) && !empty($field_map[$field]['custom_type'])) continue;
516 516
 
517
-			if(isset($data[$field])) {
517
+			if (isset($data[$field])) {
518 518
 				// clean the incoming value..
519 519
 				$val = from_html($data[$field]);
520 520
 			} else {
521
-				if(isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) {
521
+				if (isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) {
522 522
 					$val = $fieldDef['default'];
523 523
 				} else {
524 524
 					$val = null;
@@ -528,26 +528,26 @@  discard block
 block discarded – undo
528 528
 			//handle auto increment values here - we may have to do something like nextval for oracle
529 529
 			if (!empty($fieldDef['auto_increment'])) {
530 530
 				$auto = $this->getAutoIncrementSQL($table, $fieldDef['name']);
531
-				if(!empty($auto)) {
531
+				if (!empty($auto)) {
532 532
 					$values[$field] = $auto;
533 533
 				}
534 534
 			} elseif ($fieldDef['name'] == 'deleted') {
535 535
 				$values['deleted'] = (int)$val;
536 536
 			} else {
537 537
 				// need to do some thing about types of values
538
-				if(!is_null($val) || !empty($fieldDef['required'])) {
538
+				if (!is_null($val) || !empty($fieldDef['required'])) {
539 539
 					$values[$field] = $this->massageValue($val, $fieldDef);
540 540
 				}
541 541
 			}
542 542
 		}
543 543
 
544 544
 		if (empty($values))
545
-			return $execute?true:''; // no columns set
545
+			return $execute ?true:''; // no columns set
546 546
 
547 547
 		// get the entire sql
548 548
 		$query = "INSERT INTO $table (".implode(",", array_keys($values)).")
549 549
 					VALUES (".implode(",", $values).")";
550
-		return $execute?$this->query($query):$query;
550
+		return $execute ? $this->query($query) : $query;
551 551
 	}
552 552
 
553 553
     /**
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
 		$sql = $this->updateSQL($bean, $where);
566 566
 		$tablename = $bean->getTableName();
567 567
 		$msg = "Error updating table: $tablename:";
568
-		return $this->query($sql,true,$msg);
568
+		return $this->query($sql, true, $msg);
569 569
 	}
570 570
 
571 571
     /**
@@ -581,8 +581,8 @@  discard block
 block discarded – undo
581 581
 	{
582 582
 		$sql = $this->deleteSQL($bean, $where);
583 583
 		$tableName = $bean->getTableName();
584
-		$msg = "Error deleting from table: ".$tableName. ":";
585
-		return $this->query($sql,true,$msg);
584
+		$msg = "Error deleting from table: ".$tableName.":";
585
+		return $this->query($sql, true, $msg);
586 586
 	}
587 587
 
588 588
 	/**
@@ -599,8 +599,8 @@  discard block
 block discarded – undo
599 599
 	{
600 600
 		$sql = $this->retrieveSQL($bean, $where);
601 601
 		$tableName = $bean->getTableName();
602
-		$msg = "Error retriving values from table:".$tableName. ":";
603
-		return $this->query($sql,true,$msg);
602
+		$msg = "Error retriving values from table:".$tableName.":";
603
+		return $this->query($sql, true, $msg);
604 604
 	}
605 605
 
606 606
 	/**
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
 	{
624 624
 		$sql = $this->retrieveViewSQL($beans, $cols, $where);
625 625
 		$msg = "Error retriving values from View Collection:";
626
-		return $this->query($sql,true,$msg);
626
+		return $this->query($sql, true, $msg);
627 627
 	}
628 628
 
629 629
 
@@ -638,8 +638,8 @@  discard block
 block discarded – undo
638 638
 		$sql = $this->createTableSQL($bean);
639 639
 		$tablename = $bean->getTableName();
640 640
 		$msg = "Error creating table: $tablename:";
641
-		$this->query($sql,true,$msg);
642
-		if(!$this->supports("inline_keys")) {
641
+		$this->query($sql, true, $msg);
642
+		if (!$this->supports("inline_keys")) {
643 643
 		// handle constraints and indices
644 644
 			$indicesArr = $this->createConstraintSql($bean);
645 645
 			if (count($indicesArr) > 0)
@@ -676,9 +676,9 @@  discard block
 block discarded – undo
676 676
 			$res = true;
677 677
 			if ($sql) {
678 678
 				$msg = "Error creating table: $tablename";
679
-				$res = ($res and $this->query($sql,true,$msg));
679
+				$res = ($res and $this->query($sql, true, $msg));
680 680
 			}
681
-			if(!$this->supports("inline_keys")) {
681
+			if (!$this->supports("inline_keys")) {
682 682
 				// handle constraints and indices
683 683
 				$indicesArr = $this->getConstraintSql($indices, $tablename);
684 684
 				if (count($indicesArr) > 0)
@@ -705,20 +705,20 @@  discard block
 block discarded – undo
705 705
 
706 706
 		//Clean the indexes to prevent duplicate definitions
707 707
 		$new_index = array();
708
-		foreach($indices as $ind_def){
708
+		foreach ($indices as $ind_def) {
709 709
 			$new_index[$ind_def['name']] = $ind_def;
710 710
 		}
711 711
 		//jc: added this for beans that do not actually have a table, namely
712 712
 		//ForecastOpportunities
713
-		if($tablename == 'does_not_exist' || $tablename == '')
713
+		if ($tablename == 'does_not_exist' || $tablename == '')
714 714
 			return '';
715 715
 
716 716
 		global $dictionary;
717
-		$engine=null;
718
-		if (isset($dictionary[$bean->getObjectName()]['engine']) && !empty($dictionary[$bean->getObjectName()]['engine']) )
717
+		$engine = null;
718
+		if (isset($dictionary[$bean->getObjectName()]['engine']) && !empty($dictionary[$bean->getObjectName()]['engine']))
719 719
 			$engine = $dictionary[$bean->getObjectName()]['engine'];
720 720
 
721
-		return $this->repairTableParams($tablename, $fielddefs,$new_index,$execute,$engine);
721
+		return $this->repairTableParams($tablename, $fielddefs, $new_index, $execute, $engine);
722 722
 	}
723 723
 
724 724
 	/**
@@ -730,12 +730,12 @@  discard block
 block discarded – undo
730 730
 	protected function isNullable($vardef)
731 731
 	{
732 732
 
733
-		if(isset($vardef['isnull']) && (strtolower($vardef['isnull']) == 'false' || $vardef['isnull'] === false)
733
+		if (isset($vardef['isnull']) && (strtolower($vardef['isnull']) == 'false' || $vardef['isnull'] === false)
734 734
 			&& !empty($vardef['required'])) {
735 735
 				/* required + is_null=false => not null */
736 736
 			return false;
737 737
 		}
738
-		if(empty($vardef['auto_increment']) && (empty($vardef['type']) || $vardef['type'] != 'id')
738
+		if (empty($vardef['auto_increment']) && (empty($vardef['type']) || $vardef['type'] != 'id')
739 739
 					&& (empty($vardef['dbType']) || $vardef['dbType'] != 'id')
740 740
 					&& (empty($vardef['name']) || ($vardef['name'] != 'id' && $vardef['name'] != 'deleted'))
741 741
 		) {
@@ -756,7 +756,7 @@  discard block
 block discarded – undo
756 756
      * @todo: refactor engine param to be more generic
757 757
      * @return string
758 758
      */
759
-	public function repairTableParams($tablename, $fielddefs,  $indices, $execute = true, $engine = null)
759
+	public function repairTableParams($tablename, $fielddefs, $indices, $execute = true, $engine = null)
760 760
 	{
761 761
 		//jc: had a bug when running the repair if the tablename is blank the repair will
762 762
 		//fail when it tries to create a repair table
@@ -766,13 +766,13 @@  discard block
 block discarded – undo
766 766
 		//if the table does not exist create it and we are done
767 767
 		$sql = "/* Table : $tablename */\n";
768 768
 		if (!$this->tableExists($tablename)) {
769
-			$createtablesql = $this->createTableSQLParams($tablename,$fielddefs,$indices,$engine);
770
-			if($execute && $createtablesql){
771
-				$this->createTableParams($tablename,$fielddefs,$indices,$engine);
769
+			$createtablesql = $this->createTableSQLParams($tablename, $fielddefs, $indices, $engine);
770
+			if ($execute && $createtablesql) {
771
+				$this->createTableParams($tablename, $fielddefs, $indices, $engine);
772 772
 			}
773 773
 
774 774
 			$sql .= "/* MISSING TABLE: {$tablename} */\n";
775
-			$sql .= $createtablesql . "\n";
775
+			$sql .= $createtablesql."\n";
776 776
 			return $sql;
777 777
 		}
778 778
 
@@ -782,7 +782,7 @@  discard block
 block discarded – undo
782 782
 		$take_action = false;
783 783
 
784 784
 		// do column comparisons
785
-		$sql .=	"/*COLUMNS*/\n";
785
+		$sql .= "/*COLUMNS*/\n";
786 786
 		foreach ($fielddefs as $name => $value) {
787 787
 			if (isset($value['source']) && $value['source'] != 'db')
788 788
 				continue;
@@ -801,9 +801,9 @@  discard block
 block discarded – undo
801 801
 
802 802
 			$name = strtolower($value['name']);
803 803
 			// add or fix the field defs per what the DB is expected to give us back
804
-			$this->massageFieldDef($value,$tablename);
804
+			$this->massageFieldDef($value, $tablename);
805 805
 
806
-			$ignorerequired=false;
806
+			$ignorerequired = false;
807 807
 
808 808
 			//Do not track requiredness in the DB, auto_increment, ID,
809 809
 			// and deleted fields are always required in the DB, so don't force those
@@ -819,32 +819,32 @@  discard block
 block discarded – undo
819 819
 				$value['required'] = $compareFieldDefs[$name]['required'];
820 820
 			}
821 821
 
822
-			if ( !isset($compareFieldDefs[$name]) ) {
822
+			if (!isset($compareFieldDefs[$name])) {
823 823
 				// ok we need this field lets create it
824
-				$sql .=	"/*MISSING IN DATABASE - $name -  ROW*/\n";
825
-				$sql .= $this->addColumnSQL($tablename, $value) .  "\n";
824
+				$sql .= "/*MISSING IN DATABASE - $name -  ROW*/\n";
825
+				$sql .= $this->addColumnSQL($tablename, $value)."\n";
826 826
 				if ($execute)
827 827
 					$this->addColumn($tablename, $value);
828 828
 				$take_action = true;
829
-			} elseif ( !$this->compareVarDefs($compareFieldDefs[$name],$value)) {
829
+			} elseif (!$this->compareVarDefs($compareFieldDefs[$name], $value)) {
830 830
 				//fields are different lets alter it
831
-				$sql .=	"/*MISMATCH WITH DATABASE - $name -  ROW ";
832
-				foreach($compareFieldDefs[$name] as $rKey => $rValue) {
833
-					$sql .=	"[$rKey] => '$rValue'  ";
831
+				$sql .= "/*MISMATCH WITH DATABASE - $name -  ROW ";
832
+				foreach ($compareFieldDefs[$name] as $rKey => $rValue) {
833
+					$sql .= "[$rKey] => '$rValue'  ";
834 834
 				}
835
-				$sql .=	"*/\n";
836
-				$sql .=	"/* VARDEF - $name -  ROW";
837
-				foreach($value as $rKey => $rValue) {
838
-					$sql .=	"[$rKey] => '$rValue'  ";
835
+				$sql .= "*/\n";
836
+				$sql .= "/* VARDEF - $name -  ROW";
837
+				foreach ($value as $rKey => $rValue) {
838
+					$sql .= "[$rKey] => '$rValue'  ";
839 839
 				}
840
-				$sql .=	"*/\n";
840
+				$sql .= "*/\n";
841 841
 
842 842
 				//jc: oracle will complain if you try to execute a statement that sets a column to (not) null
843 843
 				//when it is already (not) null
844
-				if ( isset($value['isnull']) && isset($compareFieldDefs[$name]['isnull']) &&
844
+				if (isset($value['isnull']) && isset($compareFieldDefs[$name]['isnull']) &&
845 845
 					$value['isnull'] === $compareFieldDefs[$name]['isnull']) {
846 846
 					unset($value['required']);
847
-					$ignorerequired=true;
847
+					$ignorerequired = true;
848 848
 				}
849 849
 
850 850
 				//dwheeler: Once a column has been defined as null, we cannot try to force it back to !null
@@ -853,12 +853,12 @@  discard block
 block discarded – undo
853 853
 				{
854 854
 					$ignorerequired = true;
855 855
 				}
856
-				$altersql = $this->alterColumnSQL($tablename, $value,$ignorerequired);
857
-				if(is_array($altersql)) {
856
+				$altersql = $this->alterColumnSQL($tablename, $value, $ignorerequired);
857
+				if (is_array($altersql)) {
858 858
 					$altersql = join("\n", $altersql);
859 859
 				}
860
-				$sql .= $altersql .  "\n";
861
-				if($execute){
860
+				$sql .= $altersql."\n";
861
+				if ($execute) {
862 862
 					$this->alterColumn($tablename, $value, $ignorerequired);
863 863
 				}
864 864
 				$take_action = true;
@@ -866,13 +866,13 @@  discard block
 block discarded – undo
866 866
 		}
867 867
 
868 868
 		// do index comparisons
869
-		$sql .=	"/* INDEXES */\n";
869
+		$sql .= "/* INDEXES */\n";
870 870
 		$correctedIndexs = array();
871 871
 
872 872
         $compareIndices_case_insensitive = array();
873 873
 
874 874
 		// do indices comparisons case-insensitive
875
-		foreach($compareIndices as $k => $value){
875
+		foreach ($compareIndices as $k => $value) {
876 876
 			$value['name'] = strtolower($value['name']);
877 877
 			$compareIndices_case_insensitive[strtolower($k)] = $value;
878 878
 		}
@@ -899,59 +899,59 @@  discard block
 block discarded – undo
899 899
 				continue;
900 900
 
901 901
 			//database helpers do not know how to handle full text indices
902
-			if ($value['type']=='fulltext')
902
+			if ($value['type'] == 'fulltext')
903 903
 				continue;
904 904
 
905
-			if ( in_array($value['type'],array('alternate_key','foreign')) )
905
+			if (in_array($value['type'], array('alternate_key', 'foreign')))
906 906
 				$value['type'] = 'index';
907 907
 
908
-			if ( !isset($compareIndices[$name]) ) {
908
+			if (!isset($compareIndices[$name])) {
909 909
 				//First check if an index exists that doesn't match our name, if so, try to rename it
910 910
 				$found = false;
911 911
 				foreach ($compareIndices as $ex_name => $ex_value) {
912
-					if($this->compareVarDefs($ex_value, $value, true)) {
912
+					if ($this->compareVarDefs($ex_value, $value, true)) {
913 913
 						$found = $ex_name;
914 914
 						break;
915 915
 					}
916 916
 				}
917 917
 				if ($found) {
918
-					$sql .=	 "/*MISSNAMED INDEX IN DATABASE - $name - $ex_name */\n";
918
+					$sql .= "/*MISSNAMED INDEX IN DATABASE - $name - $ex_name */\n";
919 919
 					$rename = $this->renameIndexDefs($ex_value, $value, $tablename);
920
-					if($execute) {
920
+					if ($execute) {
921 921
 						$this->query($rename, true, "Cannot rename index");
922 922
 					}
923
-					$sql .= is_array($rename)?join("\n", $rename). "\n":$rename."\n";
923
+					$sql .= is_array($rename) ?join("\n", $rename)."\n" : $rename."\n";
924 924
 
925 925
 				} else {
926 926
 					// ok we need this field lets create it
927
-					$sql .=	 "/*MISSING INDEX IN DATABASE - $name -{$value['type']}  ROW */\n";
928
-					$sql .= $this->addIndexes($tablename,array($value), $execute) .  "\n";
927
+					$sql .= "/*MISSING INDEX IN DATABASE - $name -{$value['type']}  ROW */\n";
928
+					$sql .= $this->addIndexes($tablename, array($value), $execute)."\n";
929 929
 				}
930 930
 				$take_action = true;
931 931
 				$correctedIndexs[$name] = true;
932
-			} elseif ( !$this->compareVarDefs($compareIndices[$name],$value) ) {
932
+			} elseif (!$this->compareVarDefs($compareIndices[$name], $value)) {
933 933
 				// fields are different lets alter it
934
-				$sql .=	"/*INDEX MISMATCH WITH DATABASE - $name -  ROW ";
934
+				$sql .= "/*INDEX MISMATCH WITH DATABASE - $name -  ROW ";
935 935
 				foreach ($compareIndices[$name] as $n1 => $t1) {
936
-					$sql .=	 "<$n1>";
937
-					if ( $n1 == 'fields' )
938
-						foreach($t1 as $rKey => $rValue)
936
+					$sql .= "<$n1>";
937
+					if ($n1 == 'fields')
938
+						foreach ($t1 as $rKey => $rValue)
939 939
 							$sql .= "[$rKey] => '$rValue'  ";
940 940
 					else
941 941
 						$sql .= " $t1 ";
942 942
 				}
943
-				$sql .=	"*/\n";
944
-				$sql .=	"/* VARDEF - $name -  ROW";
943
+				$sql .= "*/\n";
944
+				$sql .= "/* VARDEF - $name -  ROW";
945 945
 				foreach ($value as $n1 => $t1) {
946
-					$sql .=	"<$n1>";
947
-					if ( $n1 == 'fields' )
946
+					$sql .= "<$n1>";
947
+					if ($n1 == 'fields')
948 948
 						foreach ($t1 as $rKey => $rValue)
949
-							$sql .=	"[$rKey] => '$rValue'  ";
949
+							$sql .= "[$rKey] => '$rValue'  ";
950 950
 					else
951 951
 						$sql .= " $t1 ";
952 952
 				}
953
-				$sql .=	"*/\n";
954
-				$sql .= $this->modifyIndexes($tablename,array($value), $execute) .  "\n";
953
+				$sql .= "*/\n";
954
+				$sql .= $this->modifyIndexes($tablename, array($value), $execute)."\n";
955 955
 				$take_action = true;
956 956
 				$correctedIndexs[$name] = true;
957 957
 			}
@@ -970,7 +970,7 @@  discard block
 block discarded – undo
970 970
      */
971 971
 	public function compareVarDefs($fielddef1, $fielddef2, $ignoreName = false)
972 972
 	{
973
-		foreach ( $fielddef1 as $key => $value ) {
973
+		foreach ($fielddef1 as $key => $value) {
974 974
 			if ($key == 'name' && $ignoreName)
975 975
 				continue;
976 976
             if (isset($fielddef2[$key]))
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
                 }
985 985
                 else
986 986
                 {
987
-                    if (array_map('strtolower', $fielddef1[$key]) == array_map('strtolower',$fielddef2[$key]))
987
+                    if (array_map('strtolower', $fielddef1[$key]) == array_map('strtolower', $fielddef2[$key]))
988 988
                     {
989 989
                         continue;
990 990
                     }
@@ -1033,9 +1033,9 @@  discard block
 block discarded – undo
1033 1033
 				}
1034 1034
 				else {
1035 1035
 					$returnArray['msg'] = 'match';
1036
-					foreach($row1 as $key => $value){
1036
+					foreach ($row1 as $key => $value) {
1037 1037
 						//ignore keys when checking we will check them when we do the index check
1038
-						if( !isset($ignore_filter[$key]) && (!isset($row2[$key]) || $row1[$key] !== $row2[$key])){
1038
+						if (!isset($ignore_filter[$key]) && (!isset($row2[$key]) || $row1[$key] !== $row2[$key])) {
1039 1039
 							$returnArray['msg'] = 'no_match';
1040 1040
 						}
1041 1041
 					}
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
 		$sql = $this->createIndexSQL($bean, $fieldDefs, $name, $unique);
1112 1112
 		$tablename = $bean->getTableName();
1113 1113
 		$msg = "Error creating index $name on table: $tablename:";
1114
-		return $this->query($sql,true,$msg);
1114
+		return $this->query($sql, true, $msg);
1115 1115
 	}
1116 1116
 
1117 1117
 	/**
@@ -1128,14 +1128,14 @@  discard block
 block discarded – undo
1128 1128
 		$columns = array();
1129 1129
 
1130 1130
 		foreach ($indices as $index) {
1131
-			if(!empty($index['db']) && $index['db'] != $this->dbType)
1131
+			if (!empty($index['db']) && $index['db'] != $this->dbType)
1132 1132
 				continue;
1133 1133
 			if (isset($index['source']) && $index['source'] != 'db')
1134 1134
 			continue;
1135 1135
 
1136 1136
 			$sql = $this->add_drop_constraint($table, $index);
1137 1137
 
1138
-			if(!empty($sql)) {
1138
+			if (!empty($sql)) {
1139 1139
 				$columns[] = $sql;
1140 1140
 			}
1141 1141
 		}
@@ -1155,11 +1155,11 @@  discard block
 block discarded – undo
1155 1155
 	{
1156 1156
 		$alters = $this->getConstraintSql($indexes, $tablename);
1157 1157
 		if ($execute) {
1158
-			foreach($alters as $sql) {
1158
+			foreach ($alters as $sql) {
1159 1159
 				$this->query($sql, true, "Error adding index: ");
1160 1160
 			}
1161 1161
 		}
1162
-		if(!empty($alters)) {
1162
+		if (!empty($alters)) {
1163 1163
 			$sql = join(";\n", $alters).";\n";
1164 1164
 		} else {
1165 1165
 			$sql = '';
@@ -1179,17 +1179,17 @@  discard block
 block discarded – undo
1179 1179
 	{
1180 1180
 		$sqls = array();
1181 1181
 		foreach ($indexes as $index) {
1182
-			$name =$index['name'];
1183
-			$sqls[$name] = $this->add_drop_constraint($tablename,$index,true);
1182
+			$name = $index['name'];
1183
+			$sqls[$name] = $this->add_drop_constraint($tablename, $index, true);
1184 1184
 		}
1185 1185
 		if (!empty($sqls) && $execute) {
1186
-			foreach($sqls as $name => $sql) {
1186
+			foreach ($sqls as $name => $sql) {
1187 1187
 				unset(self::$index_descriptions[$tablename][$name]);
1188 1188
 				$this->query($sql);
1189 1189
 			}
1190 1190
 		}
1191
-		if(!empty($sqls)) {
1192
-			return join(";\n",$sqls).";";
1191
+		if (!empty($sqls)) {
1192
+			return join(";\n", $sqls).";";
1193 1193
 		} else {
1194 1194
 			return '';
1195 1195
 		}
@@ -1219,7 +1219,7 @@  discard block
 block discarded – undo
1219 1219
 	public function addColumn($tablename, $fieldDefs)
1220 1220
 	{
1221 1221
 		$sql = $this->addColumnSQL($tablename, $fieldDefs);
1222
-		if ($this->isFieldArray($fieldDefs)){
1222
+		if ($this->isFieldArray($fieldDefs)) {
1223 1223
 			$columns = array();
1224 1224
 			foreach ($fieldDefs as $fieldDef)
1225 1225
 				$columns[] = $fieldDef['name'];
@@ -1229,7 +1229,7 @@  discard block
 block discarded – undo
1229 1229
 			$columns = $fieldDefs['name'];
1230 1230
 		}
1231 1231
 		$msg = "Error adding column(s) $columns on table: $tablename:";
1232
-		return $this->query($sql,true,$msg);
1232
+		return $this->query($sql, true, $msg);
1233 1233
 	}
1234 1234
 
1235 1235
 	/**
@@ -1242,8 +1242,8 @@  discard block
 block discarded – undo
1242 1242
      */
1243 1243
 	public function alterColumn($tablename, $newFieldDef, $ignoreRequired = false)
1244 1244
 	{
1245
-		$sql = $this->alterColumnSQL($tablename, $newFieldDef,$ignoreRequired);
1246
-		if ($this->isFieldArray($newFieldDef)){
1245
+		$sql = $this->alterColumnSQL($tablename, $newFieldDef, $ignoreRequired);
1246
+		if ($this->isFieldArray($newFieldDef)) {
1247 1247
 			$columns = array();
1248 1248
 			foreach ($newFieldDef as $fieldDef) {
1249 1249
 				$columns[] = $fieldDef['name'];
@@ -1255,8 +1255,8 @@  discard block
 block discarded – undo
1255 1255
 		}
1256 1256
 
1257 1257
 		$msg = "Error altering column(s) $columns on table: $tablename:";
1258
-		$res = $this->query($sql,true,$msg);
1259
-		if($res) {
1258
+		$res = $this->query($sql, true, $msg);
1259
+		if ($res) {
1260 1260
 			$this->getTableDescription($tablename, true); // reload table description after altering
1261 1261
 		}
1262 1262
 		return $res;
@@ -1282,7 +1282,7 @@  discard block
 block discarded – undo
1282 1282
 	public function dropTableName($name)
1283 1283
 	{
1284 1284
 		$sql = $this->dropTableNameSQL($name);
1285
-		return $this->query($sql,true,"Error dropping table $name:");
1285
+		return $this->query($sql, true, "Error dropping table $name:");
1286 1286
 	}
1287 1287
 
1288 1288
     /**
@@ -1297,7 +1297,7 @@  discard block
 block discarded – undo
1297 1297
 		$tablename = $bean->getTableName();
1298 1298
 		$sql = $this->dropColumnSQL($tablename, $fieldDefs);
1299 1299
 		$msg = "Error deleting column(s) on table: $tablename:";
1300
-		return $this->query($sql,true,$msg);
1300
+		return $this->query($sql, true, $msg);
1301 1301
 	}
1302 1302
 
1303 1303
     /**
@@ -1325,18 +1325,18 @@  discard block
 block discarded – undo
1325 1325
 
1326 1326
 		$rows_found = 0;
1327 1327
 		$count_query = $bean->create_list_count_query($select_query);
1328
-		if(!empty($count_query))
1328
+		if (!empty($count_query))
1329 1329
 		{
1330 1330
 			// We have a count query.  Run it and get the results.
1331 1331
 			$result = $this->query($count_query, true, "Error running count query for $this->object_name List: ");
1332 1332
 			$assoc = $this->fetchByAssoc($result);
1333
-			if(!empty($assoc['c']))
1333
+			if (!empty($assoc['c']))
1334 1334
 			{
1335 1335
 				$rows_found = $assoc['c'];
1336 1336
 			}
1337 1337
 		}
1338
-		if($count == -1){
1339
-			$count 	= $sugar_config['list_max_entries_per_page'];
1338
+		if ($count == -1) {
1339
+			$count = $sugar_config['list_max_entries_per_page'];
1340 1340
 		}
1341 1341
 		$next_offset = $start + $count;
1342 1342
 
@@ -1349,13 +1349,13 @@  discard block
 block discarded – undo
1349 1349
 		$fields = $bean->getFieldDefinitions();
1350 1350
 		$custom_fields = array();
1351 1351
 
1352
-		if($bean->hasCustomFields()){
1353
-			foreach ($fields as $fieldDef){
1354
-				if($fieldDef['source'] == 'custom_fields'){
1352
+		if ($bean->hasCustomFields()) {
1353
+			foreach ($fields as $fieldDef) {
1354
+				if ($fieldDef['source'] == 'custom_fields') {
1355 1355
 					$custom_fields[$fieldDef['name']] = $fieldDef['name'];
1356 1356
 				}
1357 1357
 			}
1358
-			if(!empty($custom_fields)){
1358
+			if (!empty($custom_fields)) {
1359 1359
 				$custom_fields['id_c'] = 'id_c';
1360 1360
 				$id_field = array('name' => 'id_c', 'custom_type' => 'id',);
1361 1361
 				$fields[] = $id_field;
@@ -1368,50 +1368,50 @@  discard block
 block discarded – undo
1368 1368
 		$cstm_row_array = array();
1369 1369
 		$cstm_columns = array();
1370 1370
 		$built_columns = false;
1371
-		while(($row = $this->fetchByAssoc($result)) != null)
1371
+		while (($row = $this->fetchByAssoc($result)) != null)
1372 1372
 		{
1373 1373
 			$values = array();
1374 1374
 			$cstm_values = array();
1375
-			if(!$is_related_query){
1375
+			if (!$is_related_query) {
1376 1376
 				foreach ($fields as $fieldDef)
1377 1377
 				{
1378
-					if(isset($fieldDef['source']) && $fieldDef['source'] != 'db' && $fieldDef['source'] != 'custom_fields') continue;
1378
+					if (isset($fieldDef['source']) && $fieldDef['source'] != 'db' && $fieldDef['source'] != 'custom_fields') continue;
1379 1379
 					$val = $row[$fieldDef['name']];
1380 1380
 
1381 1381
 					//handle auto increment values here only need to do this on insert not create
1382
-					if ($fieldDef['name'] == 'deleted'){
1382
+					if ($fieldDef['name'] == 'deleted') {
1383 1383
 							$values['deleted'] = $val;
1384
-							if(!$built_columns){
1384
+							if (!$built_columns) {
1385 1385
 							$columns[] = 'deleted';
1386 1386
 						}
1387 1387
 					}
1388 1388
 					else
1389 1389
 					{
1390 1390
 						$type = $fieldDef['type'];
1391
-						if(!empty($fieldDef['custom_type'])){
1391
+						if (!empty($fieldDef['custom_type'])) {
1392 1392
 							$type = $fieldDef['custom_type'];
1393 1393
 						}
1394 1394
 						// need to do some thing about types of values
1395
-						if($this->dbType == 'mysql' && $val == '' && ($type == 'datetime' ||  $type == 'date' || $type == 'int' || $type == 'currency' || $type == 'decimal')){
1396
-							if(!empty($custom_fields[$fieldDef['name']]))
1395
+						if ($this->dbType == 'mysql' && $val == '' && ($type == 'datetime' || $type == 'date' || $type == 'int' || $type == 'currency' || $type == 'decimal')) {
1396
+							if (!empty($custom_fields[$fieldDef['name']]))
1397 1397
 								$cstm_values[$fieldDef['name']] = 'null';
1398 1398
 							else
1399 1399
 								$values[$fieldDef['name']] = 'null';
1400
-						}else{
1401
-							if(isset($type) && $type=='int') {
1402
-								if(!empty($custom_fields[$fieldDef['name']]))
1400
+						} else {
1401
+							if (isset($type) && $type == 'int') {
1402
+								if (!empty($custom_fields[$fieldDef['name']]))
1403 1403
 									$cstm_values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1404 1404
 								else
1405 1405
 									$values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1406 1406
 							} else {
1407
-								if(!empty($custom_fields[$fieldDef['name']]))
1407
+								if (!empty($custom_fields[$fieldDef['name']]))
1408 1408
 									$cstm_values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1409 1409
 								else
1410 1410
 									$values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1411 1411
 							}
1412 1412
 						}
1413
-						if(!$built_columns){
1414
-							if(!empty($custom_fields[$fieldDef['name']]))
1413
+						if (!$built_columns) {
1414
+							if (!empty($custom_fields[$fieldDef['name']]))
1415 1415
 								$cstm_columns[] = $fieldDef['name'];
1416 1416
 							else
1417 1417
 								$columns[] = $fieldDef['name'];
@@ -1422,19 +1422,19 @@  discard block
 block discarded – undo
1422 1422
 			} else {
1423 1423
 			foreach ($row as $key=>$val)
1424 1424
 			{
1425
-					if($key != 'orc_row'){
1425
+					if ($key != 'orc_row') {
1426 1426
 						$values[$key] = "'$val'";
1427
-						if(!$built_columns){
1427
+						if (!$built_columns) {
1428 1428
 							$columns[] = $key;
1429 1429
 						}
1430 1430
 					}
1431 1431
 			}
1432 1432
 			}
1433 1433
 			$built_columns = true;
1434
-			if(!empty($values)){
1434
+			if (!empty($values)) {
1435 1435
 				$row_array[] = $values;
1436 1436
 			}
1437
-			if(!empty($cstm_values) && !empty($cstm_values['id_c']) && (strlen($cstm_values['id_c']) > 7)){
1437
+			if (!empty($cstm_values) && !empty($cstm_values['id_c']) && (strlen($cstm_values['id_c']) > 7)) {
1438 1438
 				$cstm_row_array[] = $cstm_values;
1439 1439
 			}
1440 1440
 		}
@@ -1444,9 +1444,9 @@  discard block
 block discarded – undo
1444 1444
 		// get the entire sql
1445 1445
 		$sql .= "(".implode(",", $columns).") ";
1446 1446
 		$sql .= "VALUES";
1447
-		for($i = 0; $i < count($row_array); $i++){
1447
+		for ($i = 0; $i < count($row_array); $i++) {
1448 1448
 			$sql .= " (".implode(",", $row_array[$i]).")";
1449
-			if($i < (count($row_array) - 1)){
1449
+			if ($i < (count($row_array) - 1)) {
1450 1450
 				$sql .= ", ";
1451 1451
 			}
1452 1452
 		}
@@ -1455,9 +1455,9 @@  discard block
 block discarded – undo
1455 1455
 		$custom_sql .= "(".implode(",", $cstm_columns).") ";
1456 1456
 		$custom_sql .= "VALUES";
1457 1457
 
1458
-		for($i = 0; $i < count($cstm_row_array); $i++){
1458
+		for ($i = 0; $i < count($cstm_row_array); $i++) {
1459 1459
 			$custom_sql .= " (".implode(",", $cstm_row_array[$i]).")";
1460
-			if($i < (count($cstm_row_array) - 1)){
1460
+			if ($i < (count($cstm_row_array) - 1)) {
1461 1461
 				$custom_sql .= ", ";
1462 1462
 			}
1463 1463
 		}
@@ -1550,17 +1550,17 @@  discard block
 block discarded – undo
1550 1550
      */
1551 1551
     public function quoteType($type, $value)
1552 1552
 	{
1553
-	    if($type == 'date') {
1553
+	    if ($type == 'date') {
1554 1554
 	        return $this->convert($this->quoted($value), "date");
1555 1555
 	    }
1556
-	    if($type == 'time') {
1556
+	    if ($type == 'time') {
1557 1557
 	        return $this->convert($this->quoted($value), "time");
1558 1558
 	    }
1559
-        if(isset($this->type_class[$type]) &&  $this->type_class[$type] == "date") {
1559
+        if (isset($this->type_class[$type]) && $this->type_class[$type] == "date") {
1560 1560
             return $this->convert($this->quoted($value), "datetime");
1561 1561
         }
1562
-        if($this->isNumericType($type)) {
1563
-            return 0+$value; // ensure it's numeric
1562
+        if ($this->isNumericType($type)) {
1563
+            return 0 + $value; // ensure it's numeric
1564 1564
         }
1565 1565
 
1566 1566
         return $this->quoted($value);
@@ -1576,7 +1576,7 @@  discard block
 block discarded – undo
1576 1576
      */
1577 1577
 	public function arrayQuote(array &$array)
1578 1578
 	{
1579
-		foreach($array as &$val) {
1579
+		foreach ($array as &$val) {
1580 1580
 			$val = $this->quote($val);
1581 1581
 		}
1582 1582
 		return $array;
@@ -1589,10 +1589,10 @@  discard block
 block discarded – undo
1589 1589
      */
1590 1590
 	protected function freeResult($result = false)
1591 1591
 	{
1592
-		if($result) {
1592
+		if ($result) {
1593 1593
 			$this->freeDbResult($result);
1594 1594
 		}
1595
-		if($this->lastResult) {
1595
+		if ($this->lastResult) {
1596 1596
 			$this->freeDbResult($this->lastResult);
1597 1597
 			$this->lastResult = null;
1598 1598
 		}
@@ -1621,17 +1621,17 @@  discard block
 block discarded – undo
1621 1621
 	public function getOne($sql, $dieOnError = false, $msg = '')
1622 1622
 	{
1623 1623
 		$this->log->info("Get One: |$sql|");
1624
-		if(!$this->hasLimit($sql)) {
1624
+		if (!$this->hasLimit($sql)) {
1625 1625
 		    $queryresult = $this->limitQuery($sql, 0, 1, $dieOnError, $msg);
1626 1626
 		} else {
1627 1627
 		    // support old code that passes LIMIT to sql
1628 1628
 		    // works only for mysql, so do not rely on this
1629 1629
 		    $queryresult = $this->query($sql, $dieOnError, $msg);
1630 1630
 		}
1631
-		$this->checkError($msg.' Get One Failed:' . $sql, $dieOnError);
1631
+		$this->checkError($msg.' Get One Failed:'.$sql, $dieOnError);
1632 1632
 		if (!$queryresult) return false;
1633 1633
 		$row = $this->fetchByAssoc($queryresult);
1634
-		if(!empty($row)) {
1634
+		if (!empty($row)) {
1635 1635
 			return array_shift($row);
1636 1636
 		}
1637 1637
 		return false;
@@ -1651,12 +1651,12 @@  discard block
 block discarded – undo
1651 1651
 		$this->log->info("Fetch One: |$sql|");
1652 1652
 		$this->checkConnection();
1653 1653
 		$queryresult = $this->query($sql, $dieOnError, $msg);
1654
-		$this->checkError($msg.' Fetch One Failed:' . $sql, $dieOnError);
1654
+		$this->checkError($msg.' Fetch One Failed:'.$sql, $dieOnError);
1655 1655
 
1656 1656
 		if (!$queryresult) return false;
1657 1657
 
1658 1658
 		$row = $this->fetchByAssoc($queryresult);
1659
-		if ( !$row ) return false;
1659
+		if (!$row) return false;
1660 1660
 
1661 1661
 		$this->freeResult($queryresult);
1662 1662
 		return $row;
@@ -1697,7 +1697,7 @@  discard block
 block discarded – undo
1697 1697
      */
1698 1698
 	public function getTableDescription($tablename, $reload = false)
1699 1699
 	{
1700
-		if($reload || empty(self::$table_descriptions[$tablename])) {
1700
+		if ($reload || empty(self::$table_descriptions[$tablename])) {
1701 1701
 			self::$table_descriptions[$tablename] = $this->get_columns($tablename);
1702 1702
 		}
1703 1703
 		return self::$table_descriptions[$tablename];
@@ -1713,12 +1713,12 @@  discard block
 block discarded – undo
1713 1713
 	protected function describeField($name, $tablename)
1714 1714
 	{
1715 1715
 		$table = $this->getTableDescription($tablename);
1716
-		if(!empty($table) && isset($table[$name]))
1716
+		if (!empty($table) && isset($table[$name]))
1717 1717
 			return 	$table[$name];
1718 1718
 
1719 1719
 		$table = $this->getTableDescription($tablename, true);
1720 1720
 
1721
-		if(isset($table[$name]))
1721
+		if (isset($table[$name]))
1722 1722
 		return $table[$name];
1723 1723
 
1724 1724
 		return array();
@@ -1733,13 +1733,13 @@  discard block
 block discarded – undo
1733 1733
 	 */
1734 1734
 	protected function describeIndex($name, $tablename)
1735 1735
 	{
1736
-		if(isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename][$name])){
1736
+		if (isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename][$name])) {
1737 1737
 			return 	self::$index_descriptions[$tablename][$name];
1738 1738
 		}
1739 1739
 
1740 1740
 		self::$index_descriptions[$tablename] = $this->get_indices($tablename);
1741 1741
 
1742
-		if(isset(self::$index_descriptions[$tablename][$name])){
1742
+		if (isset(self::$index_descriptions[$tablename][$name])) {
1743 1743
 			return 	self::$index_descriptions[$tablename][$name];
1744 1744
 		}
1745 1745
 
@@ -1756,9 +1756,9 @@  discard block
 block discarded – undo
1756 1756
      */
1757 1757
 	public function truncate($string, $len)
1758 1758
 	{
1759
-		if ( is_numeric($len) && $len > 0)
1759
+		if (is_numeric($len) && $len > 0)
1760 1760
 		{
1761
-			$string = mb_substr($string,0,(int) $len, "UTF-8");
1761
+			$string = mb_substr($string, 0, (int)$len, "UTF-8");
1762 1762
 		}
1763 1763
 		return $string;
1764 1764
 	}
@@ -1773,11 +1773,11 @@  discard block
 block discarded – undo
1773 1773
      */
1774 1774
 	public function concat($table, array $fields, $space = ' ')
1775 1775
 	{
1776
-		if(empty($fields)) return '';
1776
+		if (empty($fields)) return '';
1777 1777
 		$elems = array();
1778 1778
 		$space = $this->quoted($space);
1779
-		foreach ( $fields as $field ) {
1780
-			if(!empty($elems)) $elems[] = $space;
1779
+		foreach ($fields as $field) {
1780
+			if (!empty($elems)) $elems[] = $space;
1781 1781
 			$elems[] = $this->convert("$table.$field", 'IFNULL', array("''"));
1782 1782
 		}
1783 1783
 		$first = array_shift($elems);
@@ -1834,8 +1834,8 @@  discard block
 block discarded – undo
1834 1834
 	 */
1835 1835
 	public function executePreparedQuery($stmt, $data = array())
1836 1836
 	{
1837
-		if(!empty($this->preparedTokens[$stmt])){
1838
-			if(!is_array($data)){
1837
+		if (!empty($this->preparedTokens[$stmt])) {
1838
+			if (!is_array($data)) {
1839 1839
 				$data = array($data);
1840 1840
 			}
1841 1841
 
@@ -1843,7 +1843,7 @@  discard block
 block discarded – undo
1843 1843
 
1844 1844
 			//ensure that the number of data elements matches the number of replacement tokens
1845 1845
 			//we found in prepare().
1846
-			if(count($data) != $pTokens['tokenCount']){
1846
+			if (count($data) != $pTokens['tokenCount']) {
1847 1847
 				//error the data count did not match the token count
1848 1848
 				return false;
1849 1849
 			}
@@ -1869,7 +1869,7 @@  discard block
 block discarded – undo
1869 1869
 				}//switch
1870 1870
 			}//foreach
1871 1871
 			return $this->query($query);
1872
-		}else{
1872
+		} else {
1873 1873
 			return false;
1874 1874
 		}
1875 1875
 	}
@@ -1913,7 +1913,7 @@  discard block
 block discarded – undo
1913 1913
 	{
1914 1914
 		// get column names and values
1915 1915
 		$sql = $this->insertParams($bean->getTableName(), $bean->getFieldDefinitions(), get_object_vars($bean),
1916
-		        isset($bean->field_name_map)?$bean->field_name_map:null, false);
1916
+		        isset($bean->field_name_map) ? $bean->field_name_map : null, false);
1917 1917
 		return $sql;
1918 1918
 	}
1919 1919
 
@@ -1941,48 +1941,48 @@  discard block
 block discarded – undo
1941 1941
     		if (!empty($bean->field_name_map[$field]['auto_increment'])) continue;
1942 1942
 
1943 1943
     		//custom fields handle their save separately
1944
-    		if(isset($bean->field_name_map) && !empty($bean->field_name_map[$field]['custom_type']))  continue;
1944
+    		if (isset($bean->field_name_map) && !empty($bean->field_name_map[$field]['custom_type']))  continue;
1945 1945
 
1946 1946
     		// no need to clear deleted since we only update not deleted records anyway
1947
-    		if($fieldDef['name'] == 'deleted' && empty($bean->deleted)) continue;
1947
+    		if ($fieldDef['name'] == 'deleted' && empty($bean->deleted)) continue;
1948 1948
 
1949
-    		if(isset($bean->$field)) {
1949
+    		if (isset($bean->$field)) {
1950 1950
     			$val = from_html($bean->$field);
1951 1951
     		} else {
1952 1952
     			continue;
1953 1953
     		}
1954 1954
 
1955
-    		if(!empty($fieldDef['type']) && $fieldDef['type'] == 'bool'){
1955
+    		if (!empty($fieldDef['type']) && $fieldDef['type'] == 'bool') {
1956 1956
     			$val = $bean->getFieldValue($field);
1957 1957
     		}
1958 1958
 
1959
-    		if(strlen($val) == 0) {
1960
-    			if(isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) {
1959
+    		if (strlen($val) == 0) {
1960
+    			if (isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) {
1961 1961
     				$val = $fieldDef['default'];
1962 1962
     			} else {
1963 1963
     				$val = null;
1964 1964
     			}
1965 1965
     		}
1966 1966
 
1967
-    		if(!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) {
1967
+    		if (!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) {
1968 1968
 			    $val = $this->truncate($val, $fieldDef['len']);
1969 1969
 			}
1970 1970
 		$columnName = $this->quoteIdentifier($fieldDef['name']);
1971
-    		if(!is_null($val) || !empty($fieldDef['required'])) {
1971
+    		if (!is_null($val) || !empty($fieldDef['required'])) {
1972 1972
     			$columns[] = "{$columnName}=".$this->massageValue($val, $fieldDef);
1973
-    		} elseif($this->isNullable($fieldDef)) {
1973
+    		} elseif ($this->isNullable($fieldDef)) {
1974 1974
     			$columns[] = "{$columnName}=NULL";
1975 1975
     		} else {
1976 1976
     		    $columns[] = "{$columnName}=".$this->emptyValue($fieldDef['type']);
1977 1977
     		}
1978 1978
 		}
1979 1979
 
1980
-		if ( sizeof($columns) == 0 )
1980
+		if (sizeof($columns) == 0)
1981 1981
 			return ""; // no columns set
1982 1982
 
1983 1983
 		// build where clause
1984 1984
 		$where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
1985
-		if(isset($fields['deleted'])) {
1985
+		if (isset($fields['deleted'])) {
1986 1986
 		    $where .= " AND deleted=0";
1987 1987
 		}
1988 1988
 
@@ -2006,7 +2006,7 @@  discard block
 block discarded – undo
2006 2006
 			$primaryColumn = $fieldDef['name'];
2007 2007
 
2008 2008
 			$val = $bean->getFieldValue($fieldDef['name']);
2009
-			if ($val != FALSE){
2009
+			if ($val != FALSE) {
2010 2010
 				$where[$primaryColumn] = $val;
2011 2011
 			}
2012 2012
 		}
@@ -2032,7 +2032,7 @@  discard block
 block discarded – undo
2032 2032
 			if (is_array($val)) {
2033 2033
 				$op = "IN";
2034 2034
 				$temp = array();
2035
-				foreach ($val as $tval){
2035
+				foreach ($val as $tval) {
2036 2036
 					$temp[] = $this->quoted($tval);
2037 2037
 				}
2038 2038
 				$val = implode(",", $temp);
@@ -2058,9 +2058,9 @@  discard block
 block discarded – undo
2058 2058
 	 * @param  array  $whereArray Optional, where conditions in an array
2059 2059
 	 * @return string
2060 2060
 	 */
2061
-	protected function getWhereClause(SugarBean $bean, array $whereArray=array())
2061
+	protected function getWhereClause(SugarBean $bean, array $whereArray = array())
2062 2062
 	{
2063
-	    return " WHERE " . $this->getColumnWhereClause($bean->getTableName(), $whereArray);
2063
+	    return " WHERE ".$this->getColumnWhereClause($bean->getTableName(), $whereArray);
2064 2064
 	}
2065 2065
 
2066 2066
 	/**
@@ -2074,13 +2074,13 @@  discard block
 block discarded – undo
2074 2074
 	{
2075 2075
 		$type = $this->getFieldType($fieldDef);
2076 2076
 
2077
-		if(isset($this->type_class[$type])) {
2077
+		if (isset($this->type_class[$type])) {
2078 2078
 			// handle some known types
2079
-			switch($this->type_class[$type]) {
2079
+			switch ($this->type_class[$type]) {
2080 2080
 				case 'bool':
2081 2081
 				case 'int':
2082
-					if (!empty($fieldDef['required']) && $val == ''){
2083
-						if (isset($fieldDef['default'])){
2082
+					if (!empty($fieldDef['required']) && $val == '') {
2083
+						if (isset($fieldDef['default'])) {
2084 2084
 							return $fieldDef['default'];
2085 2085
 						}
2086 2086
 						return 0;
@@ -2088,16 +2088,16 @@  discard block
 block discarded – undo
2088 2088
 					return intval($val);
2089 2089
                 case 'bigint' :
2090 2090
                     $val = (float)$val;
2091
-					if (!empty($fieldDef['required']) && $val == false){
2092
-						if (isset($fieldDef['default'])){
2091
+					if (!empty($fieldDef['required']) && $val == false) {
2092
+						if (isset($fieldDef['default'])) {
2093 2093
 							return $fieldDef['default'];
2094 2094
 						}
2095 2095
 						return 0;
2096 2096
 					}
2097 2097
                     return $val;
2098 2098
 				case 'float':
2099
-					if (!empty($fieldDef['required'])  && $val == ''){
2100
-						if (isset($fieldDef['default'])){
2099
+					if (!empty($fieldDef['required']) && $val == '') {
2100
+						if (isset($fieldDef['default'])) {
2101 2101
 							return $fieldDef['default'];
2102 2102
 						}
2103 2103
 						return 0;
@@ -2106,7 +2106,7 @@  discard block
 block discarded – undo
2106 2106
 				case 'time':
2107 2107
 				case 'date':
2108 2108
 					// empty date can't be '', so convert it to either NULL or empty date value
2109
-					if($val == '') {
2109
+					if ($val == '') {
2110 2110
 						if (!empty($fieldDef['required'])) {
2111 2111
 							if (isset($fieldDef['default'])) {
2112 2112
 								return $fieldDef['default'];
@@ -2118,14 +2118,14 @@  discard block
 block discarded – undo
2118 2118
 					break;
2119 2119
 			}
2120 2120
 		} else {
2121
-		    if(!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) {
2121
+		    if (!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) {
2122 2122
 			    $val = $this->truncate($val, $fieldDef['len']);
2123 2123
 			}
2124 2124
 		}
2125 2125
 
2126
-		if ( is_null($val) ) {
2127
-			if(!empty($fieldDef['required'])) {
2128
-				if (isset($fieldDef['default'])  && $fieldDef['default'] != ''){
2126
+		if (is_null($val)) {
2127
+			if (!empty($fieldDef['required'])) {
2128
+				if (isset($fieldDef['default']) && $fieldDef['default'] != '') {
2129 2129
 					return $fieldDef['default'];
2130 2130
 				}
2131 2131
 				return $this->emptyValue($type);
@@ -2133,7 +2133,7 @@  discard block
 block discarded – undo
2133 2133
 				return "NULL";
2134 2134
 			}
2135 2135
 		}
2136
-        if($type == "datetimecombo") {
2136
+        if ($type == "datetimecombo") {
2137 2137
             $type = "datetime";
2138 2138
         }
2139 2139
 		return $this->convert($this->quoted($val), $type);
@@ -2148,23 +2148,23 @@  discard block
 block discarded – undo
2148 2148
 	 */
2149 2149
 	public function massageFieldDef(&$fieldDef, $tablename)
2150 2150
 	{
2151
-		if ( !isset($fieldDef['dbType']) ) {
2152
-			if ( isset($fieldDef['dbtype']) )
2151
+		if (!isset($fieldDef['dbType'])) {
2152
+			if (isset($fieldDef['dbtype']))
2153 2153
 				$fieldDef['dbType'] = $fieldDef['dbtype'];
2154 2154
 			else
2155 2155
 				$fieldDef['dbType'] = $fieldDef['type'];
2156 2156
 		}
2157
-		$type = $this->getColumnType($fieldDef['dbType'],$fieldDef['name'],$tablename);
2157
+		$type = $this->getColumnType($fieldDef['dbType'], $fieldDef['name'], $tablename);
2158 2158
 		$matches = array();
2159 2159
         // len can be a number or a string like 'max', for example, nvarchar(max)
2160 2160
         preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*|\w+)\)|)/i', $type, $matches);
2161
-		if ( isset($matches[1][0]) )
2161
+		if (isset($matches[1][0]))
2162 2162
 			$fieldDef['type'] = $matches[1][0];
2163
-		if ( isset($matches[2][0]) && empty($fieldDef['len']) )
2163
+		if (isset($matches[2][0]) && empty($fieldDef['len']))
2164 2164
 			$fieldDef['len'] = $matches[2][0];
2165
-		if ( !empty($fieldDef['precision']) && is_numeric($fieldDef['precision']) && !strstr($fieldDef['len'],',') )
2165
+		if (!empty($fieldDef['precision']) && is_numeric($fieldDef['precision']) && !strstr($fieldDef['len'], ','))
2166 2166
 			$fieldDef['len'] .= ",{$fieldDef['precision']}";
2167
-		if (!empty($fieldDef['required']) || ($fieldDef['name'] == 'id' && !isset($fieldDef['required'])) ) {
2167
+		if (!empty($fieldDef['required']) || ($fieldDef['name'] == 'id' && !isset($fieldDef['required']))) {
2168 2168
 			$fieldDef['required'] = 'true';
2169 2169
 		}
2170 2170
 	}
@@ -2185,7 +2185,7 @@  discard block
 block discarded – undo
2185 2185
 		$level = 0;
2186 2186
 		$selectField = "";
2187 2187
 		$strLen = strlen($selectStatement);
2188
-		for($i = 0; $i < $strLen; $i++)
2188
+		for ($i = 0; $i < $strLen; $i++)
2189 2189
 		{
2190 2190
 			$char = $selectStatement[$i];
2191 2191
 
@@ -2195,16 +2195,16 @@  discard block
 block discarded – undo
2195 2195
 				$fields[$field] = $selectField;
2196 2196
 				$selectField = "";
2197 2197
 			}
2198
-			else if ($char == "("){
2198
+			else if ($char == "(") {
2199 2199
 				$level++;
2200 2200
 				$selectField .= $char;
2201 2201
 			}
2202
-			else if($char == ")"){
2202
+			else if ($char == ")") {
2203 2203
 				$level--;
2204 2204
 				$selectField .= $char;
2205 2205
 
2206 2206
 
2207
-			}else{
2207
+			} else {
2208 2208
 				$selectField .= $char;
2209 2209
 			}
2210 2210
 
@@ -2220,7 +2220,7 @@  discard block
 block discarded – undo
2220 2220
      */
2221 2221
 	protected function getFieldNameFromSelect($string)
2222 2222
 	{
2223
-		if(strncasecmp($string, "DISTINCT ", 9) == 0) {
2223
+		if (strncasecmp($string, "DISTINCT ", 9) == 0) {
2224 2224
 			$string = substr($string, 9);
2225 2225
 		}
2226 2226
 		if (stripos($string, " as ") !== false)
@@ -2298,14 +2298,14 @@  discard block
 block discarded – undo
2298 2298
 				foreach ($cols[$beanID] as $def) $select[] = $table.".".$def['name'];
2299 2299
 
2300 2300
 			// build part of where clause
2301
-			if (is_array($whereClause[$beanID])){
2301
+			if (is_array($whereClause[$beanID])) {
2302 2302
 				$where[] = $this->getColumnWhereClause($table, $whereClause[$beanID]);
2303 2303
 			}
2304 2304
 			// initialize so that it can be used properly in form clause generation
2305 2305
 			$table_used_in_from[$table] = false;
2306 2306
 
2307 2307
 			$indices = $bean->getIndices();
2308
-			foreach ($indices as $index){
2308
+			foreach ($indices as $index) {
2309 2309
 				if ($index['type'] == 'foreign') {
2310 2310
 					$relationship[$table][] = array('foreignTable'=> $index['foreignTable']
2311 2311
 												,'foreignColumn'=>$index['foreignField']
@@ -2326,12 +2326,12 @@  discard block
 block discarded – undo
2326 2326
 		// table2 is assumed to joining through primary key called id
2327 2327
 		$separator = "";
2328 2328
 		$from = ''; $table_used_in_from = array();
2329
-		foreach ($relations as $table1 => $rightsidearray){
2329
+		foreach ($relations as $table1 => $rightsidearray) {
2330 2330
 			if ($table_used_in_from[$table1]) continue; // table has been joined
2331 2331
 
2332 2332
 			$from .= $separator." ".$table1;
2333 2333
 			$table_used_in_from[$table1] = true;
2334
-			foreach ($rightsidearray as $tablearray){
2334
+			foreach ($rightsidearray as $tablearray) {
2335 2335
 				$table2 = $tablearray['foreignTable']; // get foreign table
2336 2336
 				$tableAlias = $aliases[$table2]; // get a list of aliases for this table
2337 2337
 				foreach ($tableAlias as $table2) {
@@ -2391,9 +2391,9 @@  discard block
 block discarded – undo
2391 2391
 		// we do not have change a lot of existing code
2392 2392
 		// and add dbtype where type is being used for some special
2393 2393
 		// purposes like referring to foreign table etc.
2394
-		if(!empty($fieldDef['dbType']))
2394
+		if (!empty($fieldDef['dbType']))
2395 2395
 			return  $fieldDef['dbType'];
2396
-		if(!empty($fieldDef['dbtype']))
2396
+		if (!empty($fieldDef['dbtype']))
2397 2397
 			return  $fieldDef['dbtype'];
2398 2398
 		if (!empty($fieldDef['type']))
2399 2399
 			return  $fieldDef['type'];
@@ -2413,17 +2413,17 @@  discard block
 block discarded – undo
2413 2413
      */
2414 2414
     public function getTypeParts($type)
2415 2415
     {
2416
-        if(preg_match("#(?P<type>\w+)\s*(?P<arg>\((?P<len>\w+)\s*(,\s*(?P<scale>\d+))*\))*#", $type, $matches))
2416
+        if (preg_match("#(?P<type>\w+)\s*(?P<arg>\((?P<len>\w+)\s*(,\s*(?P<scale>\d+))*\))*#", $type, $matches))
2417 2417
         {
2418
-            $return = array();  // Not returning matches array as such as we don't want to expose the regex make up on the interface
2418
+            $return = array(); // Not returning matches array as such as we don't want to expose the regex make up on the interface
2419 2419
             $return['baseType'] = $matches['type'];
2420
-            if( isset($matches['arg'])) {
2420
+            if (isset($matches['arg'])) {
2421 2421
                 $return['arg'] = $matches['arg'];
2422 2422
             }
2423
-            if( isset($matches['len'])) {
2423
+            if (isset($matches['len'])) {
2424 2424
                 $return['len'] = $matches['len'];
2425 2425
             }
2426
-            if( isset($matches['scale'])) {
2426
+            if (isset($matches['scale'])) {
2427 2427
                 $return['scale'] = $matches['scale'];
2428 2428
             }
2429 2429
             return $return;
@@ -2447,28 +2447,28 @@  discard block
 block discarded – undo
2447 2447
 		$type = $this->getFieldType($fieldDef);
2448 2448
         $colType = $this->getColumnType($type);
2449 2449
 
2450
-        if($parts = $this->getTypeParts($colType))
2450
+        if ($parts = $this->getTypeParts($colType))
2451 2451
         {
2452 2452
             $colBaseType = $parts['baseType'];
2453
-            $defLen =  isset($parts['len']) ? $parts['len'] : '255'; // Use the mappings length (precision) as default if it exists
2453
+            $defLen = isset($parts['len']) ? $parts['len'] : '255'; // Use the mappings length (precision) as default if it exists
2454 2454
         }
2455 2455
 
2456
-        if(!empty($fieldDef['len'])) {
2457
-            if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char',
2456
+        if (!empty($fieldDef['len'])) {
2457
+            if (in_array($colBaseType, array('nvarchar', 'nchar', 'varchar', 'varchar2', 'char',
2458 2458
                                           'clob', 'blob', 'text'))) {
2459 2459
           	    $colType = "$colBaseType(${fieldDef['len']})";
2460
-            } elseif(($colBaseType == 'decimal' || $colBaseType == 'float')){
2461
-                  if(!empty($fieldDef['precision']) && is_numeric($fieldDef['precision']))
2462
-                      if(strpos($fieldDef['len'],',') === false){
2463
-                          $colType = $colBaseType . "(".$fieldDef['len'].",".$fieldDef['precision'].")";
2464
-                      }else{
2465
-                          $colType = $colBaseType . "(".$fieldDef['len'].")";
2460
+            } elseif (($colBaseType == 'decimal' || $colBaseType == 'float')) {
2461
+                  if (!empty($fieldDef['precision']) && is_numeric($fieldDef['precision']))
2462
+                      if (strpos($fieldDef['len'], ',') === false) {
2463
+                          $colType = $colBaseType."(".$fieldDef['len'].",".$fieldDef['precision'].")";
2464
+                      } else {
2465
+                          $colType = $colBaseType."(".$fieldDef['len'].")";
2466 2466
                       }
2467 2467
                   else
2468
-                          $colType = $colBaseType . "(".$fieldDef['len'].")";
2468
+                          $colType = $colBaseType."(".$fieldDef['len'].")";
2469 2469
               }
2470 2470
         } else {
2471
-            if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char'))) {
2471
+            if (in_array($colBaseType, array('nvarchar', 'nchar', 'varchar', 'varchar2', 'char'))) {
2472 2472
                 $colType = "$colBaseType($defLen)";
2473 2473
             }
2474 2474
         }
@@ -2490,29 +2490,29 @@  discard block
 block discarded – undo
2490 2490
         }
2491 2491
 
2492 2492
 		$auto_increment = '';
2493
-		if(!empty($fieldDef['auto_increment']) && $fieldDef['auto_increment'])
2494
-			$auto_increment = $this->setAutoIncrement($table , $fieldDef['name']);
2493
+		if (!empty($fieldDef['auto_increment']) && $fieldDef['auto_increment'])
2494
+			$auto_increment = $this->setAutoIncrement($table, $fieldDef['name']);
2495 2495
 
2496
-		$required = 'NULL';  // MySQL defaults to NULL, SQL Server defaults to NOT NULL -- must specify
2496
+		$required = 'NULL'; // MySQL defaults to NULL, SQL Server defaults to NOT NULL -- must specify
2497 2497
 		//Starting in 6.0, only ID and auto_increment fields will be NOT NULL in the DB.
2498 2498
 		if ((empty($fieldDef['isnull']) || strtolower($fieldDef['isnull']) == 'false') &&
2499 2499
 			(!empty($auto_increment) || $name == 'id' || ($fieldDef['type'] == 'id' && !empty($fieldDef['required'])))) {
2500
-			$required =  "NOT NULL";
2500
+			$required = "NOT NULL";
2501 2501
 		}
2502 2502
 		// If the field is marked both required & isnull=>false - alwqys make it not null
2503 2503
 		// Use this to ensure primary key fields never defined as null
2504
-		if(isset($fieldDef['isnull']) && (strtolower($fieldDef['isnull']) == 'false' || $fieldDef['isnull'] === false)
2504
+		if (isset($fieldDef['isnull']) && (strtolower($fieldDef['isnull']) == 'false' || $fieldDef['isnull'] === false)
2505 2505
 			&& !empty($fieldDef['required'])) {
2506
-			$required =  "NOT NULL";
2506
+			$required = "NOT NULL";
2507 2507
 		}
2508 2508
 		if ($ignoreRequired)
2509 2509
 			$required = "";
2510 2510
 
2511
-		if ( $return_as_array ) {
2511
+		if ($return_as_array) {
2512 2512
 			return array(
2513 2513
 				'name' => $name,
2514 2514
 				'colType' => $colType,
2515
-                'colBaseType' => $colBaseType,  // Adding base type for easier processing in derived classes
2515
+                'colBaseType' => $colBaseType, // Adding base type for easier processing in derived classes
2516 2516
 				'default' => $default,
2517 2517
 				'required' => $required,
2518 2518
 				'auto_increment' => $auto_increment,
@@ -2542,14 +2542,14 @@  discard block
 block discarded – undo
2542 2542
 
2543 2543
 		if ($this->isFieldArray($fieldDefs)) {
2544 2544
 			foreach ($fieldDefs as $fieldDef) {
2545
-				if(!isset($fieldDef['source']) || $fieldDef['source'] == 'db') {
2546
-					$columns[] = $this->oneColumnSQLRep($fieldDef,false, $tablename);
2545
+				if (!isset($fieldDef['source']) || $fieldDef['source'] == 'db') {
2546
+					$columns[] = $this->oneColumnSQLRep($fieldDef, false, $tablename);
2547 2547
 				}
2548 2548
 			}
2549 2549
 			$columns = implode(",", $columns);
2550 2550
 		}
2551 2551
 		else {
2552
-			$columns = $this->oneColumnSQLRep($fieldDefs,$ignoreRequired, $tablename);
2552
+			$columns = $this->oneColumnSQLRep($fieldDefs, $ignoreRequired, $tablename);
2553 2553
 		}
2554 2554
 
2555 2555
 		return $columns;
@@ -2711,40 +2711,40 @@  discard block
 block discarded – undo
2711 2711
      */
2712 2712
 	public function getValidDBName($name, $ensureUnique = false, $type = 'column', $force = false)
2713 2713
 	{
2714
-		if(is_array($name)) {
2714
+		if (is_array($name)) {
2715 2715
 			$result = array();
2716
-			foreach($name as $field) {
2716
+			foreach ($name as $field) {
2717 2717
 				$result[] = $this->getValidDBName($field, $ensureUnique, $type);
2718 2718
 			}
2719 2719
 			return $result;
2720 2720
 		} else {
2721
-		    if(strchr($name, ".")) {
2721
+		    if (strchr($name, ".")) {
2722 2722
 		        // this is a compound name with dots, handle separately
2723 2723
 		        $parts = explode(".", $name);
2724
-		        if(count($parts) > 2) {
2724
+		        if (count($parts) > 2) {
2725 2725
 		            // some weird name, cut to table.name
2726
-		            array_splice($parts, 0, count($parts)-2);
2726
+		            array_splice($parts, 0, count($parts) - 2);
2727 2727
 		        }
2728 2728
 		        $parts = $this->getValidDBName($parts, $ensureUnique, $type, $force);
2729 2729
                 return join(".", $parts);
2730 2730
 		    }
2731 2731
 			// first strip any invalid characters - all but word chars (which is alphanumeric and _)
2732
-			$name = preg_replace( '/[^\w]+/i', '', $name ) ;
2733
-			$len = strlen( $name ) ;
2732
+			$name = preg_replace('/[^\w]+/i', '', $name);
2733
+			$len = strlen($name);
2734 2734
 			$maxLen = empty($this->maxNameLengths[$type]) ? $this->maxNameLengths[$type]['column'] : $this->maxNameLengths[$type];
2735 2735
 			if ($len <= $maxLen && !$force) {
2736 2736
 				return strtolower($name);
2737 2737
 			}
2738 2738
 			if ($ensureUnique) {
2739 2739
 				$md5str = md5($name);
2740
-				$tail = substr ( $name, -11) ;
2741
-				$temp = substr($md5str , strlen($md5str)-4 );
2742
-				$result = substr( $name, 0, 10) . $temp . $tail ;
2740
+				$tail = substr($name, -11);
2741
+				$temp = substr($md5str, strlen($md5str) - 4);
2742
+				$result = substr($name, 0, 10).$temp.$tail;
2743 2743
 			} else {
2744
-				$result = substr( $name, 0, 11) . substr( $name, 11 - $maxLen);
2744
+				$result = substr($name, 0, 11).substr($name, 11 - $maxLen);
2745 2745
 			}
2746 2746
 
2747
-			return strtolower( $result ) ;
2747
+			return strtolower($result);
2748 2748
 		}
2749 2749
 	}
2750 2750
 
@@ -2756,7 +2756,7 @@  discard block
 block discarded – undo
2756 2756
 	 */
2757 2757
 	public function getColumnType($type)
2758 2758
 	{
2759
-		return isset($this->type_map[$type])?$this->type_map[$type]:$type;
2759
+		return isset($this->type_map[$type]) ? $this->type_map[$type] : $type;
2760 2760
 	}
2761 2761
 
2762 2762
 	/**
@@ -2770,10 +2770,10 @@  discard block
 block discarded – undo
2770 2770
 	 */
2771 2771
 	public function isFieldArray($defArray)
2772 2772
 	{
2773
-		if ( !is_array($defArray) )
2773
+		if (!is_array($defArray))
2774 2774
 			return false;
2775 2775
 
2776
-		if ( isset($defArray['type']) ){
2776
+		if (isset($defArray['type'])) {
2777 2777
 			// type key exists. May be an array of defs or a simple definition
2778 2778
 			return is_array($defArray['type']); // type is not an array => definition else array
2779 2779
 		}
@@ -2808,19 +2808,19 @@  discard block
 block discarded – undo
2808 2808
 		require('metadata/audit_templateMetaData.php');
2809 2809
 		$fieldDefs = $dictionary['audit']['fields'];
2810 2810
 
2811
-		$values=array();
2811
+		$values = array();
2812 2812
 		$values['id'] = $this->massageValue(create_guid(), $fieldDefs['id']);
2813
-		$values['parent_id']= $this->massageValue($bean->id, $fieldDefs['parent_id']);
2814
-		$values['field_name']= $this->massageValue($changes['field_name'], $fieldDefs['field_name']);
2813
+		$values['parent_id'] = $this->massageValue($bean->id, $fieldDefs['parent_id']);
2814
+		$values['field_name'] = $this->massageValue($changes['field_name'], $fieldDefs['field_name']);
2815 2815
 		$values['data_type'] = $this->massageValue($changes['data_type'], $fieldDefs['data_type']);
2816
-		if ($changes['data_type']=='text') {
2816
+		if ($changes['data_type'] == 'text') {
2817 2817
 			$values['before_value_text'] = $this->massageValue($changes['before'], $fieldDefs['before_value_text']);
2818 2818
 			$values['after_value_text'] = $this->massageValue($changes['after'], $fieldDefs['after_value_text']);
2819 2819
 		} else {
2820 2820
 			$values['before_value_string'] = $this->massageValue($changes['before'], $fieldDefs['before_value_string']);
2821 2821
 			$values['after_value_string'] = $this->massageValue($changes['after'], $fieldDefs['after_value_string']);
2822 2822
 		}
2823
-		$values['date_created'] = $this->massageValue(TimeDate::getInstance()->nowDb(), $fieldDefs['date_created'] );
2823
+		$values['date_created'] = $this->massageValue(TimeDate::getInstance()->nowDb(), $fieldDefs['date_created']);
2824 2824
 		$values['created_by'] = $this->massageValue($current_user->id, $fieldDefs['created_by']);
2825 2825
 
2826 2826
 		$sql .= "(".implode(",", array_keys($values)).") ";
@@ -2850,9 +2850,9 @@  discard block
 block discarded – undo
2850 2850
      * @param array|null $field_filter Array of filter names to be inspected (NULL means all fields)
2851 2851
      * @return array
2852 2852
      */
2853
-    public function getDataChanges(SugarBean &$bean, array $field_filter = null)
2853
+    public function getDataChanges(SugarBean & $bean, array $field_filter = null)
2854 2854
 	{
2855
-        $changed_values=array();
2855
+        $changed_values = array();
2856 2856
 
2857 2857
         $fetched_row = array();
2858 2858
         if (is_array($bean->fetched_row))
@@ -2872,40 +2872,40 @@  discard block
 block discarded – undo
2872 2872
             $field_defs = array_intersect_key($field_defs, $fetched_row);
2873 2873
 
2874 2874
             // remove fields which do not exist as bean property
2875
-            $field_defs = array_intersect_key($field_defs, (array) $bean);
2875
+            $field_defs = array_intersect_key($field_defs, (array)$bean);
2876 2876
 
2877 2877
             foreach ($field_defs as $field => $properties) {
2878 2878
                 $before_value = $fetched_row[$field];
2879
-                $after_value=$bean->$field;
2879
+                $after_value = $bean->$field;
2880 2880
                 if (isset($properties['type'])) {
2881
-                    $field_type=$properties['type'];
2881
+                    $field_type = $properties['type'];
2882 2882
                 } else {
2883 2883
                     if (isset($properties['dbType'])) {
2884
-                        $field_type=$properties['dbType'];
2884
+                        $field_type = $properties['dbType'];
2885 2885
                     }
2886
-                    else if(isset($properties['data_type'])) {
2887
-                        $field_type=$properties['data_type'];
2886
+                    else if (isset($properties['data_type'])) {
2887
+                        $field_type = $properties['data_type'];
2888 2888
                     }
2889 2889
                     else {
2890
-                        $field_type=$properties['dbtype'];
2890
+                        $field_type = $properties['dbtype'];
2891 2891
                     }
2892 2892
                 }
2893 2893
 
2894 2894
                 //Because of bug #25078(sqlserver haven't 'date' type, trim extra "00:00:00" when insert into *_cstm table).
2895 2895
                 // so when we read the audit datetime field from sqlserver, we have to replace the extra "00:00:00" again.
2896
-                if(!empty($field_type) && $field_type == 'date'){
2897
-                    $before_value = $this->fromConvert($before_value , $field_type);
2896
+                if (!empty($field_type) && $field_type == 'date') {
2897
+                    $before_value = $this->fromConvert($before_value, $field_type);
2898 2898
                 }
2899 2899
                 //if the type and values match, do nothing.
2900
-                if (!($this->_emptyValue($before_value,$field_type) && $this->_emptyValue($after_value,$field_type))) {
2900
+                if (!($this->_emptyValue($before_value, $field_type) && $this->_emptyValue($after_value, $field_type))) {
2901 2901
                     $change = false;
2902 2902
                     if (trim($before_value) !== trim($after_value)) {
2903 2903
                         // Bug #42475: Don't directly compare numeric values, instead do the subtract and see if the comparison comes out to be "close enough", it is necessary for floating point numbers.
2904 2904
                         // Manual merge of fix 95727f2eed44852f1b6bce9a9eccbe065fe6249f from DBHelper
2905 2905
                         // This fix also fixes Bug #44624 in a more generic way and therefore eliminates the need for fix 0a55125b281c4bee87eb347709af462715f33d2d in DBHelper
2906 2906
                         if ($this->isNumericType($field_type)) {
2907
-                            $numerator = abs(2*((trim($before_value)+0)-(trim($after_value)+0)));
2908
-                            $denominator = abs(((trim($before_value)+0)+(trim($after_value)+0)));
2907
+                            $numerator = abs(2 * ((trim($before_value) + 0) - (trim($after_value) + 0)));
2908
+                            $denominator = abs(((trim($before_value) + 0) + (trim($after_value) + 0)));
2909 2909
                             // detect whether to use absolute or relative error. use absolute if denominator is zero to avoid division by zero
2910 2910
                             $error = ($denominator == 0) ? $numerator : $numerator / $denominator;
2911 2911
                             if ($error >= 0.0000000001) {    // Smaller than 10E-10
@@ -2921,7 +2921,7 @@  discard block
 block discarded – undo
2921 2921
                             $change = true;
2922 2922
                         }
2923 2923
                         if ($change) {
2924
-                            $changed_values[$field]=array('field_name'=>$field,
2924
+                            $changed_values[$field] = array('field_name'=>$field,
2925 2925
                                 'data_type'=>$field_type,
2926 2926
                                 'before'=>$before_value,
2927 2927
                                 'after'=>$after_value);
@@ -2992,8 +2992,8 @@  discard block
 block discarded – undo
2992 2992
      */
2993 2993
 	public function renameIndexDefs($old_definition, $new_definition, $table_name)
2994 2994
 	{
2995
-		return array($this->add_drop_constraint($table_name,$old_definition,true),
2996
-				$this->add_drop_constraint($table_name,$new_definition), false);
2995
+		return array($this->add_drop_constraint($table_name, $old_definition, true),
2996
+				$this->add_drop_constraint($table_name, $new_definition), false);
2997 2997
 	}
2998 2998
 
2999 2999
 	/**
@@ -3015,7 +3015,7 @@  discard block
 block discarded – undo
3015 3015
 	protected function _getBooleanValue($val)
3016 3016
 	{
3017 3017
 		//need to put the === sign here otherwise true == 'non empty string'
3018
-		if (empty($val) or $val==='off')
3018
+		if (empty($val) or $val === 'off')
3019 3019
 			return false;
3020 3020
 
3021 3021
 		return true;
@@ -3028,7 +3028,7 @@  discard block
 block discarded – undo
3028 3028
 	 */
3029 3029
 	public function isNumericType($type)
3030 3030
 	{
3031
-	    if(isset($this->type_class[$type]) && ($this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) {
3031
+	    if (isset($this->type_class[$type]) && ($this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) {
3032 3032
 	        return true;
3033 3033
 	    }
3034 3034
 		return false;
@@ -3045,7 +3045,7 @@  discard block
 block discarded – undo
3045 3045
 		if (empty($val))
3046 3046
 			return true;
3047 3047
 
3048
-		if($this->emptyValue($type) == $val) {
3048
+		if ($this->emptyValue($type) == $val) {
3049 3049
 			return true;
3050 3050
 		}
3051 3051
 		switch ($type) {
@@ -3104,7 +3104,7 @@  discard block
 block discarded – undo
3104 3104
 		$i = 0;
3105 3105
 		$order_by_arr = array();
3106 3106
 		foreach ($values as $key => $value) {
3107
-			if($key == '') {
3107
+			if ($key == '') {
3108 3108
 				$order_by_arr[] = "WHEN ($order_by='' OR $order_by IS NULL) THEN $i";
3109 3109
 			} else {
3110 3110
 				$order_by_arr[] = "WHEN $order_by=".$this->quoted($key)." THEN $i";
@@ -3122,7 +3122,7 @@  discard block
 block discarded – undo
3122 3122
      */
3123 3123
 	public function emptyValue($type)
3124 3124
 	{
3125
-		if(isset($this->type_class[$type]) && ($this->type_class[$type] == 'bool' || $this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) {
3125
+		if (isset($this->type_class[$type]) && ($this->type_class[$type] == 'bool' || $this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) {
3126 3126
 			return 0;
3127 3127
 		}
3128 3128
 
@@ -3171,9 +3171,9 @@  discard block
 block discarded – undo
3171 3171
      * @return resource|bool query result
3172 3172
      * @see DBManager::limitQuery()
3173 3173
 	 */
3174
-	public function limitQuerySql($sql, $start, $count, $dieOnError=false, $msg='')
3174
+	public function limitQuerySql($sql, $start, $count, $dieOnError = false, $msg = '')
3175 3175
 	{
3176
-		return $this->limitQuery($sql,$start,$count,$dieOnError,$msg,false);
3176
+		return $this->limitQuery($sql, $start, $count, $dieOnError, $msg, false);
3177 3177
 	}
3178 3178
 
3179 3179
 	/**
@@ -3192,7 +3192,7 @@  discard block
 block discarded – undo
3192 3192
      */
3193 3193
 	public function checkPrivilege($privilege)
3194 3194
 	{
3195
-		switch($privilege) {
3195
+		switch ($privilege) {
3196 3196
 			case "CREATE TABLE":
3197 3197
 				$this->query("CREATE TABLE temp (id varchar(36))");
3198 3198
 				break;
@@ -3213,23 +3213,23 @@  discard block
 block discarded – undo
3213 3213
 				break;
3214 3214
 			case "ADD COLUMN":
3215 3215
 				$test = array("test" => array("name" => "test", "type" => "varchar", "len" => 50));
3216
-				$sql = 	$this->changeColumnSQL("temp", $test, "add");
3216
+				$sql = $this->changeColumnSQL("temp", $test, "add");
3217 3217
 				$this->query($sql);
3218 3218
 				break;
3219 3219
 			case "CHANGE COLUMN":
3220 3220
 				$test = array("test" => array("name" => "test", "type" => "varchar", "len" => 100));
3221
-				$sql = 	$this->changeColumnSQL("temp", $test, "modify");
3221
+				$sql = $this->changeColumnSQL("temp", $test, "modify");
3222 3222
 				$this->query($sql);
3223 3223
 				break;
3224 3224
 			case "DROP COLUMN":
3225 3225
 				$test = array("test" => array("name" => "test", "type" => "varchar", "len" => 100));
3226
-				$sql = 	$this->changeColumnSQL("temp", $test, "drop");
3226
+				$sql = $this->changeColumnSQL("temp", $test, "drop");
3227 3227
 				$this->query($sql);
3228 3228
 				break;
3229 3229
 			default:
3230 3230
 				return false;
3231 3231
 		}
3232
-		if($this->checkError("Checking privileges")) {
3232
+		if ($this->checkError("Checking privileges")) {
3233 3233
 			return false;
3234 3234
 		}
3235 3235
 		return true;
@@ -3246,7 +3246,7 @@  discard block
 block discarded – undo
3246 3246
 		$select_check = strpos(strtolower($query), strtolower("SELECT"));
3247 3247
 		//Checks to see if there is union select which is valid
3248 3248
 		$select_check2 = strpos(strtolower($query), strtolower("(SELECT"));
3249
-		if($select_check==0 || $select_check2==0){
3249
+		if ($select_check == 0 || $select_check2 == 0) {
3250 3250
 			//Returning false means query is ok!
3251 3251
 			return true;
3252 3252
 		}
@@ -3265,10 +3265,10 @@  discard block
 block discarded – undo
3265 3265
 	public function parseFulltextQuery($query)
3266 3266
 	{
3267 3267
 		/* split on space or comma, double quotes with \ for escape */
3268
-		if(strpbrk($query, " ,")) {
3268
+		if (strpbrk($query, " ,")) {
3269 3269
 			// ("([^"]*?)"|[^" ,]+)((, )+)?
3270 3270
 			// '/([^" ,]+|".*?[^\\\\]")(,|\s)\s*/'
3271
-			if(!preg_match_all('/("([^"]*?)"|[^"\s,]+)((,\s)+)?/', $query, $m)) {
3271
+			if (!preg_match_all('/("([^"]*?)"|[^"\s,]+)((,\s)+)?/', $query, $m)) {
3272 3272
 				return false;
3273 3273
 			}
3274 3274
 			$qterms = $m[1];
@@ -3276,17 +3276,17 @@  discard block
 block discarded – undo
3276 3276
 			$qterms = array($query);
3277 3277
 		}
3278 3278
 		$terms = $must_terms = $not_terms = array();
3279
-		foreach($qterms as $item) {
3280
-			if($item[0] == '"') {
3279
+		foreach ($qterms as $item) {
3280
+			if ($item[0] == '"') {
3281 3281
 				$item = trim($item, '"');
3282 3282
 			}
3283
-			if($item[0] == '+') {
3283
+			if ($item[0] == '+') {
3284 3284
                 if (strlen($item) > 1) {
3285 3285
                     $must_terms[] = substr($item, 1);
3286 3286
                 }
3287 3287
                 continue;
3288 3288
 			}
3289
-			if($item[0] == '-') {
3289
+			if ($item[0] == '-') {
3290 3290
                 if (strlen($item) > 1) {
3291 3291
 				    $not_terms[] = substr($item, 1);
3292 3292
                 }
@@ -3335,11 +3335,11 @@  discard block
 block discarded – undo
3335 3335
 	public function verifySQLStatement($query, $skipTables)
3336 3336
 	{
3337 3337
 		$query = trim($query);
3338
-		foreach($this->standardQueries as $qstart => $check) {
3339
-			if(strncasecmp($qstart, $query, strlen($qstart)) == 0) {
3340
-				if(is_callable(array($this, $check))) {
3338
+		foreach ($this->standardQueries as $qstart => $check) {
3339
+			if (strncasecmp($qstart, $query, strlen($qstart)) == 0) {
3340
+				if (is_callable(array($this, $check))) {
3341 3341
 					$table = $this->extractTableName($query);
3342
-					if(!in_array($table, $skipTables)) {
3342
+					if (!in_array($table, $skipTables)) {
3343 3343
 						return call_user_func(array($this, $check), $table, $query);
3344 3344
 					} else {
3345 3345
 						$this->log->debug("Skipping table $table as blacklisted");
@@ -3368,20 +3368,20 @@  discard block
 block discarded – undo
3368 3368
 		$tempname = $table."__uw_temp";
3369 3369
 		$tempTableQuery = str_replace("CREATE TABLE {$table}", "CREATE TABLE $tempname", $query);
3370 3370
 
3371
-		if(strpos($tempTableQuery, '__uw_temp') === false) {
3371
+		if (strpos($tempTableQuery, '__uw_temp') === false) {
3372 3372
 			return 'Could not use a temp table to test query!';
3373 3373
 		}
3374 3374
 
3375 3375
 		$this->query($tempTableQuery, false, "Preflight Failed for: {$query}");
3376 3376
 
3377 3377
 		$error = $this->lastError(); // empty on no-errors
3378
-		if(!empty($error)) {
3378
+		if (!empty($error)) {
3379 3379
 			return $error;
3380 3380
 		}
3381 3381
 
3382 3382
 		// check if table exists
3383 3383
 		$this->log->debug('testing for table: '.$table);
3384
-		if(!$this->tableExists($tempname)) {
3384
+		if (!$this->tableExists($tempname)) {
3385 3385
 			return "Failed to create temp table!";
3386 3386
 		}
3387 3387
 
@@ -3400,8 +3400,8 @@  discard block
 block discarded – undo
3400 3400
 	public function queryArray(array $sqls, $dieOnError = false, $msg = '', $suppress = false)
3401 3401
 	{
3402 3402
 		$last = true;
3403
-		foreach($sqls as $sql) {
3404
-			if(!($last = $this->query($sql, $dieOnError, $msg, $suppress))) {
3403
+		foreach ($sqls as $sql) {
3404
+			if (!($last = $this->query($sql, $dieOnError, $msg, $suppress))) {
3405 3405
 				break;
3406 3406
 			}
3407 3407
 		}
@@ -3419,7 +3419,7 @@  discard block
 block discarded – undo
3419 3419
 	{
3420 3420
 	    if (empty($result))	return false;
3421 3421
 
3422
-	    if(is_int($encode) && func_num_args() == 3) {
3422
+	    if (is_int($encode) && func_num_args() == 3) {
3423 3423
 	        // old API: $result, $rowNum, $encode
3424 3424
 	        $GLOBALS['log']->deprecated("Using row number in fetchByAssoc is not portable and no longer supported. Please fix your code.");
3425 3425
 	        $encode = func_get_arg(2);
@@ -3470,7 +3470,7 @@  discard block
 block discarded – undo
3470 3470
 	 */
3471 3471
 	public function getOption($option)
3472 3472
 	{
3473
-	    if(isset($this->options[$option])) {
3473
+	    if (isset($this->options[$option])) {
3474 3474
 	        return $this->options[$option];
3475 3475
 	    }
3476 3476
 	    return null;
@@ -3510,7 +3510,7 @@  discard block
 block discarded – undo
3510 3510
 	public function isDatabaseNameValid($name)
3511 3511
 	{
3512 3512
 		// Generic case - no slashes, no dots
3513
-		return preg_match('#[/.\\\\]#', $name)==0;
3513
+		return preg_match('#[/.\\\\]#', $name) == 0;
3514 3514
 	}
3515 3515
 
3516 3516
 	/**
Please login to merge, or discard this patch.
include/database/MysqliManager.php 3 patches
Spacing   +36 added lines, -36 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.
@@ -121,18 +121,18 @@  discard block
 block discarded – undo
121 121
 	 */
122 122
 	public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
123 123
 	{
124
-		if(is_array($sql)) {
124
+		if (is_array($sql)) {
125 125
 			return $this->queryArray($sql, $dieOnError, $msg, $suppress);
126 126
         }
127 127
 
128 128
 		static $queryMD5 = array();
129 129
 
130 130
 		parent::countQuery($sql);
131
-		$GLOBALS['log']->info('Query:' . $sql);
131
+		$GLOBALS['log']->info('Query:'.$sql);
132 132
 		$this->checkConnection();
133 133
 		$this->query_time = microtime(true);
134 134
 		$this->lastsql = $sql;
135
-		$result = $suppress?@mysqli_query($this->database,$sql):mysqli_query($this->database,$sql);
135
+		$result = $suppress ? @mysqli_query($this->database, $sql) : mysqli_query($this->database, $sql);
136 136
 		$md5 = md5($sql);
137 137
 
138 138
 		if (empty($queryMD5[$md5]))
@@ -154,9 +154,9 @@  discard block
 block discarded – undo
154 154
 		*/
155 155
 
156 156
 
157
-		if($keepResult)
157
+		if ($keepResult)
158 158
 			$this->lastResult = $result;
159
-		$this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
159
+		$this->checkError($msg.' Query Failed: '.$sql, $dieOnError);
160 160
 
161 161
 		return $result;
162 162
 	}
@@ -193,10 +193,10 @@  discard block
 block discarded – undo
193 193
 	 */
194 194
 	public function disconnect()
195 195
 	{
196
-		if(isset($GLOBALS['log']) && !is_null($GLOBALS['log'])) {
196
+		if (isset($GLOBALS['log']) && !is_null($GLOBALS['log'])) {
197 197
 			$GLOBALS['log']->debug('Calling MySQLi::disconnect()');
198 198
 		}
199
-		if(!empty($this->database)){
199
+		if (!empty($this->database)) {
200 200
 			$this->freeResult();
201 201
 			mysqli_close($this->database);
202 202
 			$this->database = null;
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 	 */
209 209
 	protected function freeDbResult($dbResult)
210 210
 	{
211
-		if(!empty($dbResult))
211
+		if (!empty($dbResult))
212 212
 			mysqli_free_result($dbResult);
213 213
 	}
214 214
 
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 			if (!$meta)
229 229
 				return 0;
230 230
 
231
-			if($make_lower_case == true)
231
+			if ($make_lower_case == true)
232 232
 				$meta->name = strtolower($meta->name);
233 233
 
234 234
 			$field_array[] = $meta->name;
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 		if (empty($result))	return false;
248 248
 
249 249
 		$row = mysqli_fetch_assoc($result);
250
-		if($row == null) $row = false; //Make sure MySQLi driver results are consistent with other database drivers
250
+		if ($row == null) $row = false; //Make sure MySQLi driver results are consistent with other database drivers
251 251
 		return $row;
252 252
 	}
253 253
 
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 	 */
257 257
 	public function quote($string)
258 258
 	{
259
-		return mysqli_real_escape_string($this->getDatabase(),$this->quoteInternal($string));
259
+		return mysqli_real_escape_string($this->getDatabase(), $this->quoteInternal($string));
260 260
 	}
261 261
 
262 262
 	/**
@@ -269,23 +269,23 @@  discard block
 block discarded – undo
269 269
 		if (is_null($configOptions))
270 270
 			$configOptions = $sugar_config['dbconfig'];
271 271
 
272
-		if(!isset($this->database)) {
272
+		if (!isset($this->database)) {
273 273
 
274 274
 			//mysqli connector has a separate parameter for port.. We need to separate it out from the host name
275
-			$dbhost=$configOptions['db_host_name'];
276
-            $dbport=isset($configOptions['db_port']) ? ($configOptions['db_port'] == '' ? null : $configOptions['db_port']) : null;
275
+			$dbhost = $configOptions['db_host_name'];
276
+            $dbport = isset($configOptions['db_port']) ? ($configOptions['db_port'] == '' ? null : $configOptions['db_port']) : null;
277 277
 			
278
-			$pos=strpos($configOptions['db_host_name'],':');
278
+			$pos = strpos($configOptions['db_host_name'], ':');
279 279
 			if ($pos !== false) {
280
-				$dbhost=substr($configOptions['db_host_name'],0,$pos);
281
-				$dbport=substr($configOptions['db_host_name'],$pos+1);
280
+				$dbhost = substr($configOptions['db_host_name'], 0, $pos);
281
+				$dbport = substr($configOptions['db_host_name'], $pos + 1);
282 282
 			}
283 283
 
284
-			$this->database = @mysqli_connect($dbhost,$configOptions['db_user_name'],$configOptions['db_password'],isset($configOptions['db_name'])?$configOptions['db_name']:'',$dbport);
285
-			if(empty($this->database)) {
286
-				$GLOBALS['log']->fatal("Could not connect to DB server ".$dbhost." as ".$configOptions['db_user_name'].". port " .$dbport . ": " . mysqli_connect_error());
287
-				if($dieOnError) {
288
-					if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
284
+			$this->database = @mysqli_connect($dbhost, $configOptions['db_user_name'], $configOptions['db_password'], isset($configOptions['db_name']) ? $configOptions['db_name'] : '', $dbport);
285
+			if (empty($this->database)) {
286
+				$GLOBALS['log']->fatal("Could not connect to DB server ".$dbhost." as ".$configOptions['db_user_name'].". port ".$dbport.": ".mysqli_connect_error());
287
+				if ($dieOnError) {
288
+					if (isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
289 289
 						sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
290 290
 					} else {
291 291
 						sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
@@ -296,10 +296,10 @@  discard block
 block discarded – undo
296 296
 			}
297 297
 		}
298 298
 
299
-		if(!empty($configOptions['db_name']) && !@mysqli_select_db($this->database,$configOptions['db_name'])) {
300
-			$GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}: " . mysqli_connect_error());
301
-			if($dieOnError) {
302
-					if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
299
+		if (!empty($configOptions['db_name']) && !@mysqli_select_db($this->database, $configOptions['db_name'])) {
300
+			$GLOBALS['log']->fatal("Unable to select database {$configOptions['db_name']}: ".mysqli_connect_error());
301
+			if ($dieOnError) {
302
+					if (isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
303 303
 						sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
304 304
 					} else {
305 305
 						sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
@@ -312,13 +312,13 @@  discard block
 block discarded – undo
312 312
 		// cn: using direct calls to prevent this from spamming the Logs
313 313
 	    
314 314
 	    $collation = $this->getOption('collation');
315
-	    if(!empty($collation)) {
315
+	    if (!empty($collation)) {
316 316
 	    	$names = "SET NAMES 'utf8' COLLATE '$collation'";
317
-	    	mysqli_query($this->database,$names);
317
+	    	mysqli_query($this->database, $names);
318 318
 		}
319
-	    mysqli_set_charset ($this->database , "utf8" );
319
+	    mysqli_set_charset($this->database, "utf8");
320 320
 
321
-		if($this->checkError('Could Not Connect', $dieOnError))
321
+		if ($this->checkError('Could Not Connect', $dieOnError))
322 322
 			$GLOBALS['log']->info("connected to db");
323 323
 
324 324
 		$this->connectOptions = $configOptions;
@@ -331,13 +331,13 @@  discard block
 block discarded – undo
331 331
 	 */
332 332
 	public function lastDbError()
333 333
 	{
334
-		if($this->database) {
335
-		    if(mysqli_errno($this->database)) {
334
+		if ($this->database) {
335
+		    if (mysqli_errno($this->database)) {
336 336
 			    return "MySQL error ".mysqli_errno($this->database).": ".mysqli_error($this->database);
337 337
 		    }
338 338
 		} else {
339
-			$err =  mysqli_connect_error();
340
-			if($err) {
339
+			$err = mysqli_connect_error();
340
+			if ($err) {
341 341
 			    return $err;
342 342
 			}
343 343
 		}
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
 	{
350 350
 		$charsets = $this->getCharsetInfo();
351 351
 		$charset_str = array();
352
-		foreach($charsets as $name => $value) {
352
+		foreach ($charsets as $name => $value) {
353 353
 			$charset_str[] = "$name = $value";
354 354
 		}
355 355
 		return array(
Please login to merge, or discard this patch.
Indentation   +253 added lines, -253 removed lines patch added patch discarded remove patch
@@ -98,52 +98,52 @@  discard block
 block discarded – undo
98 98
  */
99 99
 class MysqliManager extends MysqlManager
100 100
 {
101
-	/**
102
-	 * @see DBManager::$dbType
103
-	 */
104
-	public $dbType = 'mysql';
105
-	public $variant = 'mysqli';
106
-	public $priority = 10;
107
-	public $label = 'LBL_MYSQLI';
108
-
109
-	/**
110
-	 * @see DBManager::$backendFunctions
111
-	 */
112
-	protected $backendFunctions = array(
113
-		'free_result'        => 'mysqli_free_result',
114
-		'close'              => 'mysqli_close',
115
-		'row_count'          => 'mysqli_num_rows',
116
-		'affected_row_count' => 'mysqli_affected_rows',
117
-		);
118
-
119
-	/**
120
-	 * @see MysqlManager::query()
121
-	 */
122
-	public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
123
-	{
124
-		if(is_array($sql)) {
125
-			return $this->queryArray($sql, $dieOnError, $msg, $suppress);
101
+    /**
102
+     * @see DBManager::$dbType
103
+     */
104
+    public $dbType = 'mysql';
105
+    public $variant = 'mysqli';
106
+    public $priority = 10;
107
+    public $label = 'LBL_MYSQLI';
108
+
109
+    /**
110
+     * @see DBManager::$backendFunctions
111
+     */
112
+    protected $backendFunctions = array(
113
+        'free_result'        => 'mysqli_free_result',
114
+        'close'              => 'mysqli_close',
115
+        'row_count'          => 'mysqli_num_rows',
116
+        'affected_row_count' => 'mysqli_affected_rows',
117
+        );
118
+
119
+    /**
120
+     * @see MysqlManager::query()
121
+     */
122
+    public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
123
+    {
124
+        if(is_array($sql)) {
125
+            return $this->queryArray($sql, $dieOnError, $msg, $suppress);
126 126
         }
127 127
 
128
-		static $queryMD5 = array();
128
+        static $queryMD5 = array();
129 129
 
130
-		parent::countQuery($sql);
131
-		$GLOBALS['log']->info('Query:' . $sql);
132
-		$this->checkConnection();
133
-		$this->query_time = microtime(true);
134
-		$this->lastsql = $sql;
135
-		$result = $suppress?@mysqli_query($this->database,$sql):mysqli_query($this->database,$sql);
136
-		$md5 = md5($sql);
130
+        parent::countQuery($sql);
131
+        $GLOBALS['log']->info('Query:' . $sql);
132
+        $this->checkConnection();
133
+        $this->query_time = microtime(true);
134
+        $this->lastsql = $sql;
135
+        $result = $suppress?@mysqli_query($this->database,$sql):mysqli_query($this->database,$sql);
136
+        $md5 = md5($sql);
137 137
 
138
-		if (empty($queryMD5[$md5]))
139
-			$queryMD5[$md5] = true;
138
+        if (empty($queryMD5[$md5]))
139
+            $queryMD5[$md5] = true;
140 140
 
141
-		$this->query_time = microtime(true) - $this->query_time;
142
-		$GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
143
-		$this->dump_slow_queries($sql);
141
+        $this->query_time = microtime(true) - $this->query_time;
142
+        $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
143
+        $this->dump_slow_queries($sql);
144 144
 
145
-		// This is some heavy duty debugging, leave commented out unless you need this:
146
-		/*
145
+        // This is some heavy duty debugging, leave commented out unless you need this:
146
+        /*
147 147
 		$bt = debug_backtrace();
148 148
 		for ( $i = count($bt) ; $i-- ; $i > 0 ) {
149 149
 			if ( strpos('MysqliManager.php',$bt[$i]['file']) === false ) {
@@ -155,228 +155,228 @@  discard block
 block discarded – undo
155 155
 		*/
156 156
 
157 157
 
158
-		if($keepResult)
159
-			$this->lastResult = $result;
160
-		$this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
161
-
162
-		return $result;
163
-	}
164
-
165
-	/**
166
-	 * Returns the number of rows affected by the last query
167
-	 *
168
-	 * @return int
169
-	 */
170
-	public function getAffectedRowCount($result)
171
-	{
172
-		return mysqli_affected_rows($this->getDatabase());
173
-	}
174
-
175
-	/**
176
-	 * Returns the number of rows returned by the result
177
-	 *
178
-	 * This function can't be reliably implemented on most DB, do not use it.
179
-	 * @abstract
180
-	 * @deprecated
181
-	 * @param  resource $result
182
-	 * @return int
183
-	 */
184
-	public function getRowCount($result)
185
-	{
186
-	    return mysqli_num_rows($result);
187
-	}
158
+        if($keepResult)
159
+            $this->lastResult = $result;
160
+        $this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
188 161
 
162
+        return $result;
163
+    }
189 164
 
190 165
     /**
191
-	 * Disconnects from the database
192
-	 *
193
-	 * Also handles any cleanup needed
194
-	 */
195
-	public function disconnect()
196
-	{
197
-		if(isset($GLOBALS['log']) && !is_null($GLOBALS['log'])) {
198
-			$GLOBALS['log']->debug('Calling MySQLi::disconnect()');
199
-		}
200
-		if(!empty($this->database)){
201
-			$this->freeResult();
202
-			mysqli_close($this->database);
203
-			$this->database = null;
204
-		}
205
-	}
206
-
207
-	/**
208
-	 * @see DBManager::freeDbResult()
209
-	 */
210
-	protected function freeDbResult($dbResult)
211
-	{
212
-		if(!empty($dbResult))
213
-			mysqli_free_result($dbResult);
214
-	}
215
-
216
-	/**
217
-	 * @see DBManager::getFieldsArray()
218
-	 */
219
-	public function getFieldsArray($result, $make_lower_case = false)
220
-	{
221
-		$field_array = array();
222
-
223
-		if (!isset($result) || empty($result))
224
-			return 0;
225
-
226
-		$i = 0;
227
-		while ($i < mysqli_num_fields($result)) {
228
-			$meta = mysqli_fetch_field_direct($result, $i);
229
-			if (!$meta)
230
-				return 0;
231
-
232
-			if($make_lower_case == true)
233
-				$meta->name = strtolower($meta->name);
234
-
235
-			$field_array[] = $meta->name;
236
-
237
-			$i++;
238
-		}
166
+     * Returns the number of rows affected by the last query
167
+     *
168
+     * @return int
169
+     */
170
+    public function getAffectedRowCount($result)
171
+    {
172
+        return mysqli_affected_rows($this->getDatabase());
173
+    }
174
+
175
+    /**
176
+     * Returns the number of rows returned by the result
177
+     *
178
+     * This function can't be reliably implemented on most DB, do not use it.
179
+     * @abstract
180
+     * @deprecated
181
+     * @param  resource $result
182
+     * @return int
183
+     */
184
+    public function getRowCount($result)
185
+    {
186
+        return mysqli_num_rows($result);
187
+    }
188
+
189
+
190
+    /**
191
+     * Disconnects from the database
192
+     *
193
+     * Also handles any cleanup needed
194
+     */
195
+    public function disconnect()
196
+    {
197
+        if(isset($GLOBALS['log']) && !is_null($GLOBALS['log'])) {
198
+            $GLOBALS['log']->debug('Calling MySQLi::disconnect()');
199
+        }
200
+        if(!empty($this->database)){
201
+            $this->freeResult();
202
+            mysqli_close($this->database);
203
+            $this->database = null;
204
+        }
205
+    }
206
+
207
+    /**
208
+     * @see DBManager::freeDbResult()
209
+     */
210
+    protected function freeDbResult($dbResult)
211
+    {
212
+        if(!empty($dbResult))
213
+            mysqli_free_result($dbResult);
214
+    }
215
+
216
+    /**
217
+     * @see DBManager::getFieldsArray()
218
+     */
219
+    public function getFieldsArray($result, $make_lower_case = false)
220
+    {
221
+        $field_array = array();
222
+
223
+        if (!isset($result) || empty($result))
224
+            return 0;
225
+
226
+        $i = 0;
227
+        while ($i < mysqli_num_fields($result)) {
228
+            $meta = mysqli_fetch_field_direct($result, $i);
229
+            if (!$meta)
230
+                return 0;
231
+
232
+            if($make_lower_case == true)
233
+                $meta->name = strtolower($meta->name);
234
+
235
+            $field_array[] = $meta->name;
236
+
237
+            $i++;
238
+        }
239
+
240
+        return $field_array;
241
+    }
242
+
243
+    /**
244
+     * @see DBManager::fetchRow()
245
+     */
246
+    public function fetchRow($result)
247
+    {
248
+        if (empty($result))	return false;
249
+
250
+        $row = mysqli_fetch_assoc($result);
251
+        if($row == null) $row = false; //Make sure MySQLi driver results are consistent with other database drivers
252
+        return $row;
253
+    }
239 254
 
240
-		return $field_array;
241
-	}
242
-
243
-	/**
244
-	 * @see DBManager::fetchRow()
245
-	 */
246
-	public function fetchRow($result)
247
-	{
248
-		if (empty($result))	return false;
249
-
250
-		$row = mysqli_fetch_assoc($result);
251
-		if($row == null) $row = false; //Make sure MySQLi driver results are consistent with other database drivers
252
-		return $row;
253
-	}
254
-
255
-	/**
256
-	 * @see DBManager::quote()
257
-	 */
258
-	public function quote($string)
259
-	{
260
-		return mysqli_real_escape_string($this->getDatabase(),$this->quoteInternal($string));
261
-	}
262
-
263
-	/**
264
-	 * @see DBManager::connect()
265
-	 */
266
-	public function connect(array $configOptions = null, $dieOnError = false)
267
-	{
268
-		global $sugar_config;
269
-
270
-		if (is_null($configOptions))
271
-			$configOptions = $sugar_config['dbconfig'];
272
-
273
-		if(!isset($this->database)) {
274
-
275
-			//mysqli connector has a separate parameter for port.. We need to separate it out from the host name
276
-			$dbhost=$configOptions['db_host_name'];
255
+    /**
256
+     * @see DBManager::quote()
257
+     */
258
+    public function quote($string)
259
+    {
260
+        return mysqli_real_escape_string($this->getDatabase(),$this->quoteInternal($string));
261
+    }
262
+
263
+    /**
264
+     * @see DBManager::connect()
265
+     */
266
+    public function connect(array $configOptions = null, $dieOnError = false)
267
+    {
268
+        global $sugar_config;
269
+
270
+        if (is_null($configOptions))
271
+            $configOptions = $sugar_config['dbconfig'];
272
+
273
+        if(!isset($this->database)) {
274
+
275
+            //mysqli connector has a separate parameter for port.. We need to separate it out from the host name
276
+            $dbhost=$configOptions['db_host_name'];
277 277
             $dbport=isset($configOptions['db_port']) ? ($configOptions['db_port'] == '' ? null : $configOptions['db_port']) : null;
278 278
 			
279
-			$pos=strpos($configOptions['db_host_name'],':');
280
-			if ($pos !== false) {
281
-				$dbhost=substr($configOptions['db_host_name'],0,$pos);
282
-				$dbport=substr($configOptions['db_host_name'],$pos+1);
283
-			}
284
-
285
-			$this->database = @mysqli_connect($dbhost,$configOptions['db_user_name'],$configOptions['db_password'],isset($configOptions['db_name'])?$configOptions['db_name']:'',$dbport);
286
-			if(empty($this->database)) {
287
-				$GLOBALS['log']->fatal("Could not connect to DB server ".$dbhost." as ".$configOptions['db_user_name'].". port " .$dbport . ": " . mysqli_connect_error());
288
-				if($dieOnError) {
289
-					if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
290
-						sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
291
-					} else {
292
-						sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
293
-					}
294
-				} else {
295
-					return false;
296
-				}
297
-			}
298
-		}
279
+            $pos=strpos($configOptions['db_host_name'],':');
280
+            if ($pos !== false) {
281
+                $dbhost=substr($configOptions['db_host_name'],0,$pos);
282
+                $dbport=substr($configOptions['db_host_name'],$pos+1);
283
+            }
284
+
285
+            $this->database = @mysqli_connect($dbhost,$configOptions['db_user_name'],$configOptions['db_password'],isset($configOptions['db_name'])?$configOptions['db_name']:'',$dbport);
286
+            if(empty($this->database)) {
287
+                $GLOBALS['log']->fatal("Could not connect to DB server ".$dbhost." as ".$configOptions['db_user_name'].". port " .$dbport . ": " . mysqli_connect_error());
288
+                if($dieOnError) {
289
+                    if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
290
+                        sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
291
+                    } else {
292
+                        sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
293
+                    }
294
+                } else {
295
+                    return false;
296
+                }
297
+            }
298
+        }
299 299
 
300
-		if(!empty($configOptions['db_name']) && !@mysqli_select_db($this->database,$configOptions['db_name'])) {
301
-			$GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}: " . mysqli_connect_error());
302
-			if($dieOnError) {
303
-					if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
304
-						sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
305
-					} else {
306
-						sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
307
-					}
308
-			} else {
309
-				return false;
310
-			}
311
-	    }
300
+        if(!empty($configOptions['db_name']) && !@mysqli_select_db($this->database,$configOptions['db_name'])) {
301
+            $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}: " . mysqli_connect_error());
302
+            if($dieOnError) {
303
+                    if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
304
+                        sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
305
+                    } else {
306
+                        sugar_die("Could not connect to the database. Please refer to suitecrm.log for details.");
307
+                    }
308
+            } else {
309
+                return false;
310
+            }
311
+        }
312 312
 
313
-		// cn: using direct calls to prevent this from spamming the Logs
313
+        // cn: using direct calls to prevent this from spamming the Logs
314 314
 	    
315
-	    $collation = $this->getOption('collation');
316
-	    if(!empty($collation)) {
317
-	    	$names = "SET NAMES 'utf8' COLLATE '$collation'";
318
-	    	mysqli_query($this->database,$names);
319
-		}
320
-	    mysqli_set_charset ($this->database , "utf8" );
321
-
322
-		if($this->checkError('Could Not Connect', $dieOnError))
323
-			$GLOBALS['log']->info("connected to db");
324
-
325
-		$this->connectOptions = $configOptions;
326
-		return true;
327
-	}
328
-
329
-	/**
330
-	 * (non-PHPdoc)
331
-	 * @see MysqlManager::lastDbError()
332
-	 */
333
-	public function lastDbError()
334
-	{
335
-		if($this->database) {
336
-		    if(mysqli_errno($this->database)) {
337
-			    return "MySQL error ".mysqli_errno($this->database).": ".mysqli_error($this->database);
338
-		    }
339
-		} else {
340
-			$err =  mysqli_connect_error();
341
-			if($err) {
342
-			    return $err;
343
-			}
344
-		}
315
+        $collation = $this->getOption('collation');
316
+        if(!empty($collation)) {
317
+            $names = "SET NAMES 'utf8' COLLATE '$collation'";
318
+            mysqli_query($this->database,$names);
319
+        }
320
+        mysqli_set_charset ($this->database , "utf8" );
345 321
 
346
-		return false;
347
-	}
322
+        if($this->checkError('Could Not Connect', $dieOnError))
323
+            $GLOBALS['log']->info("connected to db");
348 324
 
349
-	public function getDbInfo()
350
-	{
351
-		$charsets = $this->getCharsetInfo();
352
-		$charset_str = array();
353
-		foreach($charsets as $name => $value) {
354
-			$charset_str[] = "$name = $value";
355
-		}
356
-		return array(
357
-			"MySQLi Version" => @mysqli_get_client_info(),
358
-			"MySQLi Host Info" => @mysqli_get_host_info($this->database),
359
-			"MySQLi Server Info" => @mysqli_get_server_info($this->database),
360
-			"MySQLi Client Encoding" =>  @mysqli_character_set_name($this->database),
361
-			"MySQL Character Set Settings" => join(", ", $charset_str),
362
-		);
363
-	}
364
-
365
-	/**
366
-	 * Select database
367
-	 * @param string $dbname
368
-	 */
369
-	protected function selectDb($dbname)
370
-	{
371
-		return mysqli_select_db($this->getDatabase(), $dbname);
372
-	}
373
-
374
-	/**
375
-	 * Check if this driver can be used
376
-	 * @return bool
377
-	 */
378
-	public function valid()
379
-	{
380
-		return function_exists("mysqli_connect") && empty($GLOBALS['sugar_config']['mysqli_disabled']);
381
-	}
325
+        $this->connectOptions = $configOptions;
326
+        return true;
327
+    }
328
+
329
+    /**
330
+     * (non-PHPdoc)
331
+     * @see MysqlManager::lastDbError()
332
+     */
333
+    public function lastDbError()
334
+    {
335
+        if($this->database) {
336
+            if(mysqli_errno($this->database)) {
337
+                return "MySQL error ".mysqli_errno($this->database).": ".mysqli_error($this->database);
338
+            }
339
+        } else {
340
+            $err =  mysqli_connect_error();
341
+            if($err) {
342
+                return $err;
343
+            }
344
+        }
345
+
346
+        return false;
347
+    }
348
+
349
+    public function getDbInfo()
350
+    {
351
+        $charsets = $this->getCharsetInfo();
352
+        $charset_str = array();
353
+        foreach($charsets as $name => $value) {
354
+            $charset_str[] = "$name = $value";
355
+        }
356
+        return array(
357
+            "MySQLi Version" => @mysqli_get_client_info(),
358
+            "MySQLi Host Info" => @mysqli_get_host_info($this->database),
359
+            "MySQLi Server Info" => @mysqli_get_server_info($this->database),
360
+            "MySQLi Client Encoding" =>  @mysqli_character_set_name($this->database),
361
+            "MySQL Character Set Settings" => join(", ", $charset_str),
362
+        );
363
+    }
364
+
365
+    /**
366
+     * Select database
367
+     * @param string $dbname
368
+     */
369
+    protected function selectDb($dbname)
370
+    {
371
+        return mysqli_select_db($this->getDatabase(), $dbname);
372
+    }
373
+
374
+    /**
375
+     * Check if this driver can be used
376
+     * @return bool
377
+     */
378
+    public function valid()
379
+    {
380
+        return function_exists("mysqli_connect") && empty($GLOBALS['sugar_config']['mysqli_disabled']);
381
+    }
382 382
 }
Please login to merge, or discard this patch.
Braces   +34 added lines, -19 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.
@@ -135,8 +137,9 @@  discard block
 block discarded – undo
135 137
 		$result = $suppress?@mysqli_query($this->database,$sql):mysqli_query($this->database,$sql);
136 138
 		$md5 = md5($sql);
137 139
 
138
-		if (empty($queryMD5[$md5]))
139
-			$queryMD5[$md5] = true;
140
+		if (empty($queryMD5[$md5])) {
141
+					$queryMD5[$md5] = true;
142
+		}
140 143
 
141 144
 		$this->query_time = microtime(true) - $this->query_time;
142 145
 		$GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
@@ -155,8 +158,9 @@  discard block
 block discarded – undo
155 158
 		*/
156 159
 
157 160
 
158
-		if($keepResult)
159
-			$this->lastResult = $result;
161
+		if($keepResult) {
162
+					$this->lastResult = $result;
163
+		}
160 164
 		$this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
161 165
 
162 166
 		return $result;
@@ -209,8 +213,9 @@  discard block
 block discarded – undo
209 213
 	 */
210 214
 	protected function freeDbResult($dbResult)
211 215
 	{
212
-		if(!empty($dbResult))
213
-			mysqli_free_result($dbResult);
216
+		if(!empty($dbResult)) {
217
+					mysqli_free_result($dbResult);
218
+		}
214 219
 	}
215 220
 
216 221
 	/**
@@ -220,17 +225,20 @@  discard block
 block discarded – undo
220 225
 	{
221 226
 		$field_array = array();
222 227
 
223
-		if (!isset($result) || empty($result))
224
-			return 0;
228
+		if (!isset($result) || empty($result)) {
229
+					return 0;
230
+		}
225 231
 
226 232
 		$i = 0;
227 233
 		while ($i < mysqli_num_fields($result)) {
228 234
 			$meta = mysqli_fetch_field_direct($result, $i);
229
-			if (!$meta)
230
-				return 0;
235
+			if (!$meta) {
236
+							return 0;
237
+			}
231 238
 
232
-			if($make_lower_case == true)
233
-				$meta->name = strtolower($meta->name);
239
+			if($make_lower_case == true) {
240
+							$meta->name = strtolower($meta->name);
241
+			}
234 242
 
235 243
 			$field_array[] = $meta->name;
236 244
 
@@ -245,10 +253,15 @@  discard block
 block discarded – undo
245 253
 	 */
246 254
 	public function fetchRow($result)
247 255
 	{
248
-		if (empty($result))	return false;
256
+		if (empty($result)) {
257
+		    return false;
258
+		}
249 259
 
250 260
 		$row = mysqli_fetch_assoc($result);
251
-		if($row == null) $row = false; //Make sure MySQLi driver results are consistent with other database drivers
261
+		if($row == null) {
262
+		    $row = false;
263
+		}
264
+		//Make sure MySQLi driver results are consistent with other database drivers
252 265
 		return $row;
253 266
 	}
254 267
 
@@ -267,8 +280,9 @@  discard block
 block discarded – undo
267 280
 	{
268 281
 		global $sugar_config;
269 282
 
270
-		if (is_null($configOptions))
271
-			$configOptions = $sugar_config['dbconfig'];
283
+		if (is_null($configOptions)) {
284
+					$configOptions = $sugar_config['dbconfig'];
285
+		}
272 286
 
273 287
 		if(!isset($this->database)) {
274 288
 
@@ -319,8 +333,9 @@  discard block
 block discarded – undo
319 333
 		}
320 334
 	    mysqli_set_charset ($this->database , "utf8" );
321 335
 
322
-		if($this->checkError('Could Not Connect', $dieOnError))
323
-			$GLOBALS['log']->info("connected to db");
336
+		if($this->checkError('Could Not Connect', $dieOnError)) {
337
+					$GLOBALS['log']->info("connected to db");
338
+		}
324 339
 
325 340
 		$this->connectOptions = $configOptions;
326 341
 		return true;
Please login to merge, or discard this patch.
modules/Calls/vardefs.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -330,7 +330,7 @@
 block discarded – undo
330 330
                 'vname' => 'LBL_CONTACTS',
331 331
             ),
332 332
         'aos_contracts' =>
333
-            array (
333
+            array(
334 334
                 'name' => 'aos_contracts',
335 335
                 'type' => 'link',
336 336
                 'relationship' => 'aos_contracts_calls',
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.
modules/Campaigns/WizardNewsletter.php 3 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
     foreach($trkr_lists as $trkr_id){
300 300
         $ct_focus = new CampaignTracker();
301 301
         $ct_focus->retrieve($trkr_id);
302
-      if(isset($ct_focus->tracker_name) && !empty($ct_focus->tracker_name)){
302
+        if(isset($ct_focus->tracker_name) && !empty($ct_focus->tracker_name)){
303 303
             if($ct_focus->is_optout){$opt = 'checked';}else{$opt = '';}
304 304
             $trkr_html .= "<div id='existing_trkr".$trkr_count."'> <table width='100%' border='0' cellspacing='0' cellpadding='0'>" ;
305 305
             $trkr_html .= "<tr class='evenListRowS1'><td width='15%'><input name='wiz_step3_is_optout".$trkr_count."' title='".$mod_strings['LBL_EDIT_OPT_OUT'] . $trkr_count ."' id='existing_is_optout". $trkr_count ."' class='checkbox' type='checkbox' $opt  /><input name='wiz_step3_id".$trkr_count."' value='".$ct_focus->id."' id='existing_tracker_id". $trkr_count ."'type='hidden''/></td>";
@@ -310,8 +310,8 @@  discard block
 block discarded – undo
310 310
 
311 311
 
312 312
 
313
-      }
314
-      $trkr_count =$trkr_count+1;
313
+        }
314
+        $trkr_count =$trkr_count+1;
315 315
     }
316 316
     
317 317
     $trkr_html .= "<div id='no_trackers'></div>";
@@ -424,33 +424,33 @@  discard block
 block discarded – undo
424 424
 $prospect_lists = $focus->prospectlists->get();
425 425
 
426 426
 if((isset($_REQUEST['wizardtype']) && $_REQUEST['wizardtype'] ==1) || ($focus->campaign_type=='NewsLetter')){
427
- //this is a newsletter type campaign, fill in subscription values   
427
+    //this is a newsletter type campaign, fill in subscription values   
428 428
 
429 429
 //if prospect lists are returned, then iterate through and populate form values
430 430
 if(count($prospect_lists)>0){
431 431
     
432 432
     foreach($prospect_lists as $pl_id){
433 433
     //retrieve prospect list
434
-     $pl = new ProspectList();   
435
-     $pl->retrieve($pl_id);
434
+        $pl = new ProspectList();   
435
+        $pl->retrieve($pl_id);
436 436
 
437
-      if(isset($pl->list_type) && !empty($pl->list_type)){
438
-         //assign values based on type
439
-         if(($pl->list_type == 'default') || ($pl->list_type == 'seed')){            
437
+        if(isset($pl->list_type) && !empty($pl->list_type)){
438
+            //assign values based on type
439
+            if(($pl->list_type == 'default') || ($pl->list_type == 'seed')){            
440 440
             $ss->assign('SUBSCRIPTION_ID', $pl->id);
441 441
             $ss->assign('SUBSCRIPTION_NAME', $pl->name);
442
-         };
443
-         if($pl->list_type == 'exempt'){
442
+            };
443
+            if($pl->list_type == 'exempt'){
444 444
             $ss->assign('UNSUBSCRIPTION_ID', $pl->id);
445 445
             $ss->assign('UNSUBSCRIPTION_NAME', $pl->name);
446 446
          
447
-         };
448
-         if($pl->list_type == 'test'){
447
+            };
448
+            if($pl->list_type == 'test'){
449 449
             $ss->assign('TEST_ID', $pl->id);
450 450
             $ss->assign('TEST_NAME', $pl->name);
451 451
          
452
-         };
453
-      }
452
+            };
453
+        }
454 454
      
455 455
     }
456 456
 }
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
 
531 531
 
532 532
 //  this is the wizard control script that resides in page    
533
- $divScript = <<<EOQ
533
+    $divScript = <<<EOQ
534 534
 
535 535
  <script type="text/javascript" language="javascript">
536 536
    
Please login to merge, or discard this patch.
Braces   +45 added lines, -37 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.
@@ -80,7 +82,7 @@  discard block
 block discarded – undo
80 82
 
81 83
 if( (isset($_REQUEST['wizardtype'])  && $_REQUEST['wizardtype']==1)  ||  ($focus->campaign_type=='NewsLetter')){
82 84
     echo getClassicModuleTitle($mod_strings['LBL_MODULE_NAME'], array($mod_strings['LBL_NEWSLETTER WIZARD_TITLE'].$focus->name), true, false);
83
-}else{
85
+} else{
84 86
     echo getClassicModuleTitle($mod_strings['LBL_MODULE_NAME'], array($mod_strings['LBL_CAMPAIGN'].$focus->name), true, false);   
85 87
 }
86 88
 
@@ -89,9 +91,15 @@  discard block
 block discarded – undo
89 91
 $ss->assign("MOD", $mod_strings);
90 92
 $ss->assign("APP", $app_strings);
91 93
 
92
-if (isset($_REQUEST['return_module'])) $ss->assign("RETURN_MODULE", $_REQUEST['return_module']);
93
-if (isset($_REQUEST['return_action'])) $ss->assign("RETURN_ACTION", $_REQUEST['return_action']);
94
-if (isset($_REQUEST['return_id'])) $ss->assign("RETURN_ID", $_REQUEST['return_id']);
94
+if (isset($_REQUEST['return_module'])) {
95
+    $ss->assign("RETURN_MODULE", $_REQUEST['return_module']);
96
+}
97
+if (isset($_REQUEST['return_action'])) {
98
+    $ss->assign("RETURN_ACTION", $_REQUEST['return_action']);
99
+}
100
+if (isset($_REQUEST['return_id'])) {
101
+    $ss->assign("RETURN_ID", $_REQUEST['return_id']);
102
+}
95 103
 // handle Create $module then Cancel
96 104
 if (empty($_REQUEST['return_id'])) {
97 105
     $ss->assign("RETURN_ACTION", 'index');
@@ -120,10 +128,10 @@  discard block
 block discarded – undo
120 128
 if( (isset($_REQUEST['wizardtype'])  && $_REQUEST['wizardtype']==1)  ||  ($focus->campaign_type=='NewsLetter')){
121 129
     $campaign_type = 'newsletter';
122 130
     $ss->assign("CAMPAIGN_DIAGNOSTIC_LINK", diagnose());    
123
-}elseif( (isset($_REQUEST['wizardtype'])  && $_REQUEST['wizardtype']==2)  || ($focus->campaign_type=='Email') ){
131
+} elseif( (isset($_REQUEST['wizardtype'])  && $_REQUEST['wizardtype']==2)  || ($focus->campaign_type=='Email') ){
124 132
     $campaign_type = 'email';
125 133
     $ss->assign("CAMPAIGN_DIAGNOSTIC_LINK", diagnose());
126
-}else{
134
+} else{
127 135
     $campaign_type = 'general';
128 136
 }
129 137
 
@@ -162,8 +170,12 @@  discard block
 block discarded – undo
162 170
 $ss->assign("CAMP_NAME", $focus->name);
163 171
 $ss->assign("CAMP_RECORD", $focus->id);
164 172
 $ss->assign("CAMP_IMPRESSIONS", $focus->impressions);
165
-if (empty($focus->assigned_user_id) && empty($focus->id))  $focus->assigned_user_id = $current_user->id;
166
-if (empty($focus->assigned_name) && empty($focus->id))  $focus->assigned_user_name = $current_user->user_name;
173
+if (empty($focus->assigned_user_id) && empty($focus->id)) {
174
+    $focus->assigned_user_id = $current_user->id;
175
+}
176
+if (empty($focus->assigned_name) && empty($focus->id)) {
177
+    $focus->assigned_user_name = $current_user->user_name;
178
+}
167 179
 $ss->assign("ASSIGNED_USER_OPTIONS", get_select_options_with_id(get_user_array(TRUE, "Active", $focus->assigned_user_id), $focus->assigned_user_id));
168 180
 //$ss->assign("ASSIGNED_USER_NAME", $focus->assigned_user_name);
169 181
 
@@ -171,10 +183,11 @@  discard block
 block discarded – undo
171 183
 
172 184
 $ss->assign("ASSIGNED_USER_ID", $focus->assigned_user_id );
173 185
 
174
-if((!isset($focus->status)) && (!isset($focus->id)))
186
+if((!isset($focus->status)) && (!isset($focus->id))) {
175 187
     $ss->assign("STATUS_OPTIONS", get_select_options_with_id($app_list_strings['campaign_status_dom'], 'Planning'));
176
-else
188
+} else {
177 189
     $ss->assign("STATUS_OPTIONS", get_select_options_with_id($app_list_strings['campaign_status_dom'], $focus->status));
190
+}
178 191
 
179 192
 //hide frequency options if this is not a newsletter
180 193
 if($campaign_type == 'newsletter'){
@@ -182,10 +195,10 @@  discard block
 block discarded – undo
182 195
     $ss->assign("FREQUENCY_LABEL", $mod_strings['LBL_CAMPAIGN_FREQUENCY']);
183 196
     if((!isset($focus->frequency)) && (!isset($focus->id))){
184 197
         $ss->assign("FREQ_OPTIONS", get_select_options_with_id($app_list_strings['newsletter_frequency_dom'], 'Monthly'));
185
-    }else{
198
+    } else{
186 199
         $ss->assign("FREQ_OPTIONS", get_select_options_with_id($app_list_strings['newsletter_frequency_dom'], $focus->frequency));
187 200
     }
188
-}else{
201
+} else{
189 202
     $ss->assign("HIDE_FREQUENCY_IF_NEWSLETTER", "input type='hidden'");
190 203
     $ss->assign("FREQUENCY_LABEL", '&nbsp;');
191 204
 }
@@ -195,12 +208,11 @@  discard block
 block discarded – undo
195 208
 if(isset($focus->currency_id) && !empty($focus->currency_id)){
196 209
     $selectCurrency = $currency->getSelectOptions($focus->currency_id);
197 210
     $ss->assign("CURRENCY", $selectCurrency);
198
-}
199
-else if($current_user->getPreference('currency') && !isset($focus->id))
211
+} else if($current_user->getPreference('currency') && !isset($focus->id))
200 212
 {
201 213
     $selectCurrency = $currency->getSelectOptions($current_user->getPreference('currency'));
202 214
     $ss->assign("CURRENCY", $selectCurrency);
203
-}else{
215
+} else{
204 216
 
205 217
     $selectCurrency = $currency->getSelectOptions();
206 218
     $ss->assign("CURRENCY", $selectCurrency);
@@ -231,7 +243,7 @@  discard block
 block discarded – undo
231 243
     foreach($OptionsArr as $key=>$val){
232 244
         if($val =='Newsletter' || $val =='Email' || $val =='' ){
233 245
             //do not add   
234
-        }else{
246
+        } else{
235 247
             $myTypeOptionsArr[$key] = $val;
236 248
         }
237 249
     }
@@ -243,7 +255,7 @@  discard block
 block discarded – undo
243 255
         //if the selected flag is set to true, then just populate
244 256
         if($selected){
245 257
             $type_option_html .="<option value='$optionKey' >$optionName</option>";
246
-        }else{//if not selected yet, check to see if this option should be selected
258
+        } else{//if not selected yet, check to see if this option should be selected
247 259
             //if the campaign type is not empty, then select the retrieved type
248 260
             if(!empty($focus->campaign_type)){
249 261
                 //check to see if key matches campaign type
@@ -252,11 +264,11 @@  discard block
 block discarded – undo
252 264
                     $type_option_html .="<option value='$optionKey' selected>$optionName</option>";
253 265
                     //mark as selected for next time
254 266
                     $selected=true;
255
-                }else{
267
+                } else{
256 268
                     //key does not match, just populate
257 269
                     $type_option_html .="<option value='$optionKey' >$optionName</option>";
258 270
                 }
259
-            }else{
271
+            } else{
260 272
             //since the campaign type is empty, then select first one                
261 273
                 $type_option_html .="<option value='$optionKey' selected>$optionName</option>";    
262 274
                 //mark as selected for next time
@@ -267,12 +279,12 @@  discard block
 block discarded – undo
267 279
     //assign the modified dropdown for general campaign creation
268 280
     $ss->assign("CAMPAIGN_TYPE_OPTIONS", $type_option_html);
269 281
     $ss->assign("SHOULD_TYPE_BE_DISABLED", "select");    
270
-}elseif($campaign_type == 'email'){
282
+} elseif($campaign_type == 'email'){
271 283
     //Assign Email as type of campaign being created an disable the select widget
272 284
     $ss->assign("CAMPAIGN_TYPE_OPTIONS", $mod_strings['LBL_EMAIL']);
273 285
     $ss->assign("SHOULD_TYPE_BE_DISABLED", "input type='hidden' value='Email'");
274 286
     $ss->assign("HIDE_CAMPAIGN_TYPE", true);
275
-}else{
287
+} else{
276 288
     //Assign NewsLetter as type of campaign being created an disable the select widget
277 289
     $ss->assign("CAMPAIGN_TYPE_OPTIONS", $mod_strings['LBL_NEWSLETTER']);
278 290
     $ss->assign("SHOULD_TYPE_BE_DISABLED", "input type='hidden' value='NewsLetter'");
@@ -300,7 +312,7 @@  discard block
 block discarded – undo
300 312
         $ct_focus = new CampaignTracker();
301 313
         $ct_focus->retrieve($trkr_id);
302 314
       if(isset($ct_focus->tracker_name) && !empty($ct_focus->tracker_name)){
303
-            if($ct_focus->is_optout){$opt = 'checked';}else{$opt = '';}
315
+            if($ct_focus->is_optout){$opt = 'checked';} else{$opt = '';}
304 316
             $trkr_html .= "<div id='existing_trkr".$trkr_count."'> <table width='100%' border='0' cellspacing='0' cellpadding='0'>" ;
305 317
             $trkr_html .= "<tr class='evenListRowS1'><td width='15%'><input name='wiz_step3_is_optout".$trkr_count."' title='".$mod_strings['LBL_EDIT_OPT_OUT'] . $trkr_count ."' id='existing_is_optout". $trkr_count ."' class='checkbox' type='checkbox' $opt  /><input name='wiz_step3_id".$trkr_count."' value='".$ct_focus->id."' id='existing_tracker_id". $trkr_count ."'type='hidden''/></td>";
306 318
             $trkr_html .= "<td width='40%'> <input id='existing_tracker_name". $trkr_count ."' type='text' size='20' maxlength='255' name='wiz_step3_tracker_name". $trkr_count ."' title='".$mod_strings['LBL_EDIT_TRACKER_NAME']. $trkr_count ."' value='".$ct_focus->tracker_name."' ></td>";
@@ -315,7 +327,7 @@  discard block
 block discarded – undo
315 327
     }
316 328
     
317 329
     $trkr_html .= "<div id='no_trackers'></div>";
318
-    }else{
330
+    } else{
319 331
         $trkr_html .= "<div id='no_trackers'><table width='100%' border='0' cellspacing='0' cellpadding='0'><tr class='evenListRowS1'><td>".$mod_strings['LBL_NONE']."</td></tr></table></div>";
320 332
     }
321 333
     $ss->assign('EXISTING_TRACKERS', $trkr_html);
@@ -457,7 +469,7 @@  discard block
 block discarded – undo
457 469
 
458 470
 
459 471
 
460
-}else{
472
+} else{
461 473
     //this is not a newlsetter campaign, so fill in target list table
462 474
     //create array for javascript, this will help to display the option text, not the value
463 475
     $dom_txt =' ';
@@ -485,7 +497,7 @@  discard block
 block discarded – undo
485 497
         }
486 498
 
487 499
         $trgt_html  .= "<div id='no_targets'></div>";
488
-    }else{
500
+    } else{
489 501
         $trgt_html  .= "<div id='no_targets'><table width='100%' border='0' cellspacing='0' cellpadding='0'><tr class='evenListRowS1'><td>".$mod_strings['LBL_NONE']."</td></tr></table></div>";
490 502
 
491 503
     }
@@ -572,12 +584,11 @@  discard block
 block discarded – undo
572 584
     $ss->assign('NAV_ITEMS',create_wiz_menu_items($_steps,'campaign',$mrkt_string,$summ_url, 'dotlist'));
573 585
     $ss->assign('HIDE_CONTINUE','hidden');
574 586
 
575
-}elseif($campaign_type == 'email'){
587
+} elseif($campaign_type == 'email'){
576 588
     $steps = create_email_steps();
577 589
     if($focus->id) {
578 590
         $summ_url = "index.php?action=WizardHome&module=Campaigns&return_id=" . $focus->id . "&record=" . $focus->id;
579
-    }
580
-    else {
591
+    } else {
581 592
         $summ_url = false;
582 593
     }
583 594
     foreach($steps as $key => $step) {
@@ -588,13 +599,12 @@  discard block
 block discarded – undo
588 599
     $template_id = isset($_REQUEST['template_id']) && $_REQUEST['template_id'] ? $_REQUEST['template_id'] : null;
589 600
     $ss->assign('NAV_ITEMS',create_wiz_menu_items($_steps,'email',$mrkt_string,$summ_url, 'dotlist', $campaign_id, $marketing_id, $template_id));
590 601
     $ss->assign('HIDE_CONTINUE','submit');
591
-}else{
602
+} else{
592 603
     $steps = create_newsletter_steps();
593 604
 
594 605
     if($focus->id) {
595 606
         $summ_url = "index.php?action=WizardHome&module=Campaigns&return_id=" . $focus->id . "&record=" . $focus->id;
596
-    }
597
-    else {
607
+    } else {
598 608
         $summ_url = false;
599 609
     }
600 610
     foreach($steps as $key => $step) {
@@ -696,8 +706,7 @@  discard block
 block discarded – undo
696 706
             preg_match('/\bhref=\'([^\']*)/', $mrkt_string, $matches);
697 707
             if(isset($matches[1])) {
698 708
                 $marketingLink = $matches[1] . ($matches[1] ? '&jump=2' : false);
699
-            }
700
-            else {
709
+            } else {
701 710
                 $marketingLink = false;
702 711
             }
703 712
 
@@ -710,8 +719,7 @@  discard block
 block discarded – undo
710 719
 
711 720
         $nav_html = new DotListWizardMenu($mod_strings, $steps, true);
712 721
 
713
-    }
714
-    else {
722
+    } else {
715 723
         $nav_html = '<table border="0" cellspacing="0" cellpadding="0" width="100%" >';
716 724
         if(isset($steps)  && !empty($steps)){
717 725
             $i=1;
@@ -724,7 +732,7 @@  discard block
 block discarded – undo
724 732
             $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i+1).">$mrkt_string</div></td></tr>";
725 733
             $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i+2).">".$mod_strings['LBL_NAVIGATION_MENU_SEND_EMAIL']."</div></li>";
726 734
             $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i+3).">".$summ_url."</div></td></tr>";
727
-        }else{
735
+        } else{
728 736
             $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i+1).">".$summ_url."</div></td></tr>";
729 737
         }
730 738
 
Please login to merge, or discard this patch.
Spacing   +141 added lines, -141 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.
@@ -64,10 +64,10 @@  discard block
 block discarded – undo
64 64
 /*************** GENERAL SETUP WORK **********/
65 65
 
66 66
 $focus = new Campaign();
67
-if(isset($_REQUEST['record'])) {
67
+if (isset($_REQUEST['record'])) {
68 68
     $focus->retrieve($_REQUEST['record']);
69 69
 }
70
-if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
70
+if (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
71 71
     $focus->id = "";
72 72
 }
73 73
 global $theme;
@@ -78,9 +78,9 @@  discard block
 block discarded – undo
78 78
 
79 79
 $GLOBALS['log']->info("Campaign NewsLetter Wizard");
80 80
 
81
-if( (isset($_REQUEST['wizardtype'])  && $_REQUEST['wizardtype']==1)  ||  ($focus->campaign_type=='NewsLetter')){
81
+if ((isset($_REQUEST['wizardtype']) && $_REQUEST['wizardtype'] == 1) || ($focus->campaign_type == 'NewsLetter')) {
82 82
     echo getClassicModuleTitle($mod_strings['LBL_MODULE_NAME'], array($mod_strings['LBL_NEWSLETTER WIZARD_TITLE'].$focus->name), true, false);
83
-}else{
83
+} else {
84 84
     echo getClassicModuleTitle($mod_strings['LBL_MODULE_NAME'], array($mod_strings['LBL_CAMPAIGN'].$focus->name), true, false);   
85 85
 }
86 86
 
@@ -104,26 +104,26 @@  discard block
 block discarded – undo
104 104
 $sqs_objects = array('parent_name' => $qsd->getQSParent(), 
105 105
                     'assigned_user_name' => $qsd->getQSUser(),
106 106
                     //'prospect_list_name' => getProspectListQSObjects(),
107
-                    'test_name' => getProspectListQSObjects('prospect_list_type_test', 'test_name','wiz_step3_test_name_id'),
108
-                    'unsubscription_name' => getProspectListQSObjects('prospect_list_type_exempt', 'unsubscription_name','wiz_step3_unsubscription_name_id'),
109
-                    'subscription_name' => getProspectListQSObjects('prospect_list_type_default', 'subscription_name','wiz_step3_subscription_name_id'),
107
+                    'test_name' => getProspectListQSObjects('prospect_list_type_test', 'test_name', 'wiz_step3_test_name_id'),
108
+                    'unsubscription_name' => getProspectListQSObjects('prospect_list_type_exempt', 'unsubscription_name', 'wiz_step3_unsubscription_name_id'),
109
+                    'subscription_name' => getProspectListQSObjects('prospect_list_type_default', 'subscription_name', 'wiz_step3_subscription_name_id'),
110 110
                     );
111 111
                     
112 112
 
113
-$quicksearch_js = '<script type="text/javascript" language="javascript">sqs_objects = ' . $json->encode($sqs_objects) . '</script>';
113
+$quicksearch_js = '<script type="text/javascript" language="javascript">sqs_objects = '.$json->encode($sqs_objects).'</script>';
114 114
 
115 115
 $ss->assign("JAVASCRIPT", $quicksearch_js);
116 116
 
117 117
 
118 118
 //set the campaign type based on wizardtype value from request object
119 119
 $campaign_type = 'newsletter';
120
-if( (isset($_REQUEST['wizardtype'])  && $_REQUEST['wizardtype']==1)  ||  ($focus->campaign_type=='NewsLetter')){
120
+if ((isset($_REQUEST['wizardtype']) && $_REQUEST['wizardtype'] == 1) || ($focus->campaign_type == 'NewsLetter')) {
121 121
     $campaign_type = 'newsletter';
122 122
     $ss->assign("CAMPAIGN_DIAGNOSTIC_LINK", diagnose());    
123
-}elseif( (isset($_REQUEST['wizardtype'])  && $_REQUEST['wizardtype']==2)  || ($focus->campaign_type=='Email') ){
123
+}elseif ((isset($_REQUEST['wizardtype']) && $_REQUEST['wizardtype'] == 2) || ($focus->campaign_type == 'Email')) {
124 124
     $campaign_type = 'email';
125 125
     $ss->assign("CAMPAIGN_DIAGNOSTIC_LINK", diagnose());
126
-}else{
126
+} else {
127 127
     $campaign_type = 'general';
128 128
 }
129 129
 
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 
144 144
 //set default values
145 145
 $ss->assign("CALENDAR_LANG", "en");
146
-$ss->assign("USER_DATEFORMAT", '('. $timedate->get_user_date_format().')');
146
+$ss->assign("USER_DATEFORMAT", '('.$timedate->get_user_date_format().')');
147 147
 $ss->assign("CALENDAR_DATEFORMAT", $timedate->get_cal_date_format());
148 148
 $ss->assign("CAMP_DATE_ENTERED", $focus->date_entered);
149 149
 $ss->assign("CAMP_DATE_MODIFIED", $focus->date_modified);
@@ -170,50 +170,50 @@  discard block
 block discarded – undo
170 170
 
171 171
 $focus->list_view_parse_additional_sections($ss);
172 172
 
173
-$ss->assign("ASSIGNED_USER_ID", $focus->assigned_user_id );
173
+$ss->assign("ASSIGNED_USER_ID", $focus->assigned_user_id);
174 174
 
175
-if((!isset($focus->status)) && (!isset($focus->id)))
175
+if ((!isset($focus->status)) && (!isset($focus->id)))
176 176
     $ss->assign("STATUS_OPTIONS", get_select_options_with_id($app_list_strings['campaign_status_dom'], 'Planning'));
177 177
 else
178 178
     $ss->assign("STATUS_OPTIONS", get_select_options_with_id($app_list_strings['campaign_status_dom'], $focus->status));
179 179
 
180 180
 //hide frequency options if this is not a newsletter
181
-if($campaign_type == 'newsletter'){
181
+if ($campaign_type == 'newsletter') {
182 182
     $ss->assign("HIDE_FREQUENCY_IF_NEWSLETTER", "Select");
183 183
     $ss->assign("FREQUENCY_LABEL", $mod_strings['LBL_CAMPAIGN_FREQUENCY']);
184
-    if((!isset($focus->frequency)) && (!isset($focus->id))){
184
+    if ((!isset($focus->frequency)) && (!isset($focus->id))) {
185 185
         $ss->assign("FREQ_OPTIONS", get_select_options_with_id($app_list_strings['newsletter_frequency_dom'], 'Monthly'));
186
-    }else{
186
+    } else {
187 187
         $ss->assign("FREQ_OPTIONS", get_select_options_with_id($app_list_strings['newsletter_frequency_dom'], $focus->frequency));
188 188
     }
189
-}else{
189
+} else {
190 190
     $ss->assign("HIDE_FREQUENCY_IF_NEWSLETTER", "input type='hidden'");
191 191
     $ss->assign("FREQUENCY_LABEL", '&nbsp;');
192 192
 }
193 193
 global $current_user;
194 194
 require_once('modules/Currencies/ListCurrency.php');
195 195
 $currency = new ListCurrency();
196
-if(isset($focus->currency_id) && !empty($focus->currency_id)){
196
+if (isset($focus->currency_id) && !empty($focus->currency_id)) {
197 197
     $selectCurrency = $currency->getSelectOptions($focus->currency_id);
198 198
     $ss->assign("CURRENCY", $selectCurrency);
199 199
 }
200
-else if($current_user->getPreference('currency') && !isset($focus->id))
200
+else if ($current_user->getPreference('currency') && !isset($focus->id))
201 201
 {
202 202
     $selectCurrency = $currency->getSelectOptions($current_user->getPreference('currency'));
203 203
     $ss->assign("CURRENCY", $selectCurrency);
204
-}else{
204
+} else {
205 205
 
206 206
     $selectCurrency = $currency->getSelectOptions();
207 207
     $ss->assign("CURRENCY", $selectCurrency);
208 208
 
209 209
 }
210 210
 global $current_user;
211
-if(is_admin($current_user) && $_REQUEST['module'] != 'DynamicLayout' && !empty($_SESSION['editinplace'])){  
211
+if (is_admin($current_user) && $_REQUEST['module'] != 'DynamicLayout' && !empty($_SESSION['editinplace'])) {  
212 212
     $record = '';
213
-    if(!empty($_REQUEST['record'])){
214
-        $record =   $_REQUEST['record'];
213
+    if (!empty($_REQUEST['record'])) {
214
+        $record = $_REQUEST['record'];
215 215
     }
216
-    $ss->assign("ADMIN_EDIT","<a href='index.php?action=index&module=DynamicLayout&from_action=".$_REQUEST['action'] ."&from_module=".$_REQUEST['module'] ."&record=".$record. "'>".SugarThemeRegistry::current()->getImage("EditLayout","border='0' align='bottom'",null,null,'.gif',$mod_strings['LBL_EDIT_LAYOUT'])."</a>");
216
+    $ss->assign("ADMIN_EDIT", "<a href='index.php?action=index&module=DynamicLayout&from_action=".$_REQUEST['action']."&from_module=".$_REQUEST['module']."&record=".$record."'>".SugarThemeRegistry::current()->getImage("EditLayout", "border='0' align='bottom'", null, null, '.gif', $mod_strings['LBL_EDIT_LAYOUT'])."</a>");
217 217
 
218 218
 }
219 219
 
@@ -226,55 +226,55 @@  discard block
 block discarded – undo
226 226
 
227 227
 //fill out the campaign type dropdown based on type of campaign being created
228 228
 $ss->assign("campaign_type", $campaign_type);
229
-if($campaign_type == 'general'){
229
+if ($campaign_type == 'general') {
230 230
     //get regular campaign dom object and strip out entries for email and newsletter
231 231
     $myTypeOptionsArr = array();
232 232
     $OptionsArr = $app_list_strings['campaign_type_dom'];
233
-    foreach($OptionsArr as $key=>$val){
234
-        if($val =='Newsletter' || $val =='Email' || $val =='' ){
233
+    foreach ($OptionsArr as $key=>$val) {
234
+        if ($val == 'Newsletter' || $val == 'Email' || $val == '') {
235 235
             //do not add   
236
-        }else{
236
+        } else {
237 237
             $myTypeOptionsArr[$key] = $val;
238 238
         }
239 239
     }
240 240
     
241 241
     //now create select option html without the newsletter/email, or blank ('') options
242
-    $type_option_html =' ';
242
+    $type_option_html = ' ';
243 243
     $selected = false;
244
-    foreach($myTypeOptionsArr as $optionKey=>$optionName){
244
+    foreach ($myTypeOptionsArr as $optionKey=>$optionName) {
245 245
         //if the selected flag is set to true, then just populate
246
-        if($selected){
247
-            $type_option_html .="<option value='$optionKey' >$optionName</option>";
248
-        }else{//if not selected yet, check to see if this option should be selected
246
+        if ($selected) {
247
+            $type_option_html .= "<option value='$optionKey' >$optionName</option>";
248
+        } else {//if not selected yet, check to see if this option should be selected
249 249
             //if the campaign type is not empty, then select the retrieved type
250
-            if(!empty($focus->campaign_type)){
250
+            if (!empty($focus->campaign_type)) {
251 251
                 //check to see if key matches campaign type
252
-                if($optionKey == $focus->campaign_type){
252
+                if ($optionKey == $focus->campaign_type) {
253 253
                     //mark as selected
254
-                    $type_option_html .="<option value='$optionKey' selected>$optionName</option>";
254
+                    $type_option_html .= "<option value='$optionKey' selected>$optionName</option>";
255 255
                     //mark as selected for next time
256
-                    $selected=true;
257
-                }else{
256
+                    $selected = true;
257
+                } else {
258 258
                     //key does not match, just populate
259
-                    $type_option_html .="<option value='$optionKey' >$optionName</option>";
259
+                    $type_option_html .= "<option value='$optionKey' >$optionName</option>";
260 260
                 }
261
-            }else{
261
+            } else {
262 262
             //since the campaign type is empty, then select first one                
263
-                $type_option_html .="<option value='$optionKey' selected>$optionName</option>";    
263
+                $type_option_html .= "<option value='$optionKey' selected>$optionName</option>";    
264 264
                 //mark as selected for next time
265
-                $selected=true;
265
+                $selected = true;
266 266
             }
267 267
         }    
268 268
     }
269 269
     //assign the modified dropdown for general campaign creation
270 270
     $ss->assign("CAMPAIGN_TYPE_OPTIONS", $type_option_html);
271 271
     $ss->assign("SHOULD_TYPE_BE_DISABLED", "select");    
272
-}elseif($campaign_type == 'email'){
272
+}elseif ($campaign_type == 'email') {
273 273
     //Assign Email as type of campaign being created an disable the select widget
274 274
     $ss->assign("CAMPAIGN_TYPE_OPTIONS", $mod_strings['LBL_EMAIL']);
275 275
     $ss->assign("SHOULD_TYPE_BE_DISABLED", "input type='hidden' value='Email'");
276 276
     $ss->assign("HIDE_CAMPAIGN_TYPE", true);
277
-}else{
277
+} else {
278 278
     //Assign NewsLetter as type of campaign being created an disable the select widget
279 279
     $ss->assign("CAMPAIGN_TYPE_OPTIONS", $mod_strings['LBL_NEWSLETTER']);
280 280
     $ss->assign("SHOULD_TYPE_BE_DISABLED", "input type='hidden' value='NewsLetter'");
@@ -291,33 +291,33 @@  discard block
 block discarded – undo
291 291
 $focus->load_relationship('tracked_urls');
292 292
 
293 293
 $trkr_lists = $focus->tracked_urls->get();
294
-$trkr_html ='';    
295
-$ss->assign('TRACKER_COUNT',count($trkr_lists));
296
-if(count($trkr_lists)>0){
294
+$trkr_html = '';    
295
+$ss->assign('TRACKER_COUNT', count($trkr_lists));
296
+if (count($trkr_lists) > 0) {
297 297
 global $odd_bg, $even_bg, $hilite_bg;
298 298
     
299 299
     $trkr_count = 0;
300 300
 //create the html to create tracker table
301
-    foreach($trkr_lists as $trkr_id){
301
+    foreach ($trkr_lists as $trkr_id) {
302 302
         $ct_focus = new CampaignTracker();
303 303
         $ct_focus->retrieve($trkr_id);
304
-      if(isset($ct_focus->tracker_name) && !empty($ct_focus->tracker_name)){
305
-            if($ct_focus->is_optout){$opt = 'checked';}else{$opt = '';}
306
-            $trkr_html .= "<div id='existing_trkr".$trkr_count."'> <table width='100%' border='0' cellspacing='0' cellpadding='0'>" ;
307
-            $trkr_html .= "<tr class='evenListRowS1'><td width='15%'><input name='wiz_step3_is_optout".$trkr_count."' title='".$mod_strings['LBL_EDIT_OPT_OUT'] . $trkr_count ."' id='existing_is_optout". $trkr_count ."' class='checkbox' type='checkbox' $opt  /><input name='wiz_step3_id".$trkr_count."' value='".$ct_focus->id."' id='existing_tracker_id". $trkr_count ."'type='hidden''/></td>";
308
-            $trkr_html .= "<td width='40%'> <input id='existing_tracker_name". $trkr_count ."' type='text' size='20' maxlength='255' name='wiz_step3_tracker_name". $trkr_count ."' title='".$mod_strings['LBL_EDIT_TRACKER_NAME']. $trkr_count ."' value='".$ct_focus->tracker_name."' ></td>";
309
-            $trkr_html .= "<td width='40%'><input type='text' size='60' maxlength='255' name='wiz_step3_tracker_url". $trkr_count ."' title='".$mod_strings['LBL_EDIT_TRACKER_URL']. $trkr_count ."' id='existing_tracker_url". $trkr_count ."' value='".$ct_focus->tracker_url."' ></td>";
304
+      if (isset($ct_focus->tracker_name) && !empty($ct_focus->tracker_name)) {
305
+            if ($ct_focus->is_optout) {$opt = 'checked'; } else {$opt = ''; }
306
+            $trkr_html .= "<div id='existing_trkr".$trkr_count."'> <table width='100%' border='0' cellspacing='0' cellpadding='0'>";
307
+            $trkr_html .= "<tr class='evenListRowS1'><td width='15%'><input name='wiz_step3_is_optout".$trkr_count."' title='".$mod_strings['LBL_EDIT_OPT_OUT'].$trkr_count."' id='existing_is_optout".$trkr_count."' class='checkbox' type='checkbox' $opt  /><input name='wiz_step3_id".$trkr_count."' value='".$ct_focus->id."' id='existing_tracker_id".$trkr_count."'type='hidden''/></td>";
308
+            $trkr_html .= "<td width='40%'> <input id='existing_tracker_name".$trkr_count."' type='text' size='20' maxlength='255' name='wiz_step3_tracker_name".$trkr_count."' title='".$mod_strings['LBL_EDIT_TRACKER_NAME'].$trkr_count."' value='".$ct_focus->tracker_name."' ></td>";
309
+            $trkr_html .= "<td width='40%'><input type='text' size='60' maxlength='255' name='wiz_step3_tracker_url".$trkr_count."' title='".$mod_strings['LBL_EDIT_TRACKER_URL'].$trkr_count."' id='existing_tracker_url".$trkr_count."' value='".$ct_focus->tracker_url."' ></td>";
310 310
             $trkr_html .= "<td><a href='#' onclick=\"javascript:remove_existing_tracker('existing_trkr".$trkr_count."','".$ct_focus->id."'); \" >  ";
311 311
             $trkr_html .= SugarThemeRegistry::current()->getImage('delete_inline', "border='0'  align='absmiddle'", 12, 12, ".gif", $mod_strings['LBL_DELETE'])."</a></td></tr></table></div>";
312 312
 
313 313
 
314 314
 
315 315
       }
316
-      $trkr_count =$trkr_count+1;
316
+      $trkr_count = $trkr_count + 1;
317 317
     }
318 318
     
319 319
     $trkr_html .= "<div id='no_trackers'></div>";
320
-    }else{
320
+    } else {
321 321
         $trkr_html .= "<div id='no_trackers'><table width='100%' border='0' cellspacing='0' cellpadding='0'><tr class='evenListRowS1'><td>".$mod_strings['LBL_NONE']."</td></tr></table></div>";
322 322
     }
323 323
     $ss->assign('EXISTING_TRACKERS', $trkr_html);
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
 
403 403
 $targetList = BeanFactory::getBean('ProspectLists')->get_full_list();
404 404
 
405
-if($targetList) {
405
+if ($targetList) {
406 406
     $targetListData = array();
407 407
     foreach ($targetList as $prospectLst) {
408 408
         $next = array(
@@ -436,29 +436,29 @@  discard block
 block discarded – undo
436 436
 
437 437
 $prospect_lists = $focus->prospectlists->get();
438 438
 
439
-if((isset($_REQUEST['wizardtype']) && $_REQUEST['wizardtype'] ==1) || ($focus->campaign_type=='NewsLetter')){
439
+if ((isset($_REQUEST['wizardtype']) && $_REQUEST['wizardtype'] == 1) || ($focus->campaign_type == 'NewsLetter')) {
440 440
  //this is a newsletter type campaign, fill in subscription values   
441 441
 
442 442
 //if prospect lists are returned, then iterate through and populate form values
443
-if(count($prospect_lists)>0){
443
+if (count($prospect_lists) > 0) {
444 444
     
445
-    foreach($prospect_lists as $pl_id){
445
+    foreach ($prospect_lists as $pl_id) {
446 446
     //retrieve prospect list
447 447
      $pl = new ProspectList();   
448 448
      $pl->retrieve($pl_id);
449 449
 
450
-      if(isset($pl->list_type) && !empty($pl->list_type)){
450
+      if (isset($pl->list_type) && !empty($pl->list_type)) {
451 451
          //assign values based on type
452
-         if(($pl->list_type == 'default') || ($pl->list_type == 'seed')){            
452
+         if (($pl->list_type == 'default') || ($pl->list_type == 'seed')) {            
453 453
             $ss->assign('SUBSCRIPTION_ID', $pl->id);
454 454
             $ss->assign('SUBSCRIPTION_NAME', $pl->name);
455 455
          };
456
-         if($pl->list_type == 'exempt'){
456
+         if ($pl->list_type == 'exempt') {
457 457
             $ss->assign('UNSUBSCRIPTION_ID', $pl->id);
458 458
             $ss->assign('UNSUBSCRIPTION_NAME', $pl->name);
459 459
          
460 460
          };
461
-         if($pl->list_type == 'test'){
461
+         if ($pl->list_type == 'test') {
462 462
             $ss->assign('TEST_ID', $pl->id);
463 463
             $ss->assign('TEST_NAME', $pl->name);
464 464
          
@@ -470,73 +470,73 @@  discard block
 block discarded – undo
470 470
 
471 471
 
472 472
 
473
-}else{
473
+} else {
474 474
     //this is not a newlsetter campaign, so fill in target list table
475 475
     //create array for javascript, this will help to display the option text, not the value
476
-    $dom_txt =' ';
477
-    foreach($app_list_strings['prospect_list_type_dom'] as $key=>$val){
478
-        $dom_txt .="if(trgt_type_text =='$key'){trgt_type_text='$val';}";
476
+    $dom_txt = ' ';
477
+    foreach ($app_list_strings['prospect_list_type_dom'] as $key=>$val) {
478
+        $dom_txt .= "if(trgt_type_text =='$key'){trgt_type_text='$val';}";
479 479
     }
480 480
     $ss->assign("PL_DOM_STMT", $dom_txt);
481 481
     $trgt_count = 0;
482 482
     $trgt_html = ' ';
483
-    if(count($prospect_lists)>0){
483
+    if (count($prospect_lists) > 0) {
484 484
 
485
-        foreach($prospect_lists as $pl_id){
485
+        foreach ($prospect_lists as $pl_id) {
486 486
             //retrieve prospect list
487 487
             $pl = new ProspectList();
488 488
             $pl_focus = $pl->retrieve($pl_id);
489
-            $trgt_html .= "<div id='existing_trgt".$trgt_count."'> <table class='tabDetailViewDL2' width='100%'>" ;
490
-            $trgt_html .= "<td width='100' style=\"width:25%\"> <input id='existing_target_name". $trgt_count ."' type='hidden' type='text' size='60' maxlength='255' name='existing_target_name". $trgt_count ."'  value='". ($pl_focus?$pl_focus->name:'-')."' ><a href=\"index.php?module=ProspectLists&action=DetailView&record=" . $pl_focus->id . "\" target=\"_blank\" title=\"" . $mod_strings['LBL_OPEN_IN_NEW_WINDOW'] . "\">". ($pl_focus?$pl_focus->name:'-')."</a></td>";
491
-            $trgt_html .= "<td width='100' style=\"width:25%\">".($pl_focus?$pl_focus->get_entry_count():'-')."</td>";
492
-            $trgt_html .= "<td width='100' style=\"width:25%\"><input type='hidden' size='60' maxlength='255' name='existing_tracker_list_type". $trgt_count ."'   id='existing_tracker_list_type". $trgt_count ."' value='".$pl_focus->list_type."' >".$app_list_strings['prospect_list_type_dom'][$pl_focus->list_type];
493
-            $trgt_html .= "<input type='hidden' name='added_target_id". $trgt_count ."' id='added_target_id". $trgt_count ."' value='". $pl_focus->id ."' ></td>";
489
+            $trgt_html .= "<div id='existing_trgt".$trgt_count."'> <table class='tabDetailViewDL2' width='100%'>";
490
+            $trgt_html .= "<td width='100' style=\"width:25%\"> <input id='existing_target_name".$trgt_count."' type='hidden' type='text' size='60' maxlength='255' name='existing_target_name".$trgt_count."'  value='".($pl_focus ? $pl_focus->name : '-')."' ><a href=\"index.php?module=ProspectLists&action=DetailView&record=".$pl_focus->id."\" target=\"_blank\" title=\"".$mod_strings['LBL_OPEN_IN_NEW_WINDOW']."\">".($pl_focus ? $pl_focus->name : '-')."</a></td>";
491
+            $trgt_html .= "<td width='100' style=\"width:25%\">".($pl_focus ? $pl_focus->get_entry_count() : '-')."</td>";
492
+            $trgt_html .= "<td width='100' style=\"width:25%\"><input type='hidden' size='60' maxlength='255' name='existing_tracker_list_type".$trgt_count."'   id='existing_tracker_list_type".$trgt_count."' value='".$pl_focus->list_type."' >".$app_list_strings['prospect_list_type_dom'][$pl_focus->list_type];
493
+            $trgt_html .= "<input type='hidden' name='added_target_id".$trgt_count."' id='added_target_id".$trgt_count."' value='".$pl_focus->id."' ></td>";
494 494
             $trgt_html .= "<td width='100' style=\"width:25%\"><a href='#' onclick=\"javascript:remove_existing_target('existing_trgt".$trgt_count."','".$pl_focus->id."'); \" >  ";
495 495
             $trgt_html .= SugarThemeRegistry::current()->getImage('delete_inline', "border='0' align='absmiddle'", 12, 12, ".gif", $mod_strings['LBL_DELETE'])."</a></td></tr></table></div>";
496 496
 
497
-            $trgt_count =$trgt_count +1;
497
+            $trgt_count = $trgt_count + 1;
498 498
         }
499 499
 
500 500
         $trgt_html  .= "<div id='no_targets'></div>";
501
-    }else{
501
+    } else {
502 502
         $trgt_html  .= "<div id='no_targets'><table width='100%' border='0' cellspacing='0' cellpadding='0'><tr class='evenListRowS1'><td>".$mod_strings['LBL_NONE']."</td></tr></table></div>";
503 503
 
504 504
     }
505
-    $ss->assign('EXISTING_TARGETS', $trgt_html );
505
+    $ss->assign('EXISTING_TARGETS', $trgt_html);
506 506
 
507 507
 }
508 508
 
509 509
     
510 510
 /**************************** WIZARD UI DIV Stuff *******************/
511 511
 $mrkt_string = $mod_strings['LBL_NAVIGATION_MENU_MARKETING'];
512
-if(!empty($focus->id)){
512
+if (!empty($focus->id)) {
513 513
     $mrkt_url = "<a  href='index.php?action=WizardMarketing&module=Campaigns&return_module=Campaigns&return_action=WizardHome";
514 514
     $mrkt_url .= "&return_id=".$focus->id."&campaign_id=".$focus->id;
515
-    $mrkt_url .= "'>". $mrkt_string."</a>";
515
+    $mrkt_url .= "'>".$mrkt_string."</a>";
516 516
     $mrkt_string = $mrkt_url;
517 517
 }
518 518
     $summ_url = $mod_strings['LBL_NAVIGATION_MENU_SUMMARY'];
519
-    if(!empty($focus->id)){
519
+    if (!empty($focus->id)) {
520 520
         $summ_url = "<a  href='index.php?action=WizardHome&module=Campaigns";
521 521
         $summ_url .= "&return_id=".$focus->id."&record=".$focus->id;
522
-        $summ_url .= "'> ". $mod_strings['LBL_NAVIGATION_MENU_SUMMARY']."</a>";
522
+        $summ_url .= "'> ".$mod_strings['LBL_NAVIGATION_MENU_SUMMARY']."</a>";
523 523
     } 
524 524
    
525 525
 
526 526
 
527
-$script_to_call ='';
528
-    if (!empty($focus->id)){
527
+$script_to_call = '';
528
+    if (!empty($focus->id)) {
529 529
         $maxStep = 2;
530 530
         $script_to_call = "link_navs(1, {$maxStep});";
531
-        if(isset($_REQUEST['direct_step']) and !empty($_REQUEST['direct_step'])){
532
-            $directStep = (int) $_REQUEST['direct_step'];
533
-            if($directStep < 1) {
531
+        if (isset($_REQUEST['direct_step']) and !empty($_REQUEST['direct_step'])) {
532
+            $directStep = (int)$_REQUEST['direct_step'];
533
+            if ($directStep < 1) {
534 534
                 $directStep = 1;
535 535
             }
536
-            if($directStep > $maxStep) {
536
+            if ($directStep > $maxStep) {
537 537
                 $directStep = $maxStep;
538 538
             }
539
-            $script_to_call .='   direct(' . $directStep . ');';
539
+            $script_to_call .= '   direct('.$directStep.');';
540 540
         }
541 541
     } 
542 542
     $ss->assign("HILITE_ALL", $script_to_call);
@@ -576,56 +576,56 @@  discard block
 block discarded – undo
576 576
 
577 577
 //Create the html to fill in the wizard steps
578 578
 
579
-if($campaign_type == 'general'){
579
+if ($campaign_type == 'general') {
580 580
     $steps = create_campaign_steps();
581 581
 
582
-    foreach($steps as $key => $step) {
582
+    foreach ($steps as $key => $step) {
583 583
         $_steps[$key] = false;
584 584
     }
585
-    $ss->assign('NAV_ITEMS',create_wiz_menu_items($_steps,'campaign',$mrkt_string,$summ_url, 'dotlist'));
586
-    $ss->assign('HIDE_CONTINUE','hidden');
585
+    $ss->assign('NAV_ITEMS', create_wiz_menu_items($_steps, 'campaign', $mrkt_string, $summ_url, 'dotlist'));
586
+    $ss->assign('HIDE_CONTINUE', 'hidden');
587 587
 
588
-}elseif($campaign_type == 'email'){
588
+}elseif ($campaign_type == 'email') {
589 589
     $steps = create_email_steps();
590
-    if($focus->id) {
591
-        $summ_url = "index.php?action=WizardHome&module=Campaigns&return_id=" . $focus->id . "&record=" . $focus->id;
590
+    if ($focus->id) {
591
+        $summ_url = "index.php?action=WizardHome&module=Campaigns&return_id=".$focus->id."&record=".$focus->id;
592 592
     }
593 593
     else {
594 594
         $summ_url = false;
595 595
     }
596
-    foreach($steps as $key => $step) {
596
+    foreach ($steps as $key => $step) {
597 597
         $_steps[$key] = false;
598 598
     }
599 599
     $campaign_id = $focus->id;
600 600
     $marketing_id = isset($_REQUEST['marketing_id']) && $_REQUEST['marketing_id'] ? $_REQUEST['marketing_id'] : null;
601 601
     $template_id = isset($_REQUEST['template_id']) && $_REQUEST['template_id'] ? $_REQUEST['template_id'] : null;
602
-    $ss->assign('NAV_ITEMS',create_wiz_menu_items($_steps,'email',$mrkt_string,$summ_url, 'dotlist', $campaign_id, $marketing_id, $template_id));
603
-    $ss->assign('HIDE_CONTINUE','submit');
604
-}else{
602
+    $ss->assign('NAV_ITEMS', create_wiz_menu_items($_steps, 'email', $mrkt_string, $summ_url, 'dotlist', $campaign_id, $marketing_id, $template_id));
603
+    $ss->assign('HIDE_CONTINUE', 'submit');
604
+} else {
605 605
     $steps = create_newsletter_steps();
606 606
 
607
-    if($focus->id) {
608
-        $summ_url = "index.php?action=WizardHome&module=Campaigns&return_id=" . $focus->id . "&record=" . $focus->id;
607
+    if ($focus->id) {
608
+        $summ_url = "index.php?action=WizardHome&module=Campaigns&return_id=".$focus->id."&record=".$focus->id;
609 609
     }
610 610
     else {
611 611
         $summ_url = false;
612 612
     }
613
-    foreach($steps as $key => $step) {
613
+    foreach ($steps as $key => $step) {
614 614
         $_steps[$key] = false;
615 615
     }
616
-    $ss->assign('NAV_ITEMS',create_wiz_menu_items($_steps,'newsletter',$mrkt_string,$summ_url, 'dotlist'));
617
-    $ss->assign('HIDE_CONTINUE','submit');
616
+    $ss->assign('NAV_ITEMS', create_wiz_menu_items($_steps, 'newsletter', $mrkt_string, $summ_url, 'dotlist'));
617
+    $ss->assign('HIDE_CONTINUE', 'submit');
618 618
 }
619 619
 
620 620
 $ss->assign('TOTAL_STEPS', count($steps));
621
-$sshtml = create_wiz_step_divs($steps,$ss);
622
-$ss->assign('STEPS',$sshtml);
621
+$sshtml = create_wiz_step_divs($steps, $ss);
622
+$ss->assign('STEPS', $sshtml);
623 623
      	   	
624 624
 
625 625
 /**************************** FINAL END OF PAGE UI Stuff *******************/
626 626
 
627
-if(isset($_REQUEST['wizardtype'])) {
628
-    switch($_REQUEST['wizardtype']) {
627
+if (isset($_REQUEST['wizardtype'])) {
628
+    switch ($_REQUEST['wizardtype']) {
629 629
         case '1':
630 630
             $ss->assign('campaign_type', 'NewsLetter');
631 631
             break;
@@ -644,12 +644,12 @@  discard block
 block discarded – undo
644 644
  * Marketing dropdown on summary page stores the last selected value in session
645 645
  * but we should unset it before user select an other campaign
646 646
  */
647
-if(!$focus->id && isset($campaign_id) && $campaign_id) {
647
+if (!$focus->id && isset($campaign_id) && $campaign_id) {
648 648
     unset($_SESSION['campaignWizard'][$campaign_id]['defaultSelectedMarketingId']);
649 649
 }
650 650
 
651 651
 
652
-function create_newsletter_steps(){
652
+function create_newsletter_steps() {
653 653
     global $mod_strings;
654 654
     $steps[$mod_strings['LBL_NAVIGATION_MENU_GEN1']]          = file_exists('custom/modules/Campaigns/tpls/WizardCampaignHeader.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignHeader.tpl' : 'modules/Campaigns/tpls/WizardCampaignHeader.tpl';
655 655
     //$steps[$mod_strings['LBL_NAVIGATION_MENU_GEN2']]          = file_exists('custom/modules/Campaigns/tpls/WizardCampaignBudget.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignBudget.tpl' : 'modules/Campaigns/tpls/WizardCampaignBudget.tpl';
@@ -658,54 +658,54 @@  discard block
 block discarded – undo
658 658
     return  $steps;
659 659
 }
660 660
 
661
-function create_campaign_steps(){
661
+function create_campaign_steps() {
662 662
     global $mod_strings;
663 663
     $steps[$mod_strings['LBL_NAVIGATION_MENU_GEN1']]          = file_exists('custom/modules/Campaigns/tpls/WizardCampaignHeader.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignHeader.tpl' : 'modules/Campaigns/tpls/WizardCampaignHeader.tpl';
664 664
     $steps[$mod_strings['LBL_NAVIGATION_MENU_GEN2']]          = file_exists('custom/modules/Campaigns/tpls/WizardCampaignBudget.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignBudget.tpl' : 'modules/Campaigns/tpls/WizardCampaignBudget.tpl';
665
-    $steps[$mod_strings['LBL_TARGET_LISTS']]                   = file_exists('custom/modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl' : 'modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl';
665
+    $steps[$mod_strings['LBL_TARGET_LISTS']] = file_exists('custom/modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl' : 'modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl';
666 666
     return  $steps;
667 667
 }
668 668
 
669
-function create_email_steps(){
669
+function create_email_steps() {
670 670
     global $mod_strings;
671
-    $steps[$mod_strings['LBL_NAVIGATION_MENU_GEN1']]          = file_exists('custom/modules/Campaigns/tpls/WizardCampaignHeader.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignHeader.tpl' : 'modules/Campaigns/tpls/WizardCampaignHeader.tpl';
671
+    $steps[$mod_strings['LBL_NAVIGATION_MENU_GEN1']] = file_exists('custom/modules/Campaigns/tpls/WizardCampaignHeader.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignHeader.tpl' : 'modules/Campaigns/tpls/WizardCampaignHeader.tpl';
672 672
     //$steps[$mod_strings['LBL_NAVIGATION_MENU_GEN2']]          = file_exists('custom/modules/Campaigns/tpls/WizardCampaignBudget.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignBudget.tpl' : 'modules/Campaigns/tpls/WizardCampaignBudget.tpl';
673 673
     //$steps[$mod_strings['LBL_NAVIGATION_MENU_TRACKERS']]      = file_exists('custom/modules/Campaigns/tpls/WizardCampaignTracker.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignTracker.tpl' : 'modules/Campaigns/tpls/WizardCampaignTracker.tpl';
674
-    $steps[$mod_strings['LBL_TARGET_LISTS']]                   = file_exists('custom/modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl' : 'modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl';
674
+    $steps[$mod_strings['LBL_TARGET_LISTS']] = file_exists('custom/modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl') ? 'custom/modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl' : 'modules/Campaigns/tpls/WizardCampaignTargetListForNonNewsLetter.tpl';
675 675
     return  $steps;
676 676
 }
677 677
 
678 678
 
679
-function create_wiz_step_divs($steps,$ss){
679
+function create_wiz_step_divs($steps, $ss) {
680 680
     $step_html = '';
681
-    if(isset($steps)  && !empty($steps)){
682
-        $i=1;
683
-        foreach($steps as $name=>$step){
684
-            $step_html .="<p><div id='step$i'>";
681
+    if (isset($steps) && !empty($steps)) {
682
+        $i = 1;
683
+        foreach ($steps as $name=>$step) {
684
+            $step_html .= "<p><div id='step$i'>";
685 685
             $step_html .= $ss->fetch($step);
686
-            $step_html .="</div></p>";
687
-            $i = $i+1;
686
+            $step_html .= "</div></p>";
687
+            $i = $i + 1;
688 688
         }    
689 689
     }
690 690
     return $step_html;
691 691
 }
692 692
 
693
-function create_wiz_menu_items($steps,$type,$mrkt_string,$summ_url, $view = null, $campaign_id = null, $marketing_id = null, $template_id = null){
693
+function create_wiz_menu_items($steps, $type, $mrkt_string, $summ_url, $view = null, $campaign_id = null, $marketing_id = null, $template_id = null) {
694 694
 
695 695
     global $mod_strings;
696 696
 
697 697
 
698
-    if($view == 'dotlist') {
698
+    if ($view == 'dotlist') {
699 699
 
700 700
         include_once 'modules/Campaigns/DotListWizardMenu.php';
701 701
 
702
-        if($type!='campaign') {
702
+        if ($type != 'campaign') {
703 703
             $templateURLForProgressBar = false;
704 704
             if ($campaign_id && $marketing_id && $template_id) {
705 705
                 $templateURLForProgressBar = "index.php?action=WizardMarketing&module=Campaigns&return_module=Campaigns&return_action=WizardHome&return_id={$campaign_id}&campaign_id={$campaign_id}&jump=2&marketing_id={$marketing_id}&record={$marketing_id}&campaign_type=Email&template_id={$template_id}";
706 706
             }
707 707
 
708
-            if(preg_match('/\bhref=\'([^\']*)/', $mrkt_string, $matches)) {
708
+            if (preg_match('/\bhref=\'([^\']*)/', $mrkt_string, $matches)) {
709 709
                 $templateURLForProgressBar = $matches[1];
710 710
             }
711 711
 
@@ -715,8 +715,8 @@  discard block
 block discarded – undo
715 715
         if ($type == 'newsletter' || $type == 'email') {
716 716
 
717 717
             preg_match('/\bhref=\'([^\']*)/', $mrkt_string, $matches);
718
-            if(isset($matches[1])) {
719
-                $marketingLink = $matches[1] . ($matches[1] ? '&jump=2' : false);
718
+            if (isset($matches[1])) {
719
+                $marketingLink = $matches[1].($matches[1] ? '&jump=2' : false);
720 720
             }
721 721
             else {
722 722
                 $marketingLink = false;
@@ -734,19 +734,19 @@  discard block
 block discarded – undo
734 734
     }
735 735
     else {
736 736
         $nav_html = '<table border="0" cellspacing="0" cellpadding="0" width="100%" >';
737
-        if(isset($steps)  && !empty($steps)){
738
-            $i=1;
739
-            foreach($steps as $name=>$step){
737
+        if (isset($steps) && !empty($steps)) {
738
+            $i = 1;
739
+            foreach ($steps as $name=>$step) {
740 740
                 $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step$i'>$name</div></td></tr>";
741
-                $i=$i+1;
741
+                $i = $i + 1;
742 742
             }
743 743
         }
744
-        if($type == 'newsletter'  ||  $type == 'email'){
745
-            $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i+1).">$mrkt_string</div></td></tr>";
746
-            $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i+2).">".$mod_strings['LBL_NAVIGATION_MENU_SEND_EMAIL']."</div></li>";
747
-            $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i+3).">".$summ_url."</div></td></tr>";
748
-        }else{
749
-            $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i+1).">".$summ_url."</div></td></tr>";
744
+        if ($type == 'newsletter' || $type == 'email') {
745
+            $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i + 1).">$mrkt_string</div></td></tr>";
746
+            $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i + 2).">".$mod_strings['LBL_NAVIGATION_MENU_SEND_EMAIL']."</div></li>";
747
+            $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i + 3).">".$summ_url."</div></td></tr>";
748
+        } else {
749
+            $nav_html .= "<tr><td scope='row' nowrap><div id='nav_step'".($i + 1).">".$summ_url."</div></td></tr>";
750 750
         }
751 751
 
752 752
         $nav_html .= '</table>';
Please login to merge, or discard this patch.
modules/Campaigns/WebToLeadFormBuilder.php 3 patches
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -420,7 +420,7 @@
 block discarded – undo
420 420
 
421 421
         $Web_To_Lead_Form_html .= self::getFormFinishHTML($webFormRequiredFieldsMsg);
422 422
 
423
-		return $Web_To_Lead_Form_html;
424
-	}
423
+        return $Web_To_Lead_Form_html;
424
+    }
425 425
 
426 426
 }
Please login to merge, or discard this patch.
Spacing   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
     // -- fields
120 120
 
121 121
     private static function getFieldLabelHTML($fieldLabel, $fieldRequired, $webRequiredSymbol) {
122
-        $html = '<label>' . $fieldLabel . ($fieldRequired ? "<span class='required'>$webRequiredSymbol</span>" : '') . '</label>';
122
+        $html = '<label>'.$fieldLabel.($fieldRequired ? "<span class='required'>$webRequiredSymbol</span>" : '').'</label>';
123 123
         return $html;
124 124
     }
125 125
 
@@ -137,11 +137,11 @@  discard block
 block discarded – undo
137 137
 
138 138
         $html .= self::getFieldLabelHTML($fieldLabel, $fieldRequired, $webRequiredSymbol);
139 139
 
140
-        if(isset($lead->field_defs[$colsField]['isMultiSelect']) && $lead->field_defs[$colsField]['isMultiSelect'] ==1){
140
+        if (isset($lead->field_defs[$colsField]['isMultiSelect']) && $lead->field_defs[$colsField]['isMultiSelect'] == 1) {
141 141
             $html .= self::getFieldEnumMultiSelectHTML($fieldName, $leadOptions, $fieldRequired);
142
-        }elseif(ifRadioButton($lead->field_defs[$colsField]['name'])){
142
+        }elseif (ifRadioButton($lead->field_defs[$colsField]['name'])) {
143 143
             $html .= self::getFieldEnumRadioGroupHTML($appListStringsFieldOptions, $lead, $fieldName, $colsField, $fieldRequired);
144
-        }else{
144
+        } else {
145 145
             $html .= self::getFieldEnumSelectHTML($fieldName, $leadOptions, $fieldRequired);
146 146
         }
147 147
         return $html;
@@ -156,17 +156,17 @@  discard block
 block discarded – undo
156 156
     private static function getFieldEnumRadioGroupHTML($appListStringsFieldOptions, $lead, $fieldName, $colsField, $fieldRequired) {
157 157
         $_required = $fieldRequired ? ' required' : '';
158 158
         $html = '';
159
-        foreach($appListStringsFieldOptions as $field_option_key => $field_option){
160
-            if($field_option != null){
161
-                if(!empty($lead->$fieldName) && in_array($field_option_key,unencodeMultienum($lead->$fieldName))) {
159
+        foreach ($appListStringsFieldOptions as $field_option_key => $field_option) {
160
+            if ($field_option != null) {
161
+                if (!empty($lead->$fieldName) && in_array($field_option_key, unencodeMultienum($lead->$fieldName))) {
162 162
                     $_checked = ' checked';
163 163
                 }
164 164
                 else {
165 165
                     $_checked = '';
166 166
                 }
167
-                $html .="<input id=\"{$colsField}_$field_option_key\" name=\"$colsField\" value=\"$field_option_key\" type=\"radio\"$_checked$_required>";
167
+                $html .= "<input id=\"{$colsField}_$field_option_key\" name=\"$colsField\" value=\"$field_option_key\" type=\"radio\"$_checked$_required>";
168 168
                 // todo ??? -->
169
-                $html .="<span ='document.getElementById('".$lead->field_defs[$colsField]."_$field_option_key').checked =true style='cursor:default'; onmousedown='return false;'>$field_option</span><br>";
169
+                $html .= "<span ='document.getElementById('".$lead->field_defs[$colsField]."_$field_option_key').checked =true style='cursor:default'; onmousedown='return false;'>$field_option</span><br>";
170 170
             }
171 171
         }
172 172
         return $html;
@@ -199,10 +199,10 @@  discard block
 block discarded – undo
199 199
     // char strings
200 200
 
201 201
     private static function getFieldCharsHTML($fieldName, $fieldLabel, $fieldRequired, $webRequiredSymbol) {
202
-        $isRequired = $fieldName=='last_name' || $fieldRequired;
202
+        $isRequired = $fieldName == 'last_name' || $fieldRequired;
203 203
         $_required = $isRequired ? ' required' : '';
204 204
         $html = self::getFieldLabelHTML($fieldLabel, $isRequired, $webRequiredSymbol);
205
-        $_type = $fieldName=='email1'||$fieldName=='email2' ? 'email' : 'text';
205
+        $_type = $fieldName == 'email1' || $fieldName == 'email2' ? 'email' : 'text';
206 206
         $html .= "<input id=\"$fieldName\" name=\"$fieldName\" type=\"$_type\"$_required>";
207 207
         return $html;
208 208
     }
@@ -239,64 +239,64 @@  discard block
 block discarded – undo
239 239
     private static function getFormTwoColumns($request, $formCols) {
240 240
         $colsFirst = isset($request[$formCols[0]]) ? $request[$formCols[0]] : null;
241 241
         $colsSecond = isset($request[$formCols[1]]) ? $request[$formCols[1]] : null;
242
-        if(!empty($colsFirst) && !empty($colsSecond)){
243
-            if(count($colsFirst) < count($colsSecond)){
244
-                $columns= count($colsSecond);
242
+        if (!empty($colsFirst) && !empty($colsSecond)) {
243
+            if (count($colsFirst) < count($colsSecond)) {
244
+                $columns = count($colsSecond);
245 245
             }
246
-            if(count($colsFirst) > count($colsSecond) || count($colsFirst) == count($colsSecond)){
247
-                $columns= count($colsFirst);
246
+            if (count($colsFirst) > count($colsSecond) || count($colsFirst) == count($colsSecond)) {
247
+                $columns = count($colsFirst);
248 248
             }
249 249
         }
250
-        else if(!empty($colsFirst)){
251
-            $columns= count($colsFirst);
250
+        else if (!empty($colsFirst)) {
251
+            $columns = count($colsFirst);
252 252
         }
253
-        else if(!empty($colsSecond)){
254
-            $columns= count($colsSecond);
253
+        else if (!empty($colsSecond)) {
254
+            $columns = count($colsSecond);
255 255
         }
256 256
         return $columns;
257 257
     }
258 258
 
259 259
     private static function getBooleanFields($boolFields) {
260
-        $boolean_fields='';
261
-        if($boolFields != null ){
262
-            foreach($boolFields as $boo){
263
-                $boolean_fields=$boolean_fields.$boo.';';
260
+        $boolean_fields = '';
261
+        if ($boolFields != null) {
262
+            foreach ($boolFields as $boo) {
263
+                $boolean_fields = $boolean_fields.$boo.';';
264 264
             }
265 265
         }
266 266
         return $boolean_fields;
267 267
     }
268 268
 
269 269
     private static function getArrayOfFieldInfo($lead, $colsField, &$requiredFields) {
270
-        $field_vname= preg_replace('/:$/','',translate($lead->field_defs[$colsField]['vname'], $lead->module_dir));
271
-        $field_name= $colsField;
272
-        $field_label = $field_vname .": ";
273
-        if(isset($lead->field_defs[$colsField]['custom_type']) && $lead->field_defs[$colsField]['custom_type'] != null){
274
-            $field_type= $lead->field_defs[$colsField]['custom_type'];
270
+        $field_vname = preg_replace('/:$/', '', translate($lead->field_defs[$colsField]['vname'], $lead->module_dir));
271
+        $field_name = $colsField;
272
+        $field_label = $field_vname.": ";
273
+        if (isset($lead->field_defs[$colsField]['custom_type']) && $lead->field_defs[$colsField]['custom_type'] != null) {
274
+            $field_type = $lead->field_defs[$colsField]['custom_type'];
275 275
         }
276
-        else{
277
-            $field_type= $lead->field_defs[$colsField]['type'];
276
+        else {
277
+            $field_type = $lead->field_defs[$colsField]['type'];
278 278
         }
279 279
 
280 280
         //bug: 47574 - make sure, that webtolead_email1 field has same required attribute as email1 field
281
-        if($colsField == 'webtolead_email1' && isset($lead->field_defs['email1']) && isset($lead->field_defs['email1']['required'])){
281
+        if ($colsField == 'webtolead_email1' && isset($lead->field_defs['email1']) && isset($lead->field_defs['email1']['required'])) {
282 282
             $lead->field_defs['webtolead_email1']['required'] = $lead->field_defs['email1']['required'];
283 283
         }
284 284
 
285 285
         $field_required = '';
286
-        if(isset($lead->field_defs[$colsField]['required']) && $lead->field_defs[$colsField]['required'] != null
287
-            && $lead->field_defs[$colsField]['required'] != 0){
286
+        if (isset($lead->field_defs[$colsField]['required']) && $lead->field_defs[$colsField]['required'] != null
287
+            && $lead->field_defs[$colsField]['required'] != 0) {
288 288
             $field_required = $lead->field_defs[$colsField]['required'];
289
-            if (! in_array($lead->field_defs[$colsField]['name'], $requiredFields)){
290
-                array_push($requiredFields,$lead->field_defs[$colsField]['name']);
289
+            if (!in_array($lead->field_defs[$colsField]['name'], $requiredFields)) {
290
+                array_push($requiredFields, $lead->field_defs[$colsField]['name']);
291 291
             }
292 292
         }
293
-        if($lead->field_defs[$colsField]['name']=='last_name'){
294
-            if (! in_array($lead->field_defs[$colsField]['name'], $requiredFields)){
295
-                array_push($requiredFields,$lead->field_defs[$colsField]['name']);
293
+        if ($lead->field_defs[$colsField]['name'] == 'last_name') {
294
+            if (!in_array($lead->field_defs[$colsField]['name'], $requiredFields)) {
295
+                array_push($requiredFields, $lead->field_defs[$colsField]['name']);
296 296
             }
297 297
         }
298 298
         $field_options = null;
299
-        if($field_type=='multienum' || $field_type=='enum' || $field_type=='radioenum')  $field_options= $lead->field_defs[$colsField]['options'];
299
+        if ($field_type == 'multienum' || $field_type == 'enum' || $field_type == 'radioenum')  $field_options = $lead->field_defs[$colsField]['options'];
300 300
         return array($field_name, $field_label, $field_type, $field_required, $field_options);
301 301
     }
302 302
 
@@ -334,14 +334,14 @@  discard block
 block discarded – undo
334 334
 
335 335
         $required_fields = array();
336 336
         $bool_fields = array();
337
-        for($i= 0; $i<$columns;$i++){
337
+        for ($i = 0; $i < $columns; $i++) {
338 338
 
339 339
             $colsFields = array();
340
-            foreach($formCols as $k => $formCol) {
340
+            foreach ($formCols as $k => $formCol) {
341 341
                 $colsFields[$k] = !empty($request[$formCol][$i]) ? $request[$formCol][$i] : null;
342 342
             }
343 343
 
344
-            if($colsFieldCount = count($formCols)) {
344
+            if ($colsFieldCount = count($formCols)) {
345 345
 
346 346
                 $colHtml = '';
347 347
                 $foundField = false;
@@ -396,7 +396,7 @@  discard block
 block discarded – undo
396 396
 
397 397
                 }
398 398
 
399
-                if($foundField) {
399
+                if ($foundField) {
400 400
                     $Web_To_Lead_Form_html .= self::getRowStartHTML();
401 401
                     $Web_To_Lead_Form_html .= $colHtml;
402 402
                     $Web_To_Lead_Form_html .= self:: getRowFinishHTML();
Please login to merge, or discard this patch.
Braces   +16 added lines, -25 removed lines patch added patch discarded remove patch
@@ -139,9 +139,9 @@  discard block
 block discarded – undo
139 139
 
140 140
         if(isset($lead->field_defs[$colsField]['isMultiSelect']) && $lead->field_defs[$colsField]['isMultiSelect'] ==1){
141 141
             $html .= self::getFieldEnumMultiSelectHTML($fieldName, $leadOptions, $fieldRequired);
142
-        }elseif(ifRadioButton($lead->field_defs[$colsField]['name'])){
142
+        } elseif(ifRadioButton($lead->field_defs[$colsField]['name'])){
143 143
             $html .= self::getFieldEnumRadioGroupHTML($appListStringsFieldOptions, $lead, $fieldName, $colsField, $fieldRequired);
144
-        }else{
144
+        } else{
145 145
             $html .= self::getFieldEnumSelectHTML($fieldName, $leadOptions, $fieldRequired);
146 146
         }
147 147
         return $html;
@@ -160,8 +160,7 @@  discard block
 block discarded – undo
160 160
             if($field_option != null){
161 161
                 if(!empty($lead->$fieldName) && in_array($field_option_key,unencodeMultienum($lead->$fieldName))) {
162 162
                     $_checked = ' checked';
163
-                }
164
-                else {
163
+                } else {
165 164
                     $_checked = '';
166 165
                 }
167 166
                 $html .="<input id=\"{$colsField}_$field_option_key\" name=\"$colsField\" value=\"$field_option_key\" type=\"radio\"$_checked$_required>";
@@ -246,11 +245,9 @@  discard block
 block discarded – undo
246 245
             if(count($colsFirst) > count($colsSecond) || count($colsFirst) == count($colsSecond)){
247 246
                 $columns= count($colsFirst);
248 247
             }
249
-        }
250
-        else if(!empty($colsFirst)){
248
+        } else if(!empty($colsFirst)){
251 249
             $columns= count($colsFirst);
252
-        }
253
-        else if(!empty($colsSecond)){
250
+        } else if(!empty($colsSecond)){
254 251
             $columns= count($colsSecond);
255 252
         }
256 253
         return $columns;
@@ -272,8 +269,7 @@  discard block
 block discarded – undo
272 269
         $field_label = $field_vname .": ";
273 270
         if(isset($lead->field_defs[$colsField]['custom_type']) && $lead->field_defs[$colsField]['custom_type'] != null){
274 271
             $field_type= $lead->field_defs[$colsField]['custom_type'];
275
-        }
276
-        else{
272
+        } else{
277 273
             $field_type= $lead->field_defs[$colsField]['type'];
278 274
         }
279 275
 
@@ -296,7 +292,9 @@  discard block
 block discarded – undo
296 292
             }
297 293
         }
298 294
         $field_options = null;
299
-        if($field_type=='multienum' || $field_type=='enum' || $field_type=='radioenum')  $field_options= $lead->field_defs[$colsField]['options'];
295
+        if($field_type=='multienum' || $field_type=='enum' || $field_type=='radioenum') {
296
+            $field_options= $lead->field_defs[$colsField]['options'];
297
+        }
300 298
         return array($field_name, $field_label, $field_type, $field_required, $field_options);
301 299
     }
302 300
 
@@ -356,35 +354,28 @@  discard block
 block discarded – undo
356 354
                         if ($field_type == 'multienum' || $field_type == 'enum' || $field_type == 'radioenum') {
357 355
                             $colHtml .= self::getFieldEnumHTML($lead, $field_name, $appListStrings[$field_options], $field_required, $field_label, $webRequiredSymbol, $colsFields[$j]);
358 356
                             $foundField = true;
359
-                        }
360
-                        elseif ($field_type == 'bool') {
357
+                        } elseif ($field_type == 'bool') {
361 358
                             $colHtml .= self::getFieldBoolHTML($field_name, $field_required, $field_label, $webRequiredSymbol);
362 359
                             $foundField = true;
363 360
                             if (!in_array($lead->field_defs[$colsFields[$j]]['name'], $bool_fields)) {
364 361
                                 array_push($bool_fields, $lead->field_defs[$colsFields[$j]]['name']);
365 362
                             }
366
-                        }
367
-                        elseif ($field_type == 'date') {
363
+                        } elseif ($field_type == 'date') {
368 364
                             $colHtml .= self::getFieldDateHTML($field_name, $field_required, $field_label, $webRequiredSymbol);
369 365
                             $foundField = true;
370
-                        }
371
-                        elseif ($field_type == 'varchar' || $field_type == 'name' || $field_type == 'phone' || $field_type == 'currency' || $field_type == 'url' || $field_type == 'int') {
366
+                        } elseif ($field_type == 'varchar' || $field_type == 'name' || $field_type == 'phone' || $field_type == 'currency' || $field_type == 'url' || $field_type == 'int') {
372 367
                             $colHtml .= self::getFieldCharsHTML($field_name, $field_label, $field_required, $webRequiredSymbol);
373 368
                             $foundField = true;
374
-                        }
375
-                        elseif ($field_type == 'text') {
369
+                        } elseif ($field_type == 'text') {
376 370
                             $colHtml .= self::getFieldTextHTML($field_name, $field_label, $field_required && false, $webRequiredSymbol);
377 371
                             $foundField = true;
378
-                        }
379
-                        elseif ($field_type == 'relate' && $field_name == 'account_name') {
372
+                        } elseif ($field_type == 'relate' && $field_name == 'account_name') {
380 373
                             $colHtml .= self::getFieldRelateHTML($field_name, $field_label, $field_required && false, $webRequiredSymbol);
381 374
                             $foundField = true;
382
-                        }
383
-                        elseif ($field_type == 'email') {
375
+                        } elseif ($field_type == 'email') {
384 376
                             $colHtml .= self::getFieldEmailHTML();
385 377
                             $foundField = true;
386
-                        }
387
-                        else {
378
+                        } else {
388 379
                             $colHtml .= self::getFieldEmptyHTML();
389 380
                         }
390 381
 
Please login to merge, or discard this patch.
modules/Campaigns/WebToLeadFormSave.php 3 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -62,27 +62,27 @@
 block discarded – undo
62 62
 
63 63
 while (strpos($bodyHTML, "ta_replace") !== false){
64 64
 
65
-	//define the marker edges of the sub string to process (opening and closing tag brackets)
66
-	$marker = strpos($bodyHTML, "ta_replace");
67
-	$start_border = strpos($bodyHTML, "input", $marker) - 1;// to account for opening '<' char;
68
-	$end_border = strpos($bodyHTML, '>', $start_border); //get the closing tag after marker ">";
65
+    //define the marker edges of the sub string to process (opening and closing tag brackets)
66
+    $marker = strpos($bodyHTML, "ta_replace");
67
+    $start_border = strpos($bodyHTML, "input", $marker) - 1;// to account for opening '<' char;
68
+    $end_border = strpos($bodyHTML, '>', $start_border); //get the closing tag after marker ">";
69 69
 
70
-	//extract the input tag string
71
-	$working_str = substr($bodyHTML, $marker-3, $end_border-($marker-3) );
70
+    //extract the input tag string
71
+    $working_str = substr($bodyHTML, $marker-3, $end_border-($marker-3) );
72 72
 
73
-	//replace input markup with text areas markups
74
-	$new_str = str_replace('input','textarea',$working_str);
75
-	$new_str = str_replace("type=\"text\"", ' ', $new_str);
76
-	$new_str = $new_str . '> </textarea';
73
+    //replace input markup with text areas markups
74
+    $new_str = str_replace('input','textarea',$working_str);
75
+    $new_str = str_replace("type=\"text\"", ' ', $new_str);
76
+    $new_str = $new_str . '> </textarea';
77 77
 
78
-	//replace the marker with generic term
79
-	$new_str = str_replace('ta_replace', 'sugarslot', $new_str);
78
+    //replace the marker with generic term
79
+    $new_str = str_replace('ta_replace', 'sugarslot', $new_str);
80 80
 
81
-	// NET-enabling start-tag requires SHORTTAG YES
82
-	$new_str = str_replace('/> </textarea>', '> </textarea>', $new_str);
81
+    // NET-enabling start-tag requires SHORTTAG YES
82
+    $new_str = str_replace('/> </textarea>', '> </textarea>', $new_str);
83 83
 
84
-	//merge the processed string back into bodyhtml string
85
-	$bodyHTML = str_replace($working_str , $new_str, $bodyHTML);
84
+    //merge the processed string back into bodyhtml string
85
+    $bodyHTML = str_replace($working_str , $new_str, $bodyHTML);
86 86
 }
87 87
 //<<<----------end replacing marked text inputs with text area tags
88 88
 
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 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.
@@ -56,24 +56,24 @@  discard block
 block discarded – undo
56 56
 
57 57
 //-----------begin replacing text input tags that have been marked with text area tags
58 58
 //get array of text areas strings to process
59
-$bodyHTML = html_entity_decode($_REQUEST['body_html'],ENT_QUOTES);
59
+$bodyHTML = html_entity_decode($_REQUEST['body_html'], ENT_QUOTES);
60 60
 //Bug53791
61 61
 $bodyHTML = str_replace(chr(160), " ", $bodyHTML);
62 62
 
63
-while (strpos($bodyHTML, "ta_replace") !== false){
63
+while (strpos($bodyHTML, "ta_replace") !== false) {
64 64
 
65 65
 	//define the marker edges of the sub string to process (opening and closing tag brackets)
66 66
 	$marker = strpos($bodyHTML, "ta_replace");
67
-	$start_border = strpos($bodyHTML, "input", $marker) - 1;// to account for opening '<' char;
67
+	$start_border = strpos($bodyHTML, "input", $marker) - 1; // to account for opening '<' char;
68 68
 	$end_border = strpos($bodyHTML, '>', $start_border); //get the closing tag after marker ">";
69 69
 
70 70
 	//extract the input tag string
71
-	$working_str = substr($bodyHTML, $marker-3, $end_border-($marker-3) );
71
+	$working_str = substr($bodyHTML, $marker - 3, $end_border - ($marker - 3));
72 72
 
73 73
 	//replace input markup with text areas markups
74
-	$new_str = str_replace('input','textarea',$working_str);
74
+	$new_str = str_replace('input', 'textarea', $working_str);
75 75
 	$new_str = str_replace("type=\"text\"", ' ', $new_str);
76
-	$new_str = $new_str . '> </textarea';
76
+	$new_str = $new_str.'> </textarea';
77 77
 
78 78
 	//replace the marker with generic term
79 79
 	$new_str = str_replace('ta_replace', 'sugarslot', $new_str);
@@ -82,29 +82,29 @@  discard block
 block discarded – undo
82 82
 	$new_str = str_replace('/> </textarea>', '> </textarea>', $new_str);
83 83
 
84 84
 	//merge the processed string back into bodyhtml string
85
-	$bodyHTML = str_replace($working_str , $new_str, $bodyHTML);
85
+	$bodyHTML = str_replace($working_str, $new_str, $bodyHTML);
86 86
 }
87 87
 //<<<----------end replacing marked text inputs with text area tags
88 88
 
89 89
 $guid = create_guid();
90 90
 $form_file = "upload://$guid";
91 91
 
92
-$SugarTiny =  new SugarTinyMCE();
92
+$SugarTiny = new SugarTinyMCE();
93 93
 $html = $SugarTiny->cleanEncodedMCEHtml($bodyHTML);
94 94
 
95 95
 //Check to ensure we have <html> tags in the form. Without them, IE8 will attempt to display the page as XML.
96 96
 if (stripos($html, "<html") === false) {
97 97
     $langHeader = get_language_header();
98
-    $html = "<html {$langHeader}><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><body>" . $html . "</body></html>";
98
+    $html = "<html {$langHeader}><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><body>".$html."</body></html>";
99 99
 }
100 100
 file_put_contents($form_file, $html);
101 101
 
102
-$xtpl=new XTemplate ('modules/Campaigns/WebToLeadDownloadForm.html');
102
+$xtpl = new XTemplate('modules/Campaigns/WebToLeadDownloadForm.html');
103 103
 $xtpl->assign("MOD", $mod_strings);
104 104
 $xtpl->assign("APP", $app_strings);
105 105
 $webformlink = "<b>$mod_strings[LBL_DOWNLOAD_TEXT_WEB_TO_LEAD_FORM]</b><br/>";
106 106
 $webformlink .= "<a href=\"index.php?entryPoint=download&id={$guid}&isTempFile=1&tempName=WebToLeadForm.html&type=temp\">$mod_strings[LBL_DOWNLOAD_WEB_TO_LEAD_FORM]</a>";
107
-$xtpl->assign("LINK_TO_WEB_FORM",$webformlink);
107
+$xtpl->assign("LINK_TO_WEB_FORM", $webformlink);
108 108
 $xtpl->assign("RAW_SOURCE", htmlspecialchars($html, ENT_QUOTES, 'iso8859-1'));
109 109
 $xtpl->parse("main.copy_source");
110 110
 $xtpl->parse("main");
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.
Dashlets/OutboundEmailAccountsDashlet/OutboundEmailAccountsDashlet.meta.php 3 patches
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -49,7 +49,7 @@
 block discarded – undo
49 49
 global $app_strings;
50 50
 
51 51
 $dashletMeta['OutboundEmailAccountsDashlet'] = array('module'		=> 'OutboundEmailAccounts',
52
-										  'title'       => translate('LBL_HOMEPAGE_TITLE', 'OutboundEmailAccounts'),
53
-                                          'description' => 'A customizable view into OutboundEmailAccounts',
54
-                                          'icon'        => 'icon_OutboundEmailAccounts_32.gif',
55
-                                          'category'    => 'Module Views');
56 52
\ No newline at end of file
53
+                                            'title'       => translate('LBL_HOMEPAGE_TITLE', 'OutboundEmailAccounts'),
54
+                                            'description' => 'A customizable view into OutboundEmailAccounts',
55
+                                            'icon'        => 'icon_OutboundEmailAccounts_32.gif',
56
+                                            'category'    => 'Module Views');
57 57
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@
 block discarded – undo
1 1
 <?php
2
-if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 3
 /*********************************************************************************
4 4
  * SugarCRM Community Edition is a customer relationship management program developed by
5 5
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,5 +1,7 @@
 block discarded – undo
1 1
 <?php
2
-if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2
+if(!defined('sugarEntry') || !sugarEntry) {
3
+    die('Not A Valid Entry Point');
4
+}
3 5
 /*********************************************************************************
4 6
  * SugarCRM Community Edition is a customer relationship management program developed by
5 7
  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
Please login to merge, or discard this patch.