]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/database/MssqlManager.php
Release 6.5.10
[Github/sugarcrm.git] / include / database / MssqlManager.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40 * Description: This file handles the Data base functionality for the application.
41 * It acts as the DB abstraction layer for the application. It depends on helper classes
42 * which generate the necessary SQL. This sql is then passed to PEAR DB classes.
43 * The helper class is chosen in DBManagerFactory, which is driven by 'db_type' in 'dbconfig' under config.php.
44 *
45 * All the functions in this class will work with any bean which implements the meta interface.
46 * The passed bean is passed to helper class which uses these functions to generate correct sql.
47 *
48 * The meta interface has the following functions:
49 * getTableName()                        Returns table name of the object.
50 * getFieldDefinitions()         Returns a collection of field definitions in order.
51 * getFieldDefintion(name)               Return field definition for the field.
52 * getFieldValue(name)           Returns the value of the field identified by name.
53 *                               If the field is not set, the function will return boolean FALSE.
54 * getPrimaryFieldDefinition()   Returns the field definition for primary key
55 *
56 * The field definition is an array with the following keys:
57 *
58 * name          This represents name of the field. This is a required field.
59 * type          This represents type of the field. This is a required field and valid values are:
60 *               int
61 *               long
62 *               varchar
63 *               text
64 *               date
65 *               datetime
66 *               double
67 *               float
68 *               uint
69 *               ulong
70 *               time
71 *               short
72 *               enum
73 * length        This is used only when the type is varchar and denotes the length of the string.
74 *                       The max value is 255.
75 * enumvals  This is a list of valid values for an enum separated by "|".
76 *                       It is used only if the type is ?enum?;
77 * required      This field dictates whether it is a required value.
78 *                       The default value is ?FALSE?.
79 * isPrimary     This field identifies the primary key of the table.
80 *                       If none of the fields have this flag set to ?TRUE?,
81 *                       the first field definition is assume to be the primary key.
82 *                       Default value for this field is ?FALSE?.
83 * default       This field sets the default value for the field definition.
84 *
85 *
86 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
87 * All Rights Reserved.
88 * Contributor(s): ______________________________________..
89 ********************************************************************************/
90
91 /**
92  * SQL Server (mssql) manager
93  */
94 class MssqlManager extends DBManager
95 {
96     /**
97      * @see DBManager::$dbType
98      */
99     public $dbType = 'mssql';
100     public $dbName = 'MsSQL';
101     public $variant = 'mssql';
102     public $label = 'LBL_MSSQL';
103
104     protected $capabilities = array(
105         "affected_rows" => true,
106         "select_rows" => true,
107         'fulltext' => true,
108         'limit_subquery' => true,
109         "fix:expandDatabase" => true, // Support expandDatabase fix
110         "create_user" => true,
111         "create_db" => true,
112     );
113
114     /**
115      * Maximum length of identifiers
116      */
117     protected $maxNameLengths = array(
118         'table' => 128,
119         'column' => 128,
120         'index' => 128,
121         'alias' => 128
122     );
123
124     protected $type_map = array(
125             'int'      => 'int',
126             'double'   => 'float',
127             'float'    => 'float',
128             'uint'     => 'int',
129             'ulong'    => 'int',
130             'long'     => 'bigint',
131             'short'    => 'smallint',
132             'varchar'  => 'varchar',
133             'text'     => 'text',
134             'longtext' => 'text',
135             'date'     => 'datetime',
136             'enum'     => 'varchar',
137             'relate'   => 'varchar',
138             'multienum'=> 'text',
139             'html'     => 'text',
140                         'longhtml' => 'text',
141                 'datetime' => 'datetime',
142             'datetimecombo' => 'datetime',
143             'time'     => 'datetime',
144             'bool'     => 'bit',
145             'tinyint'  => 'tinyint',
146             'char'     => 'char',
147             'blob'     => 'image',
148             'longblob' => 'image',
149             'currency' => 'decimal(26,6)',
150             'decimal'  => 'decimal',
151             'decimal2' => 'decimal',
152             'id'       => 'varchar(36)',
153             'url'      => 'varchar',
154             'encrypt'  => 'varchar',
155             'file'     => 'varchar',
156                 'decimal_tpl' => 'decimal(%d, %d)',
157             );
158
159     protected $connectOptions = null;
160
161     /**
162      * @see DBManager::connect()
163      */
164     public function connect(array $configOptions = null, $dieOnError = false)
165     {
166         global $sugar_config;
167
168         if (is_null($configOptions))
169             $configOptions = $sugar_config['dbconfig'];
170
171         //SET DATEFORMAT to 'YYYY-MM-DD''
172         ini_set('mssql.datetimeconvert', '0');
173
174         //set the text size and textlimit to max number so that blob columns are not truncated
175         ini_set('mssql.textlimit','2147483647');
176         ini_set('mssql.textsize','2147483647');
177         ini_set('mssql.charset','UTF-8');
178
179         if(!empty($configOptions['db_host_instance'])) {
180             $configOptions['db_host_instance'] = trim($configOptions['db_host_instance']);
181         }
182         //set the connections parameters
183         if (empty($configOptions['db_host_instance'])) {
184             $connect_param = $configOptions['db_host_name'];
185         } else {
186             $connect_param = $configOptions['db_host_name']."\\".$configOptions['db_host_instance'];
187         }
188
189         //create persistent connection
190         if ($this->getOption('persistent')) {
191             $this->database =@mssql_pconnect(
192                 $connect_param ,
193                 $configOptions['db_user_name'],
194                 $configOptions['db_password']
195                 );
196         }
197         //if no persistent connection created, then create regular connection
198         if(!$this->database){
199             $this->database = mssql_connect(
200                     $connect_param ,
201                     $configOptions['db_user_name'],
202                     $configOptions['db_password']
203                     );
204             if(!$this->database){
205                 $GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name'].
206                     " as ".$configOptions['db_user_name'].".");
207                 if($dieOnError) {
208                     sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
209                 } else {
210                     return false;
211                 }
212             }
213             if($this->database && $this->getOption('persistent')){
214                 $_SESSION['administrator_error'] = "<B>Severe Performance Degradation: Persistent Database Connections "
215                     . "not working.  Please set \$sugar_config['dbconfigoption']['persistent'] to false in your "
216                     . "config.php file</B>";
217             }
218         }
219         //make sure connection exists
220         if(!$this->database) {
221                 if($dieOnError) {
222                     sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
223                 } else {
224                     return false;
225                 }
226         }
227
228         //select database
229
230         //Adding sleep and retry for mssql connection. We have come across scenarios when
231         //an error is thrown.' Unable to select database'. Following will try to connect to
232         //mssql db maximum number of 5 times at the interval of .2 second. If can not connect
233         //it will throw an Unable to select database message.
234
235         if(!empty($configOptions['db_name']) && !@mssql_select_db($configOptions['db_name'], $this->database)){
236                         $connected = false;
237                         for($i=0;$i<5;$i++){
238                                 usleep(200000);
239                                 if(@mssql_select_db($configOptions['db_name'], $this->database)){
240                                         $connected = true;
241                                         break;
242                                 }
243                         }
244                         if(!$connected){
245                             $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}");
246                 if($dieOnError) {
247                     if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
248                         sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
249                     } else {
250                         sugar_die("Could not connect to the database. Please refer to sugarcrm.log for details.");
251                     }
252                 } else {
253                     return false;
254                 }
255                         }
256          }
257
258         if(!$this->checkError('Could Not Connect', $dieOnError))
259             $GLOBALS['log']->info("connected to db");
260
261         $this->connectOptions = $configOptions;
262
263         $GLOBALS['log']->info("Connect:".$this->database);
264         return true;
265     }
266
267         /**
268      * @see DBManager::version()
269      */
270     public function version()
271     {
272         return $this->getOne("SELECT @@VERSION as version");
273         }
274
275         /**
276      * @see DBManager::query()
277          */
278         public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
279     {
280         if(is_array($sql)) {
281             return $this->queryArray($sql, $dieOnError, $msg, $suppress);
282         }
283         // Flag if there are odd number of single quotes
284         if ((substr_count($sql, "'") & 1))
285             $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
286
287                 $sql = $this->_appendN($sql);
288
289         $GLOBALS['log']->info('Query:' . $sql);
290         $this->checkConnection();
291         $this->countQuery($sql);
292         $this->query_time = microtime(true);
293
294         // Bug 34892 - Clear out previous error message by checking the @@ERROR global variable
295                 @mssql_query("SELECT @@ERROR", $this->database);
296
297         $result = $suppress?@mssql_query($sql, $this->database):mssql_query($sql, $this->database);
298
299         if (!$result) {
300             // awu Bug 10657: ignoring mssql error message 'Changed database context to' - an intermittent
301             //                            and difficult to reproduce error. The message is only a warning, and does
302             //                            not affect the functionality of the query
303             $sqlmsg = mssql_get_last_message();
304             $sqlpos = strpos($sqlmsg, 'Changed database context to');
305                         $sqlpos2 = strpos($sqlmsg, 'Warning:');
306                         $sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
307
308                         if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false)              // if sqlmsg has 'Changed database context to', just log it
309                                 $GLOBALS['log']->debug($sqlmsg . ": " . $sql );
310                         else {
311                                 $GLOBALS['log']->fatal($sqlmsg . ": " . $sql );
312                                 if($dieOnError)
313                                         sugar_die('SQL Error : ' . $sqlmsg);
314                                 else
315                                         echo 'SQL Error : ' . $sqlmsg;
316                         }
317         }
318
319         $this->query_time = microtime(true) - $this->query_time;
320         $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
321
322
323         $this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
324
325         return $result;
326     }
327
328     /**
329      * This function take in the sql for a union query, the start and offset,
330      * and wraps it around an "mssql friendly" limit query
331      *
332      * @param  string $sql
333      * @param  int    $start record to start at
334      * @param  int    $count number of records to retrieve
335      * @return string SQL statement
336      */
337     private function handleUnionLimitQuery($sql, $start, $count)
338     {
339         //set the start to 0, no negs
340         if ($start < 0)
341             $start=0;
342
343         $GLOBALS['log']->debug(print_r(func_get_args(),true));
344
345         $this->lastsql = $sql;
346
347         //change the casing to lower for easier string comparison, and trim whitespaces
348         $sql = strtolower(trim($sql)) ;
349
350         //set default sql
351         $limitUnionSQL = $sql;
352         $order_by_str = 'order by';
353
354         //make array of order by's.  substring approach was proving too inconsistent
355         $orderByArray = explode($order_by_str, $sql);
356         $unionOrderBy = '';
357         $rowNumOrderBy = '';
358
359         //count the number of array elements
360         $unionOrderByCount = count($orderByArray);
361         $arr_count = 0;
362
363         //process if there are elements
364         if ($unionOrderByCount){
365             //we really want the last order by, so reconstruct string
366             //adding a 1 to count, as we dont wish to process the last element
367             $unionsql = '';
368             while ($unionOrderByCount>$arr_count+1) {
369                 $unionsql .= $orderByArray[$arr_count];
370                 $arr_count = $arr_count+1;
371                 //add an "order by" string back if we are coming into loop again
372                 //remember they were taken out when array was created
373                 if ($unionOrderByCount>$arr_count+1) {
374                     $unionsql .= "order by";
375                 }
376             }
377             //grab the last order by element, set both order by's'
378             $unionOrderBy = $orderByArray[$arr_count];
379             $rowNumOrderBy = $unionOrderBy;
380
381             //if last element contains a "select", then this is part of the union query,
382             //and there is no order by to use
383             if (strpos($unionOrderBy, "select")) {
384                 $unionsql = $sql;
385                 //with no guidance on what to use for required order by in rownumber function,
386                 //resort to using name column.
387                 $rowNumOrderBy = 'id';
388                 $unionOrderBy = "";
389             }
390         }
391         else {
392             //there are no order by elements, so just pass back string
393             $unionsql = $sql;
394             //with no guidance on what to use for required order by in rownumber function,
395             //resort to using name column.
396             $rowNumOrderBy = 'id';
397             $unionOrderBy = '';
398         }
399         //Unions need the column name being sorted on to match across all queries in Union statement
400         //so we do not want to strip the alias like in other queries.  Just add the "order by" string and
401         //pass column name as is
402         if ($unionOrderBy != '') {
403             $unionOrderBy = ' order by ' . $unionOrderBy;
404         }
405
406         //Bug 56560, use top query in conjunction with rownumber() function
407         //to create limit query when paging is needed. Otherwise,
408         //it shows duplicates when paging on activities subpanel.
409         //If not for paging, no need to use rownumber() function
410         if ($count == 1)
411         {
412             $limitUnionSQL = "SELECT TOP $count * FROM (" .$unionsql .") as top_count ".$unionOrderBy;
413         }
414         else
415         {
416             $limitUnionSQL = "SELECT TOP $count * FROM( select ROW_NUMBER() OVER ( order by "
417             .$rowNumOrderBy.") AS row_number, * FROM ("
418             .$unionsql .") As numbered) "
419             . "As top_count_limit WHERE row_number > $start "
420             .$unionOrderBy;
421         }
422
423         return $limitUnionSQL;
424     }
425
426         /**
427          * FIXME: verify and thoroughly test this code, these regexps look fishy
428      * @see DBManager::limitQuery()
429      */
430     public function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true)
431     {
432         $start = (int)$start;
433         $count = (int)$count;
434         $newSQL = $sql;
435         $distinctSQLARRAY = array();
436         if (strpos($sql, "UNION") && !preg_match("/(')(UNION).?(')/i", $sql))
437             $newSQL = $this->handleUnionLimitQuery($sql,$start,$count);
438         else {
439             if ($start < 0)
440                 $start = 0;
441             $GLOBALS['log']->debug(print_r(func_get_args(),true));
442             $this->lastsql = $sql;
443             $matches = array();
444             preg_match('/^(.*SELECT )(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
445             if (!empty($matches[3])) {
446                 if ($start == 0) {
447                     $match_two = strtolower($matches[2]);
448                     if (!strpos($match_two, "distinct")> 0 && strpos($match_two, "distinct") !==0) {
449                         $orderByMatch = array();
450                         preg_match('/^(.*)(ORDER BY)(.*)$/is',$matches[3], $orderByMatch);
451                         if (!empty($orderByMatch[3])) {
452                             $selectPart = array();
453                             preg_match('/^(.*)(\bFROM .*)$/isU', $matches[2], $selectPart);
454                             $newSQL = "SELECT TOP $count * FROM
455                                 (
456                                     " . $matches[1] . $selectPart[1] . ", ROW_NUMBER()
457                                     OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]) . ") AS row_number
458                                     " . $selectPart[2] . $orderByMatch[1]. "
459                                 ) AS a
460                                 WHERE row_number > $start";
461                         }
462                         else {
463                             $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
464                         }
465                     }
466                     else {
467                         $distinct_o = strpos($match_two, "distinct");
468                         $up_to_distinct_str = substr($match_two, 0, $distinct_o);
469                         //check to see if the distinct is within a function, if so, then proceed as normal
470                         if (strpos($up_to_distinct_str,"(")) {
471                             //proceed as normal
472                             $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
473                         }
474                         else {
475                             //if distinct is not within a function, then parse
476                             //string contains distinct clause, "TOP needs to come after Distinct"
477                             //get position of distinct
478                             $match_zero = strtolower($matches[0]);
479                             $distinct_pos = strpos($match_zero , "distinct");
480                             //get position of where
481                             $where_pos = strpos($match_zero, "where");
482                             //parse through string
483                             $beg = substr($matches[0], 0, $distinct_pos+9 );
484                             $mid = substr($matches[0], strlen($beg), ($where_pos+5) - (strlen($beg)));
485                             $end = substr($matches[0], strlen($beg) + strlen($mid) );
486                             //repopulate matches array
487                             $matches[1] = $beg; $matches[2] = $mid; $matches[3] = $end;
488
489                             $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
490                         }
491                     }
492                 } else {
493                     $orderByMatch = array();
494                     preg_match('/^(.*)(ORDER BY)(.*)$/is',$matches[3], $orderByMatch);
495
496                     //if there is a distinct clause, parse sql string as we will have to insert the rownumber
497                     //for paging, AFTER the distinct clause
498                     $grpByStr = '';
499                     $hasDistinct = strpos(strtolower($matches[0]), "distinct");
500                     if ($hasDistinct) {
501                         $matches_sql = strtolower($matches[0]);
502                         //remove reference to distinct and select keywords, as we will use a group by instead
503                         //we need to use group by because we are introducing rownumber column which would make every row unique
504
505                         //take out the select and distinct from string so we can reuse in group by
506                         $dist_str = ' distinct ';
507                         $distinct_pos = strpos($matches_sql, $dist_str);
508                         $matches_sql = substr($matches_sql,$distinct_pos+ strlen($dist_str));
509                         //get the position of where and from for further processing
510                         $from_pos = strpos($matches_sql , " from ");
511                         $where_pos = strpos($matches_sql, "where");
512                         //split the sql into a string before and after the from clause
513                         //we will use the columns being selected to construct the group by clause
514                         if ($from_pos>0 ) {
515                             $distinctSQLARRAY[0] = substr($matches_sql,0, $from_pos+1);
516                             $distinctSQLARRAY[1] = substr($matches_sql,$from_pos+1);
517                             //get position of order by (if it exists) so we can strip it from the string
518                             $ob_pos = strpos($distinctSQLARRAY[1], "order by");
519                             if ($ob_pos) {
520                                 $distinctSQLARRAY[1] = substr($distinctSQLARRAY[1],0,$ob_pos);
521                             }
522
523                             // strip off last closing parentheses from the where clause
524                             $distinctSQLARRAY[1] = preg_replace('/\)\s$/',' ',$distinctSQLARRAY[1]);
525                         }
526
527                         //place group by string into array
528                         $grpByArr = explode(',', $distinctSQLARRAY[0]);
529                         $first = true;
530                         //remove the aliases for each group by element, sql server doesnt like these in group by.
531                         foreach ($grpByArr as $gb) {
532                             $gb = trim($gb);
533
534                             //clean out the extra stuff added if we are concatenating first_name and last_name together
535                             //this way both fields are added in correctly to the group by
536                             $gb = str_replace("isnull(","",$gb);
537                             $gb = str_replace("'') + ' ' + ","",$gb);
538
539                             //remove outer reference if they exist
540                             if (strpos($gb,"'")!==false){
541                                 continue;
542                             }
543                             //if there is a space, then an alias exists, remove alias
544                             if (strpos($gb,' ')){
545                                 $gb = substr( $gb, 0,strpos($gb,' '));
546                             }
547
548                             //if resulting string is not empty then add to new group by string
549                             if (!empty($gb)) {
550                                 if ($first) {
551                                     $grpByStr .= " $gb";
552                                     $first = false;
553                                 } else {
554                                     $grpByStr .= ", $gb";
555                                 }
556                             }
557                         }
558                     }
559
560                     if (!empty($orderByMatch[3])) {
561                         //if there is a distinct clause, form query with rownumber after distinct
562                         if ($hasDistinct) {
563                             $newSQL = "SELECT TOP $count * FROM
564                                         (
565                                             SELECT ROW_NUMBER()
566                                                 OVER (ORDER BY ".$this->returnOrderBy($sql, $orderByMatch[3]).") AS row_number,
567                                                 count(*) counter, " . $distinctSQLARRAY[0] . "
568                                                 " . $distinctSQLARRAY[1] . "
569                                                 group by " . $grpByStr . "
570                                         ) AS a
571                                         WHERE row_number > $start";
572                         }
573                         else {
574                         $newSQL = "SELECT TOP $count * FROM
575                                     (
576                                         " . $matches[1] . " ROW_NUMBER()
577                                         OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]) . ") AS row_number,
578                                         " . $matches[2] . $orderByMatch[1]. "
579                                     ) AS a
580                                     WHERE row_number > $start";
581                         }
582                     }else{
583                         //bug: 22231 Records in campaigns' subpanel may not come from
584                         //table of $_REQUEST['module']. Get it directly from query
585                         $upperQuery = strtoupper($matches[2]);
586                         if (!strpos($upperQuery,"JOIN")){
587                             $from_pos = strpos($upperQuery , "FROM") + 4;
588                             $where_pos = strpos($upperQuery, "WHERE");
589                             $tablename = trim(substr($upperQuery,$from_pos, $where_pos - $from_pos));
590                         }else{
591                             // FIXME: this looks really bad. Probably source for tons of bug
592                             // needs to be removed
593                             $tablename = $this->getTableNameFromModuleName($_REQUEST['module'],$sql);
594                         }
595                         //if there is a distinct clause, form query with rownumber after distinct
596                         if ($hasDistinct) {
597                              $newSQL = "SELECT TOP $count * FROM
598                                             (
599                             SELECT ROW_NUMBER() OVER (ORDER BY ".$tablename.".id) AS row_number, count(*) counter, " . $distinctSQLARRAY[0] . "
600                                                         " . $distinctSQLARRAY[1] . "
601                                                     group by " . $grpByStr . "
602                                             )
603                                             AS a
604                                             WHERE row_number > $start";
605                         }
606                         else {
607                              $newSQL = "SELECT TOP $count * FROM
608                                            (
609                                   " . $matches[1] . " ROW_NUMBER() OVER (ORDER BY ".$tablename.".id) AS row_number, " . $matches[2] . $matches[3]. "
610                                            )
611                                            AS a
612                                            WHERE row_number > $start";
613                         }
614                     }
615                 }
616             }
617         }
618
619         $GLOBALS['log']->debug('Limit Query: ' . $newSQL);
620         if($execute) {
621             $result =  $this->query($newSQL, $dieOnError, $msg);
622             $this->dump_slow_queries($newSQL);
623             return $result;
624         } else {
625             return $newSQL;
626         }
627     }
628
629
630     /**
631      * Searches for begginning and ending characters.  It places contents into
632      * an array and replaces contents in original string.  This is used to account for use of
633      * nested functions while aliasing column names
634      *
635      * @param  string $p_sql     SQL statement
636      * @param  string $strip_beg Beginning character
637      * @param  string $strip_end Ending character
638      * @param  string $patt      Optional, pattern to
639      */
640     private function removePatternFromSQL($p_sql, $strip_beg, $strip_end, $patt = 'patt')
641     {
642         //strip all single quotes out
643         $count = substr_count ( $p_sql, $strip_beg);
644         $increment = 1;
645         if ($strip_beg != $strip_end)
646             $increment = 2;
647
648         $i=0;
649         $offset = 0;
650         $strip_array = array();
651         while ($i<$count && $offset<strlen($p_sql)) {
652             if ($offset > strlen($p_sql))
653             {
654                                 break;
655             }
656
657             $beg_sin = strpos($p_sql, $strip_beg, $offset);
658             if (!$beg_sin)
659             {
660                 break;
661             }
662             $sec_sin = strpos($p_sql, $strip_end, $beg_sin+1);
663             $strip_array[$patt.$i] = substr($p_sql, $beg_sin, $sec_sin - $beg_sin +1);
664             if ($increment > 1) {
665                 //we are in here because beginning and end patterns are not identical, so search for nesting
666                 $exists = strpos($strip_array[$patt.$i], $strip_beg );
667                 if ($exists>=0) {
668                     $nested_pos = (strrpos($strip_array[$patt.$i], $strip_beg ));
669                     $strip_array[$patt.$i] = substr($p_sql,$nested_pos+$beg_sin,$sec_sin - ($nested_pos+$beg_sin)+1);
670                     $p_sql = substr($p_sql, 0, $nested_pos+$beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
671                     $i = $i + 1;
672                     continue;
673                 }
674             }
675             $p_sql = substr($p_sql, 0, $beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
676             //move the marker up
677             $offset = $sec_sin+1;
678
679             $i = $i + 1;
680         }
681         $strip_array['sql_string'] = $p_sql;
682
683         return $strip_array;
684     }
685
686     /**
687      * adds a pattern
688      *
689      * @param  string $token
690      * @param  array  $pattern_array
691      * @return string
692      */
693         private function addPatternToSQL($token, array $pattern_array)
694     {
695         //strip all single quotes out
696         $pattern_array = array_reverse($pattern_array);
697
698         foreach ($pattern_array as $key => $replace) {
699             $token = str_replace( "##".$key."##", $replace,$token);
700         }
701
702         return $token;
703     }
704
705     /**
706      * gets an alias from the sql statement
707      *
708      * @param  string $sql
709      * @param  string $alias
710      * @return string
711      */
712         private function getAliasFromSQL($sql, $alias)
713     {
714         $matches = array();
715         preg_match('/^(.*SELECT)(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
716         //parse all single and double  quotes out of array
717         $sin_array = $this->removePatternFromSQL($matches[2], "'", "'","sin_");
718         $new_sql = array_pop($sin_array);
719         $dub_array = $this->removePatternFromSQL($new_sql, "\"", "\"","dub_");
720         $new_sql = array_pop($dub_array);
721
722         //search for parenthesis
723         $paren_array = $this->removePatternFromSQL($new_sql, "(", ")", "par_");
724         $new_sql = array_pop($paren_array);
725
726         //all functions should be removed now, so split the array on commas
727         $mstr_sql_array = explode(",", $new_sql);
728         foreach($mstr_sql_array as $token ) {
729             if (strpos($token, $alias)) {
730                 //found token, add back comments
731                 $token = $this->addPatternToSQL($token, $paren_array);
732                 $token = $this->addPatternToSQL($token, $dub_array);
733                 $token = $this->addPatternToSQL($token, $sin_array);
734
735                 //log and break out of this function
736                 return $token;
737             }
738         }
739         return null;
740     }
741
742
743     /**
744      * Finds the alias of the order by column, and then return the preceding column name
745      *
746      * @param  string $sql
747      * @param  string $orderMatch
748      * @return string
749      */
750     private function findColumnByAlias($sql, $orderMatch)
751     {
752         //change case to lowercase
753         $sql = strtolower($sql);
754         $patt = '/\s+'.trim($orderMatch).'\s*(,|from)/';
755
756         //check for the alias, it should contain comma, may contain space, \n, or \t
757         $matches = array();
758         preg_match($patt, $sql, $matches, PREG_OFFSET_CAPTURE);
759         $found_in_sql = isset($matches[0][1]) ? $matches[0][1] : false;
760
761
762         //set default for found variable
763         $found = $found_in_sql;
764
765         //if still no match found, then we need to parse through the string
766         if (!$found_in_sql){
767             //get count of how many times the match exists in string
768             $found_count = substr_count($sql, $orderMatch);
769             $i = 0;
770             $first_ = 0;
771             $len = strlen($orderMatch);
772             //loop through string as many times as there is a match
773             while ($found_count > $i) {
774                 //get the first match
775                 $found_in_sql = strpos($sql, $orderMatch,$first_);
776                 //make sure there was a match
777                 if($found_in_sql){
778                     //grab the next 2 individual characters
779                     $str_plusone = substr($sql,$found_in_sql + $len,1);
780                     $str_plustwo = substr($sql,$found_in_sql + $len+1,1);
781                     //if one of those characters is a comma, then we have our alias
782                     if ($str_plusone === "," || $str_plustwo === ","){
783                         //keep track of this position
784                         $found = $found_in_sql;
785                     }
786                 }
787                 //set the offset and increase the iteration counter
788                 $first_ = $found_in_sql+$len;
789                 $i = $i+1;
790             }
791         }
792         //return $found, defaults have been set, so if no match was found it will be a negative number
793         return $found;
794     }
795
796
797     /**
798      * Return the order by string to use in case the column has been aliased
799      *
800      * @param  string $sql
801      * @param  string $orig_order_match
802      * @return string
803      */
804     private function returnOrderBy($sql, $orig_order_match)
805     {
806         $sql = strtolower($sql);
807         $orig_order_match = trim($orig_order_match);
808         if (strpos($orig_order_match, ".") != 0)
809             //this has a tablename defined, pass in the order match
810             return $orig_order_match;
811
812         // If there is no ordering direction (ASC/DESC), use ASC by default
813         if (strpos($orig_order_match, " ") === false) {
814                 $orig_order_match .= " ASC";
815         }
816             
817         //grab first space in order by
818         $firstSpace = strpos($orig_order_match, " ");
819
820         //split order by into column name and ascending/descending
821         $orderMatch = " " . strtolower(substr($orig_order_match, 0, $firstSpace));
822         $asc_desc =  substr($orig_order_match,$firstSpace);
823
824         //look for column name as an alias in sql string
825         $found_in_sql = $this->findColumnByAlias($sql, $orderMatch);
826
827         if (!$found_in_sql) {
828             //check if this column needs the tablename prefixed to it
829             $orderMatch = ".".trim($orderMatch);
830             $colMatchPos = strpos($sql, $orderMatch);
831             if ($colMatchPos !== false) {
832                 //grab sub string up to column name
833                 $containsColStr = substr($sql,0, $colMatchPos);
834                 //get position of first space, so we can grab table name
835                 $lastSpacePos = strrpos($containsColStr, " ");
836                 //use positions of column name, space before name, and length of column to find the correct column name
837                 $col_name = substr($sql, $lastSpacePos, $colMatchPos-$lastSpacePos+strlen($orderMatch));
838                                 //bug 25485. When sorting by a custom field in Account List and then pressing NEXT >, system gives an error
839                                 $containsCommaPos = strpos($col_name, ",");
840                                 if($containsCommaPos !== false) {
841                                         $col_name = substr($col_name, $containsCommaPos+1);
842                                 }
843                 //add the "asc/desc" order back
844                 $col_name = $col_name. " ". $asc_desc;
845
846                 //return column name
847                 return $col_name;
848             }
849             //break out of here, log this
850             $GLOBALS['log']->debug("No match was found for order by, pass string back untouched as: $orig_order_match");
851             return $orig_order_match;
852         }
853         else {
854             //if found, then parse and return
855             //grab string up to the aliased column
856             $GLOBALS['log']->debug("order by found, process sql string");
857
858             $psql = (trim($this->getAliasFromSQL($sql, $orderMatch )));
859             if (empty($psql))
860                 $psql = trim(substr($sql, 0, $found_in_sql));
861
862             //grab the last comma before the alias
863             $comma_pos = strrpos($psql, " ");
864             //substring between the comma and the alias to find the joined_table alias and column name
865             $col_name = substr($psql,0, $comma_pos);
866
867             //make sure the string does not have an end parenthesis
868             //and is not part of a function (i.e. "ISNULL(leads.last_name,'') as name"  )
869             //this is especially true for unified search from home screen
870
871             $alias_beg_pos = 0;
872             if(strpos($psql, " as "))
873                 $alias_beg_pos = strpos($psql, " as ");
874
875             // Bug # 44923 - This breaks the query and does not properly filter isnull
876             // as there are other functions such as ltrim and rtrim.
877             /* else if (strncasecmp($psql, 'isnull', 6) != 0)
878                 $alias_beg_pos = strpos($psql, " "); */
879
880             if ($alias_beg_pos > 0) {
881                 $col_name = substr($psql,0, $alias_beg_pos );
882             }
883             //add the "asc/desc" order back
884             $col_name = $col_name. " ". $asc_desc;
885
886             //pass in new order by
887             $GLOBALS['log']->debug("order by being returned is " . $col_name);
888             return $col_name;
889         }
890     }
891
892     /**
893      * Take in a string of the module and retrieve the correspondent table name
894      *
895      * @param  string $module_str module name
896      * @param  string $sql        SQL statement
897      * @return string table name
898      */
899     private function getTableNameFromModuleName($module_str, $sql)
900     {
901
902         global $beanList, $beanFiles;
903         $GLOBALS['log']->debug("Module being processed is " . $module_str);
904         //get the right module files
905         //the module string exists in bean list, then process bean for correct table name
906         //note that we exempt the reports module from this, as queries from reporting module should be parsed for
907         //correct table name.
908         if (($module_str != 'Reports' && $module_str != 'SavedReport') && isset($beanList[$module_str])  &&  isset($beanFiles[$beanList[$module_str]])){
909             //if the class is not already loaded, then load files
910             if (!class_exists($beanList[$module_str]))
911                 require_once($beanFiles[$beanList[$module_str]]);
912
913             //instantiate new bean
914             $module_bean = new $beanList[$module_str]();
915             //get table name from bean
916             $tbl_name = $module_bean->table_name;
917             //make sure table name is not just a blank space, or empty
918             $tbl_name = trim($tbl_name);
919
920             if(empty($tbl_name)){
921                 $GLOBALS['log']->debug("Could not find table name for module $module_str. ");
922                 $tbl_name = $module_str;
923             }
924         }
925         else {
926             //since the module does NOT exist in beanlist, then we have to parse the string
927             //and grab the table name from the passed in sql
928             $GLOBALS['log']->debug("Could not find table name from module in request, retrieve from passed in sql");
929             $tbl_name = $module_str;
930             $sql = strtolower($sql);
931
932             // Bug #45625 : Getting Multi-part identifier (reports.id) could not be bound error when navigating to next page in reprots in mssql
933             // there is cases when sql string is multiline string and it we cannot find " from " string in it
934             $sql = str_replace(array("\n", "\r"), " ", $sql);
935
936             //look for the location of the "from" in sql string
937             $fromLoc = strpos($sql," from " );
938             if ($fromLoc>0){
939                 //found from, substring from the " FROM " string in sql to end
940                 $tableEnd = substr($sql, $fromLoc+6);
941                 //We know that tablename will be next parameter after from, so
942                 //grab the next space after table name.
943                 // MFH BUG #14009: Also check to see if there are any carriage returns before the next space so that we don't grab any arbitrary joins or other tables.
944                 $carriage_ret = strpos($tableEnd,"\n");
945                 $next_space = strpos($tableEnd," " );
946                 if ($carriage_ret < $next_space)
947                     $next_space = $carriage_ret;
948                 if ($next_space > 0) {
949                     $tbl_name= substr($tableEnd,0, $next_space);
950                     if(empty($tbl_name)){
951                         $GLOBALS['log']->debug("Could not find table name sql either, return $module_str. ");
952                         $tbl_name = $module_str;
953                     }
954                 }
955
956                 //grab the table, to see if it is aliased
957                 $aliasTableEnd = trim(substr($tableEnd, $next_space));
958                 $alias_space = strpos ($aliasTableEnd, " " );
959                 if ($alias_space > 0){
960                     $alias_tbl_name= substr($aliasTableEnd,0, $alias_space);
961                     strtolower($alias_tbl_name);
962                     if(empty($alias_tbl_name)
963                         || $alias_tbl_name == "where"
964                         || $alias_tbl_name == "inner"
965                         || $alias_tbl_name == "left"
966                         || $alias_tbl_name == "join"
967                         || $alias_tbl_name == "outer"
968                         || $alias_tbl_name == "right") {
969                         //not aliased, do nothing
970                     }
971                     elseif ($alias_tbl_name == "as") {
972                             //the next word is the table name
973                             $aliasTableEnd = trim(substr($aliasTableEnd, $alias_space));
974                             $alias_space = strpos ($aliasTableEnd, " " );
975                             if ($alias_space > 0) {
976                                 $alias_tbl_name= trim(substr($aliasTableEnd,0, $alias_space));
977                                 if (!empty($alias_tbl_name))
978                                     $tbl_name = $alias_tbl_name;
979                             }
980                     }
981                     else {
982                         //this is table alias
983                         $tbl_name = $alias_tbl_name;
984                     }
985                 }
986             }
987         }
988         //return table name
989         $GLOBALS['log']->debug("Table name for module $module_str is: ".$tbl_name);
990         return $tbl_name;
991     }
992
993
994         /**
995      * @see DBManager::getFieldsArray()
996      */
997         public function getFieldsArray($result, $make_lower_case = false)
998         {
999                 $field_array = array();
1000
1001                 if(! isset($result) || empty($result))
1002             return 0;
1003
1004         $i = 0;
1005         while ($i < mssql_num_fields($result)) {
1006             $meta = mssql_fetch_field($result, $i);
1007             if (!$meta)
1008                 return 0;
1009             if($make_lower_case==true)
1010                 $meta->name = strtolower($meta->name);
1011
1012             $field_array[] = $meta->name;
1013
1014             $i++;
1015         }
1016
1017         return $field_array;
1018         }
1019
1020     /**
1021      * @see DBManager::getAffectedRowCount()
1022      */
1023         public function getAffectedRowCount()
1024     {
1025         return $this->getOne("SELECT @@ROWCOUNT");
1026     }
1027
1028         /**
1029          * @see DBManager::fetchRow()
1030          */
1031         public function fetchRow($result)
1032         {
1033                 if (empty($result))     return false;
1034
1035         $row = mssql_fetch_assoc($result);
1036         //MSSQL returns a space " " when a varchar column is empty ("") and not null.
1037         //We need to iterate through the returned row array and strip empty spaces
1038         if(!empty($row)){
1039             foreach($row as $key => $column) {
1040                //notice we only strip if one space is returned.  we do not want to strip
1041                //strings with intentional spaces (" foo ")
1042                if (!empty($column) && $column ==" ") {
1043                    $row[$key] = '';
1044                }
1045             }
1046         }
1047         return $row;
1048         }
1049
1050     /**
1051      * @see DBManager::quote()
1052      */
1053     public function quote($string)
1054     {
1055         if(is_array($string)) {
1056             return $this->arrayQuote($string);
1057         }
1058         return str_replace("'","''", $this->quoteInternal($string));
1059     }
1060
1061     /**
1062      * @see DBManager::tableExists()
1063      */
1064     public function tableExists($tableName)
1065     {
1066         $GLOBALS['log']->info("tableExists: $tableName");
1067
1068         $this->checkConnection();
1069         $result = $this->getOne(
1070             "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME=".$this->quoted($tableName));
1071
1072         return !empty($result);
1073     }
1074
1075     /**
1076      * Get tables like expression
1077      * @param $like string
1078      * @return array
1079      */
1080     public function tablesLike($like)
1081     {
1082         if ($this->getDatabase()) {
1083             $tables = array();
1084             $r = $this->query('SELECT TABLE_NAME tn FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE=\'BASE TABLE\' AND TABLE_NAME LIKE '.$this->quoted($like));
1085             if (!empty($r)) {
1086                 while ($a = $this->fetchByAssoc($r)) {
1087                     $row = array_values($a);
1088                                         $tables[]=$row[0];
1089                 }
1090                 return $tables;
1091             }
1092         }
1093         return false;
1094     }
1095
1096     /**
1097      * @see DBManager::getTablesArray()
1098      */
1099     public function getTablesArray()
1100     {
1101         $GLOBALS['log']->debug('MSSQL fetching table list');
1102
1103         if($this->getDatabase()) {
1104             $tables = array();
1105             $r = $this->query('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES');
1106             if (is_resource($r)) {
1107                 while ($a = $this->fetchByAssoc($r))
1108                     $tables[] = $a['TABLE_NAME'];
1109
1110                 return $tables;
1111             }
1112         }
1113
1114         return false; // no database available
1115     }
1116
1117
1118     /**
1119      * This call is meant to be used during install, when Full Text Search is enabled
1120      * Indexing would always occur after a fresh sql server install, so this code creates
1121      * a catalog and table with full text index.
1122      */
1123     public function full_text_indexing_setup()
1124     {
1125         $GLOBALS['log']->debug('MSSQL about to wakeup FTS');
1126
1127         if($this->getDatabase()) {
1128                 //create wakeup catalog
1129                 $FTSqry[] = "if not exists(  select * from sys.fulltext_catalogs where name ='wakeup_catalog' )
1130                 CREATE FULLTEXT CATALOG wakeup_catalog
1131                 ";
1132
1133                 //drop wakeup table if it exists
1134                 $FTSqry[] = "IF EXISTS(SELECT 'fts_wakeup' FROM sysobjects WHERE name = 'fts_wakeup' AND xtype='U')
1135                     DROP TABLE fts_wakeup
1136                 ";
1137                 //create wakeup table
1138                 $FTSqry[] = "CREATE TABLE fts_wakeup(
1139                     id varchar(36) NOT NULL CONSTRAINT pk_fts_wakeup_id PRIMARY KEY CLUSTERED (id ASC ),
1140                     body text NULL,
1141                     kb_index int IDENTITY(1,1) NOT NULL CONSTRAINT wakeup_fts_unique_idx UNIQUE NONCLUSTERED
1142                 )
1143                 ";
1144                 //create full text index
1145                  $FTSqry[] = "CREATE FULLTEXT INDEX ON fts_wakeup
1146                 (
1147                     body
1148                     Language 0X0
1149                 )
1150                 KEY INDEX wakeup_fts_unique_idx ON wakeup_catalog
1151                 WITH CHANGE_TRACKING AUTO
1152                 ";
1153
1154                 //insert dummy data
1155                 $FTSqry[] = "INSERT INTO fts_wakeup (id ,body)
1156                 VALUES ('".create_guid()."', 'SugarCRM Rocks' )";
1157
1158
1159                 //create queries to stop and restart indexing
1160                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup STOP POPULATION';
1161                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup DISABLE';
1162                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup ENABLE';
1163                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING MANUAL';
1164                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup START FULL POPULATION';
1165                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING AUTO';
1166
1167                 foreach($FTSqry as $q){
1168                     sleep(3);
1169                     $this->query($q);
1170                 }
1171                 $this->create_default_full_text_catalog();
1172         }
1173
1174         return false; // no database available
1175     }
1176
1177     protected $date_formats = array(
1178         '%Y-%m-%d' => 10,
1179         '%Y-%m' => 7,
1180         '%Y' => 4,
1181     );
1182
1183     /**
1184      * @see DBManager::convert()
1185      */
1186     public function convert($string, $type, array $additional_parameters = array())
1187     {
1188         // convert the parameters array into a comma delimited string
1189         if (!empty($additional_parameters)) {
1190             $additional_parameters_string = ','.implode(',',$additional_parameters);
1191         } else {
1192             $additional_parameters_string = '';
1193         }
1194         $all_parameters = $additional_parameters;
1195         if(is_array($string)) {
1196             $all_parameters = array_merge($string, $all_parameters);
1197         } elseif (!is_null($string)) {
1198             array_unshift($all_parameters, $string);
1199         }
1200
1201         switch (strtolower($type)) {
1202             case 'today':
1203                 return "GETDATE()";
1204             case 'left':
1205                 return "LEFT($string$additional_parameters_string)";
1206             case 'date_format':
1207                 if(!empty($additional_parameters[0]) && $additional_parameters[0][0] == "'") {
1208                     $additional_parameters[0] = trim($additional_parameters[0], "'");
1209                 }
1210                 if(!empty($additional_parameters) && isset($this->date_formats[$additional_parameters[0]])) {
1211                     $len = $this->date_formats[$additional_parameters[0]];
1212                     return "LEFT(CONVERT(varchar($len),". $string . ",120),$len)";
1213                 } else {
1214                    return "LEFT(CONVERT(varchar(10),". $string . ",120),10)";
1215                 }
1216             case 'ifnull':
1217                 if(empty($additional_parameters_string)) {
1218                     $additional_parameters_string = ",''";
1219                 }
1220                 return "ISNULL($string$additional_parameters_string)";
1221             case 'concat':
1222                 return implode("+",$all_parameters);
1223             case 'text2char':
1224                 return "CAST($string AS varchar(8000))";
1225             case 'quarter':
1226                 return "DATENAME(quarter, $string)";
1227             case "length":
1228                 return "LEN($string)";
1229             case 'month':
1230                 return "MONTH($string)";
1231             case 'add_date':
1232                 return "DATEADD({$additional_parameters[1]},{$additional_parameters[0]},$string)";
1233             case 'add_time':
1234                 return "DATEADD(hh, {$additional_parameters[0]}, DATEADD(mi, {$additional_parameters[1]}, $string))";
1235             case 'add_tz_offset' :
1236                 $getUserUTCOffset = $GLOBALS['timedate']->getUserUTCOffset();
1237                 $operation = $getUserUTCOffset < 0 ? '-' : '+';
1238                 return 'DATEADD(minute, ' . $operation . abs($getUserUTCOffset) . ', ' . $string. ')';
1239         }
1240
1241         return "$string";
1242     }
1243
1244     /**
1245      * @see DBManager::fromConvert()
1246      */
1247     public function fromConvert($string, $type)
1248     {
1249         switch($type) {
1250             case 'datetimecombo':
1251             case 'datetime': return substr($string, 0,19);
1252             case 'date': return substr($string, 0, 10);
1253             case 'time': return substr($string, 11);
1254                 }
1255                 return $string;
1256     }
1257
1258     /**
1259      * @see DBManager::createTableSQLParams()
1260      */
1261         public function createTableSQLParams($tablename, $fieldDefs, $indices)
1262     {
1263         if (empty($tablename) || empty($fieldDefs))
1264             return '';
1265
1266         $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
1267         if (empty($columns))
1268             return '';
1269
1270         return "CREATE TABLE $tablename ($columns)";
1271     }
1272
1273     /**
1274      * Does this type represent text (i.e., non-varchar) value?
1275      * @param string $type
1276      */
1277     public function isTextType($type)
1278     {
1279         $type = strtolower($type);
1280         if(!isset($this->type_map[$type])) return false;
1281         return in_array($this->type_map[$type], array('ntext','text','image', 'nvarchar(max)'));
1282     }
1283
1284     /**
1285      * Return representation of an empty value depending on type
1286      * @param string $type
1287      */
1288     public function emptyValue($type)
1289     {
1290         $ctype = $this->getColumnType($type);
1291         if($ctype == "datetime") {
1292             return $this->convert($this->quoted("1970-01-01 00:00:00"), "datetime");
1293         }
1294         if($ctype == "date") {
1295             return $this->convert($this->quoted("1970-01-01"), "datetime");
1296         }
1297         if($ctype == "time") {
1298             return $this->convert($this->quoted("00:00:00"), "time");
1299         }
1300         return parent::emptyValue($type);
1301     }
1302
1303     public function renameColumnSQL($tablename, $column, $newname)
1304     {
1305         return "SP_RENAME '$tablename.$column', '$newname', 'COLUMN'";
1306     }
1307
1308     /**
1309      * Returns the SQL Alter table statment
1310      *
1311      * MSSQL has a quirky T-SQL alter table syntax. Pay special attention to the
1312      * modify operation
1313      * @param string $action
1314      * @param array  $def
1315      * @param bool   $ignorRequired
1316      * @param string $tablename
1317      */
1318     protected function alterSQLRep($action, array $def, $ignoreRequired, $tablename)
1319     {
1320         switch($action){
1321         case 'add':
1322              $f_def=$this->oneColumnSQLRep($def, $ignoreRequired,$tablename,false);
1323             return "ADD " . $f_def;
1324             break;
1325         case 'drop':
1326             return "DROP COLUMN " . $def['name'];
1327             break;
1328         case 'modify':
1329             //You cannot specify a default value for a column for MSSQL
1330             $f_def  = $this->oneColumnSQLRep($def, $ignoreRequired,$tablename, true);
1331             $f_stmt = "ALTER COLUMN ".$f_def['name'].' '.$f_def['colType'].' '.
1332                         $f_def['required'].' '.$f_def['auto_increment']."\n";
1333             if (!empty( $f_def['default']))
1334                 $f_stmt .= " ALTER TABLE " . $tablename .  " ADD  ". $f_def['default'] . " FOR " . $def['name'];
1335             return $f_stmt;
1336             break;
1337         default:
1338             return '';
1339         }
1340     }
1341
1342     /**
1343      * @see DBManager::changeColumnSQL()
1344      *
1345      * MSSQL uses a different syntax than MySQL for table altering that is
1346      * not quite as simplistic to implement...
1347      */
1348     protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
1349     {
1350         $sql=$sql2='';
1351         $constraints = $this->get_field_default_constraint_name($tablename);
1352         $columns = array();
1353         if ($this->isFieldArray($fieldDefs)) {
1354             foreach ($fieldDefs as $def)
1355                 {
1356                         //if the column is being modified drop the default value
1357                         //constraint if it exists. alterSQLRep will add the constraint back
1358                         if (!empty($constraints[$def['name']])) {
1359                                 $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$def['name']];
1360                         }
1361                         //check to see if we need to drop related indexes before the alter
1362                         $indices = $this->get_indices($tablename);
1363                 foreach ( $indices as $index ) {
1364                     if ( in_array($def['name'],$index['fields']) ) {
1365                         $sql  .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
1366                         $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
1367                     }
1368                 }
1369
1370                         $columns[] = $this->alterSQLRep($action, $def, $ignoreRequired,$tablename);
1371                 }
1372         }
1373         else {
1374             //if the column is being modified drop the default value
1375                 //constraint if it exists. alterSQLRep will add the constraint back
1376                 if (!empty($constraints[$fieldDefs['name']])) {
1377                         $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$fieldDefs['name']];
1378                 }
1379                 //check to see if we need to drop related indexes before the alter
1380             $indices = $this->get_indices($tablename);
1381             foreach ( $indices as $index ) {
1382                 if ( in_array($fieldDefs['name'],$index['fields']) ) {
1383                     $sql  .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
1384                     $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
1385                 }
1386             }
1387
1388
1389                 $columns[] = $this->alterSQLRep($action, $fieldDefs, $ignoreRequired,$tablename);
1390         }
1391
1392         $columns = implode(", ", $columns);
1393         $sql .= " ALTER TABLE $tablename $columns " . $sql2;
1394
1395         return $sql;
1396     }
1397
1398     protected function setAutoIncrement($table, $field_name)
1399     {
1400                 return "identity(1,1)";
1401         }
1402
1403     /**
1404      * @see DBManager::setAutoIncrementStart()
1405      */
1406     public function setAutoIncrementStart($table, $field_name, $start_value)
1407     {
1408         if($start_value > 1)
1409             $start_value -= 1;
1410                 $this->query("DBCC CHECKIDENT ('$table', RESEED, $start_value) WITH NO_INFOMSGS");
1411         return true;
1412     }
1413
1414         /**
1415      * @see DBManager::getAutoIncrement()
1416      */
1417     public function getAutoIncrement($table, $field_name)
1418     {
1419                 $result = $this->getOne("select IDENT_CURRENT('$table') + IDENT_INCR ( '$table' ) as 'Auto_increment'");
1420         return $result;
1421     }
1422
1423     /**
1424      * @see DBManager::get_indices()
1425      */
1426     public function get_indices($tableName)
1427     {
1428         //find all unique indexes and primary keys.
1429         $query = <<<EOSQL
1430 SELECT sys.tables.object_id, sys.tables.name as table_name, sys.columns.name as column_name,
1431                 sys.indexes.name as index_name, sys.indexes.is_unique, sys.indexes.is_primary_key
1432             FROM sys.tables, sys.indexes, sys.index_columns, sys.columns
1433             WHERE (sys.tables.object_id = sys.indexes.object_id
1434                     AND sys.tables.object_id = sys.index_columns.object_id
1435                     AND sys.tables.object_id = sys.columns.object_id
1436                     AND sys.indexes.index_id = sys.index_columns.index_id
1437                     AND sys.index_columns.column_id = sys.columns.column_id)
1438                 AND sys.tables.name = '$tableName'
1439 EOSQL;
1440         $result = $this->query($query);
1441
1442         $indices = array();
1443         while (($row=$this->fetchByAssoc($result)) != null) {
1444             $index_type = 'index';
1445             if ($row['is_primary_key'] == '1')
1446                 $index_type = 'primary';
1447             elseif ($row['is_unique'] == 1 )
1448                 $index_type = 'unique';
1449             $name = strtolower($row['index_name']);
1450             $indices[$name]['name']     = $name;
1451             $indices[$name]['type']     = $index_type;
1452             $indices[$name]['fields'][] = strtolower($row['column_name']);
1453         }
1454         return $indices;
1455     }
1456
1457     /**
1458      * @see DBManager::get_columns()
1459      */
1460     public function get_columns($tablename)
1461     {
1462         //find all unique indexes and primary keys.
1463         $result = $this->query("sp_columns $tablename");
1464
1465         $columns = array();
1466         while (($row=$this->fetchByAssoc($result)) !=null) {
1467             $column_name = strtolower($row['COLUMN_NAME']);
1468             $columns[$column_name]['name']=$column_name;
1469             $columns[$column_name]['type']=strtolower($row['TYPE_NAME']);
1470             if ( $row['TYPE_NAME'] == 'decimal' ) {
1471                 $columns[$column_name]['len']=strtolower($row['PRECISION']);
1472                 $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
1473             }
1474                         elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) )
1475                                 $columns[$column_name]['len']=strtolower($row['PRECISION']);
1476             elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) )
1477                 $columns[$column_name]['len']=strtolower($row['LENGTH']);
1478             if ( stristr($row['TYPE_NAME'],'identity') ) {
1479                 $columns[$column_name]['auto_increment'] = '1';
1480                 $columns[$column_name]['type']=str_replace(' identity','',strtolower($row['TYPE_NAME']));
1481             }
1482
1483             if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI')))
1484                 $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
1485
1486             $column_def = 1;
1487             if ( strtolower($tablename) == 'relationships' ) {
1488                 $column_def = $this->getOne("select cdefault from syscolumns where id = object_id('relationships') and name = '$column_name'");
1489             }
1490             if ( $column_def != 0 && ($row['COLUMN_DEF'] != null)) {    // NOTE Not using !empty as an empty string may be a viable default value.
1491                 $matches = array();
1492                 $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'],ENT_QUOTES);
1493                 if ( preg_match('/\([\(|\'](.*)[\)|\']\)/i',$row['COLUMN_DEF'],$matches) )
1494                     $columns[$column_name]['default'] = $matches[1];
1495                 elseif ( preg_match('/\(N\'(.*)\'\)/i',$row['COLUMN_DEF'],$matches) )
1496                     $columns[$column_name]['default'] = $matches[1];
1497                 else
1498                     $columns[$column_name]['default'] = $row['COLUMN_DEF'];
1499             }
1500         }
1501         return $columns;
1502     }
1503
1504
1505     /**
1506      * Get FTS catalog name for current DB
1507      */
1508     protected function ftsCatalogName()
1509     {
1510         if(isset($this->connectOptions['db_name'])) {
1511             return $this->connectOptions['db_name']."_fts_catalog";
1512         }
1513         return 'sugar_fts_catalog';
1514     }
1515
1516     /**
1517      * @see DBManager::add_drop_constraint()
1518      */
1519     public function add_drop_constraint($table, $definition, $drop = false)
1520     {
1521         $type         = $definition['type'];
1522         $fields       = is_array($definition['fields'])?implode(',',$definition['fields']):$definition['fields'];
1523         $name         = $definition['name'];
1524         $sql          = '';
1525
1526         switch ($type){
1527         // generic indices
1528         case 'index':
1529         case 'alternate_key':
1530             if ($drop)
1531                 $sql = "DROP INDEX {$name} ON {$table}";
1532             else
1533                 $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
1534             break;
1535         case 'clustered':
1536             if ($drop)
1537                 $sql = "DROP INDEX {$name} ON {$table}";
1538             else
1539                 $sql = "CREATE CLUSTERED INDEX $name ON $table ($fields)";
1540             break;
1541             // constraints as indices
1542         case 'unique':
1543             if ($drop)
1544                 $sql = "ALTER TABLE {$table} DROP CONSTRAINT $name";
1545             else
1546                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE ({$fields})";
1547             break;
1548         case 'primary':
1549             if ($drop)
1550                 $sql = "ALTER TABLE {$table} DROP CONSTRAINT {$name}";
1551             else
1552                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} PRIMARY KEY ({$fields})";
1553             break;
1554         case 'foreign':
1555             if ($drop)
1556                 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
1557             else
1558                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name}  FOREIGN KEY ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignFields']})";
1559             break;
1560         case 'fulltext':
1561             if ($this->full_text_indexing_enabled() && $drop) {
1562                 $sql = "DROP FULLTEXT INDEX ON {$table}";
1563             } elseif ($this->full_text_indexing_enabled()) {
1564                 $catalog_name=$this->ftsCatalogName();
1565                 if ( isset($definition['catalog_name']) && $definition['catalog_name'] != 'default')
1566                     $catalog_name = $definition['catalog_name'];
1567
1568                 $language = "Language 1033";
1569                 if (isset($definition['language']) && !empty($definition['language']))
1570                     $language = "Language " . $definition['language'];
1571
1572                 $key_index = $definition['key_index'];
1573
1574                 $change_tracking = "auto";
1575                 if (isset($definition['change_tracking']) && !empty($definition['change_tracking']))
1576                     $change_tracking = $definition['change_tracking'];
1577
1578                 $sql = " CREATE FULLTEXT INDEX ON $table ($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
1579             }
1580             break;
1581         }
1582         return $sql;
1583     }
1584
1585     /**
1586      * Returns true if Full Text Search is installed
1587      *
1588      * @return bool
1589      */
1590     public function full_text_indexing_installed()
1591     {
1592         $ftsChckRes = $this->getOne("SELECT FULLTEXTSERVICEPROPERTY('IsFulltextInstalled') as fts");
1593         return !empty($ftsChckRes);
1594     }
1595
1596     /**
1597      * @see DBManager::full_text_indexing_enabled()
1598      */
1599     protected function full_text_indexing_enabled($dbname = null)
1600     {
1601         // check to see if we already have install setting in session
1602         if(!isset($_SESSION['IsFulltextInstalled']))
1603             $_SESSION['IsFulltextInstalled'] = $this->full_text_indexing_installed();
1604
1605         // check to see if FTS Indexing service is installed
1606         if(empty($_SESSION['IsFulltextInstalled']))
1607             return false;
1608
1609         // grab the dbname if it was not passed through
1610                 if (empty($dbname)) {
1611                         global $sugar_config;
1612                         $dbname = $sugar_config['dbconfig']['db_name'];
1613                 }
1614         //we already know that Indexing service is installed, now check
1615         //to see if it is enabled
1616                 $res = $this->getOne("SELECT DATABASEPROPERTY('$dbname', 'IsFulltextEnabled') ftext");
1617         return !empty($res);
1618         }
1619
1620     /**
1621      * Creates default full text catalog
1622      */
1623         protected function create_default_full_text_catalog()
1624     {
1625                 if ($this->full_text_indexing_enabled()) {
1626                     $catalog = $this->ftsCatalogName();
1627             $GLOBALS['log']->debug("Creating the default catalog for full-text indexing, $catalog");
1628
1629             //drop catalog if exists.
1630                         $ret = $this->query("
1631                 if not exists(
1632                     select *
1633                         from sys.fulltext_catalogs
1634                         where name ='$catalog'
1635                         )
1636                 CREATE FULLTEXT CATALOG $catalog");
1637
1638                         if (empty($ret)) {
1639                                 $GLOBALS['log']->error("Error creating default full-text catalog, $catalog");
1640                         }
1641                 }
1642         }
1643
1644     /**
1645      * Function returns name of the constraint automatically generated by sql-server.
1646      * We request this for default, primary key, required
1647      *
1648      * @param  string $table
1649      * @param  string $column
1650      * @return string
1651      */
1652         private function get_field_default_constraint_name($table, $column = null)
1653     {
1654         static $results = array();
1655
1656         if ( empty($column) && isset($results[$table]) )
1657             return $results[$table];
1658
1659         $query = <<<EOQ
1660 select s.name, o.name, c.name dtrt, d.name ctrt
1661     from sys.default_constraints as d
1662         join sys.objects as o
1663             on o.object_id = d.parent_object_id
1664         join sys.columns as c
1665             on c.object_id = o.object_id and c.column_id = d.parent_column_id
1666         join sys.schemas as s
1667             on s.schema_id = o.schema_id
1668     where o.name = '$table'
1669 EOQ;
1670         if ( !empty($column) )
1671             $query .= " and c.name = '$column'";
1672         $res = $this->query($query);
1673         if ( !empty($column) ) {
1674             $row = $this->fetchByAssoc($res);
1675             if (!empty($row))
1676                 return $row['ctrt'];
1677         }
1678         else {
1679             $returnResult = array();
1680             while ( $row = $this->fetchByAssoc($res) )
1681                 $returnResult[$row['dtrt']] = $row['ctrt'];
1682             $results[$table] = $returnResult;
1683             return $returnResult;
1684         }
1685
1686         return null;
1687         }
1688
1689     /**
1690      * @see DBManager::massageFieldDef()
1691      */
1692     public function massageFieldDef(&$fieldDef, $tablename)
1693     {
1694         parent::massageFieldDef($fieldDef,$tablename);
1695
1696         if ($fieldDef['type'] == 'int')
1697             $fieldDef['len'] = '4';
1698
1699         if(empty($fieldDef['len']))
1700         {
1701             switch($fieldDef['type']) {
1702                 case 'bit'      :
1703                 case 'bool'     : $fieldDef['len'] = '1'; break;
1704                 case 'smallint' : $fieldDef['len'] = '2'; break;
1705                 case 'float'    : $fieldDef['len'] = '8'; break;
1706                 case 'varchar'  :
1707                 case 'nvarchar' :
1708                                   $fieldDef['len'] = $this->isTextType($fieldDef['dbType']) ? 'max' : '255';
1709                                   break;
1710                 case 'image'    : $fieldDef['len'] = '2147483647'; break;
1711                 case 'ntext'    : $fieldDef['len'] = '2147483646'; break;   // Note: this is from legacy code, don't know if this is correct
1712             }
1713         }
1714         if($fieldDef['type'] == 'decimal'
1715            && empty($fieldDef['precision'])
1716            && !strpos($fieldDef['len'], ','))
1717         {
1718              $fieldDef['len'] .= ',0'; // Adding 0 precision if it is not specified
1719         }
1720
1721         if(empty($fieldDef['default'])
1722             && in_array($fieldDef['type'],array('bit','bool')))
1723         {
1724             $fieldDef['default'] = '0';
1725         }
1726                 if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']) )
1727                         $fieldDef['default'] = '';
1728 //        if ($fieldDef['type'] == 'bit' && empty($fieldDef['len']) )
1729 //            $fieldDef['len'] = '1';
1730 //              if ($fieldDef['type'] == 'bool' && empty($fieldDef['len']) )
1731 //            $fieldDef['len'] = '1';
1732 //        if ($fieldDef['type'] == 'float' && empty($fieldDef['len']) )
1733 //            $fieldDef['len'] = '8';
1734 //        if ($fieldDef['type'] == 'varchar' && empty($fieldDef['len']) )
1735 //            $fieldDef['len'] = '255';
1736 //              if ($fieldDef['type'] == 'nvarchar' && empty($fieldDef['len']) )
1737 //            $fieldDef['len'] = '255';
1738 //        if ($fieldDef['type'] == 'image' && empty($fieldDef['len']) )
1739 //            $fieldDef['len'] = '2147483647';
1740 //        if ($fieldDef['type'] == 'ntext' && empty($fieldDef['len']) )
1741 //            $fieldDef['len'] = '2147483646';
1742 //        if ($fieldDef['type'] == 'smallint' && empty($fieldDef['len']) )
1743 //            $fieldDef['len'] = '2';
1744 //        if ($fieldDef['type'] == 'bit' && empty($fieldDef['default']) )
1745 //            $fieldDef['default'] = '0';
1746 //              if ($fieldDef['type'] == 'bool' && empty($fieldDef['default']) )
1747 //            $fieldDef['default'] = '0';
1748
1749     }
1750
1751     /**
1752      * @see DBManager::oneColumnSQLRep()
1753      */
1754     protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
1755     {
1756         //Bug 25814
1757                 if(isset($fieldDef['name'])){
1758                     $colType = $this->getFieldType($fieldDef);
1759                 if(stristr($this->getFieldType($fieldDef), 'decimal') && isset($fieldDef['len'])){
1760                                 $fieldDef['len'] = min($fieldDef['len'],38);
1761                         }
1762                     //bug: 39690 float(8) is interpreted as real and this generates a diff when doing repair
1763                         if(stristr($colType, 'float') && isset($fieldDef['len']) && $fieldDef['len'] == 8){
1764                                 unset($fieldDef['len']);
1765                         }
1766                 }
1767
1768                 // always return as array for post-processing
1769                 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
1770
1771                 // Bug 24307 - Don't add precision for float fields.
1772                 if ( stristr($ref['colType'],'float') )
1773                         $ref['colType'] = preg_replace('/(,\d+)/','',$ref['colType']);
1774
1775         if ( $return_as_array )
1776             return $ref;
1777         else
1778             return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
1779         }
1780
1781     /**
1782      * Saves changes to module's audit table
1783      *
1784      * @param object $bean    Sugarbean instance
1785      * @param array  $changes changes
1786      */
1787     public function save_audit_records(SugarBean $bean, $changes)
1788         {
1789                 //Bug 25078 fixed by Martin Hu: sqlserver haven't 'date' type, trim extra "00:00:00"
1790                 if($changes['data_type'] == 'date'){
1791                         $changes['before'] = str_replace(' 00:00:00','',$changes['before']);
1792                 }
1793                 parent::save_audit_records($bean,$changes);
1794         }
1795
1796     /**
1797      * Disconnects from the database
1798      *
1799      * Also handles any cleanup needed
1800      */
1801     public function disconnect()
1802     {
1803         $GLOBALS['log']->debug('Calling Mssql::disconnect()');
1804         if(!empty($this->database)){
1805             $this->freeResult();
1806             mssql_close($this->database);
1807             $this->database = null;
1808         }
1809     }
1810
1811     /**
1812      * @see DBManager::freeDbResult()
1813      */
1814     protected function freeDbResult($dbResult)
1815     {
1816         if(!empty($dbResult))
1817             mssql_free_result($dbResult);
1818     }
1819
1820         /**
1821          * (non-PHPdoc)
1822          * @see DBManager::lastDbError()
1823          */
1824     public function lastDbError()
1825     {
1826         $sqlmsg = mssql_get_last_message();
1827         if(empty($sqlmsg)) return false;
1828         global $app_strings;
1829         if (empty($app_strings)
1830                     or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
1831                         or !isset($app_strings['ERR_MSSQL_WARNING']) ) {
1832         //ignore the message from sql-server if $app_strings array is empty. This will happen
1833         //only if connection if made before language is set.
1834                     return false;
1835         }
1836
1837         $sqlpos = strpos($sqlmsg, 'Changed database context to');
1838         $sqlpos2 = strpos($sqlmsg, 'Warning:');
1839         $sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
1840         if ( $sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false ) {
1841             return false;
1842         } else {
1843                 global $app_strings;
1844             //ERR_MSSQL_DB_CONTEXT: localized version of 'Changed database context to' message
1845             if (empty($app_strings) or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])) {
1846                 //ignore the message from sql-server if $app_strings array is empty. This will happen
1847                 //only if connection if made before languge is set.
1848                 $GLOBALS['log']->debug("Ignoring this database message: " . $sqlmsg);
1849                 return false;
1850             }
1851             else {
1852                 $sqlpos = strpos($sqlmsg, $app_strings['ERR_MSSQL_DB_CONTEXT']);
1853                 if ( $sqlpos !== false )
1854                     return false;
1855             }
1856         }
1857
1858         if ( strlen($sqlmsg) > 2 ) {
1859                 return "SQL Server error: " . $sqlmsg;
1860         }
1861
1862         return false;
1863     }
1864
1865     /**
1866      * (non-PHPdoc)
1867      * @see DBManager::getDbInfo()
1868      */
1869     public function getDbInfo()
1870     {
1871         return array("version" => $this->version());
1872     }
1873
1874     /**
1875      * (non-PHPdoc)
1876      * @see DBManager::validateQuery()
1877      */
1878     public function validateQuery($query)
1879     {
1880         if(!$this->isSelect($query)) {
1881             return false;
1882         }
1883         $this->query("SET SHOWPLAN_TEXT ON");
1884         $res = $this->getOne($query);
1885         $this->query("SET SHOWPLAN_TEXT OFF");
1886         return !empty($res);
1887     }
1888
1889     /**
1890      * This is a utility function to prepend the "N" character in front of SQL values that are
1891      * surrounded by single quotes.
1892      *
1893      * @param  $sql string SQL statement
1894      * @return string SQL statement with single quote values prepended with "N" character for nvarchar columns
1895      */
1896     protected function _appendN($sql)
1897     {
1898         // If there are no single quotes, don't bother, will just assume there is no character data
1899         if (strpos($sql, "'") === false)
1900             return $sql;
1901
1902         // Flag if there are odd number of single quotes, just continue without trying to append N
1903         if ((substr_count($sql, "'") & 1)) {
1904             $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
1905             return $sql;
1906         }
1907
1908         //The only location of three subsequent ' will be at the beginning or end of a value.
1909         $sql = preg_replace('/(?<!\')(\'{3})(?!\')/', "'<@#@#@PAIR@#@#@>", $sql);
1910
1911         // Remove any remaining '' and do not parse... replace later (hopefully we don't even have any)
1912         $pairs        = array();
1913         $regexp       = '/(\'{2})/';
1914         $pair_matches = array();
1915         preg_match_all($regexp, $sql, $pair_matches);
1916         if ($pair_matches) {
1917             foreach (array_unique($pair_matches[0]) as $key=>$value) {
1918                 $pairs['<@PAIR-'.$key.'@>'] = $value;
1919             }
1920             if (!empty($pairs)) {
1921                 $sql = str_replace($pairs, array_keys($pairs), $sql);
1922             }
1923         }
1924
1925         $regexp  = "/(N?'.+?')/is";
1926         $matches = array();
1927         preg_match_all($regexp, $sql, $matches);
1928         $replace = array();
1929         if (!empty($matches)) {
1930             foreach ($matches[0] as $value) {
1931                 // We are assuming that all nvarchar columns are no more than 200 characters in length
1932                 // One problem we face is the image column type in reports which cannot accept nvarchar data
1933                 if (!empty($value) && !is_numeric(trim(str_replace(array("'", ","), "", $value))) && !preg_match('/^\'[\,]\'$/', $value)) {
1934                     $replace[$value] = 'N' . trim($value, "N");
1935                 }
1936             }
1937         }
1938
1939         if (!empty($replace))
1940             $sql = str_replace(array_keys($replace), $replace, $sql);
1941
1942         if (!empty($pairs))
1943             $sql = str_replace(array_keys($pairs), $pairs, $sql);
1944
1945         if(strpos($sql, "<@#@#@PAIR@#@#@>"))
1946             $sql = str_replace(array('<@#@#@PAIR@#@#@>'), array("''"), $sql);
1947
1948         return $sql;
1949     }
1950
1951     /**
1952      * Quote SQL Server search term
1953      * @param string $term
1954      * @return string
1955      */
1956     protected function quoteTerm($term)
1957     {
1958         $term = str_replace("%", "*", $term); // Mssql wildcard is *
1959         return '"'.$term.'"';
1960     }
1961
1962     /**
1963      * Generate fulltext query from set of terms
1964      * @param string $fields Field to search against
1965      * @param array $terms Search terms that may be or not be in the result
1966      * @param array $must_terms Search terms that have to be in the result
1967      * @param array $exclude_terms Search terms that have to be not in the result
1968      */
1969     public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1970     {
1971         $condition = $or_condition = array();
1972         foreach($must_terms as $term) {
1973             $condition[] = $this->quoteTerm($term);
1974         }
1975
1976         foreach($terms as $term) {
1977             $or_condition[] = $this->quoteTerm($term);
1978         }
1979
1980         if(!empty($or_condition)) {
1981             $condition[] = "(".join(" | ", $or_condition).")";
1982         }
1983
1984         foreach($exclude_terms as $term) {
1985             $condition[] = " NOT ".$this->quoteTerm($term);
1986         }
1987         $condition = $this->quoted(join(" AND ",$condition));
1988         return "CONTAINS($field, $condition)";
1989     }
1990
1991     /**
1992      * Check if certain database exists
1993      * @param string $dbname
1994      */
1995     public function dbExists($dbname)
1996     {
1997         $db = $this->getOne("SELECT name FROM master..sysdatabases WHERE name = N".$this->quoted($dbname));
1998         return !empty($db);
1999     }
2000
2001     /**
2002      * Select database
2003      * @param string $dbname
2004      */
2005     protected function selectDb($dbname)
2006     {
2007         return mssql_select_db($dbname);
2008     }
2009
2010     /**
2011      * Check if certain DB user exists
2012      * @param string $username
2013      */
2014     public function userExists($username)
2015     {
2016         $this->selectDb("master");
2017         $user = $this->getOne("select count(*) from sys.sql_logins where name =".$this->quoted($username));
2018         // FIXME: go back to the original DB
2019         return !empty($user);
2020     }
2021
2022     /**
2023      * Create DB user
2024      * @param string $database_name
2025      * @param string $host_name
2026      * @param string $user
2027      * @param string $password
2028      */
2029     public function createDbUser($database_name, $host_name, $user, $password)
2030     {
2031         $qpassword = $this->quote($password);
2032         $this->selectDb($database_name);
2033         $this->query("CREATE LOGIN $user WITH PASSWORD = '$qpassword'", true);
2034         $this->query("CREATE USER $user FOR LOGIN $user", true);
2035         $this->query("EXEC sp_addRoleMember 'db_ddladmin ', '$user'", true);
2036         $this->query("EXEC sp_addRoleMember 'db_datareader','$user'", true);
2037         $this->query("EXEC sp_addRoleMember 'db_datawriter','$user'", true);
2038     }
2039
2040     /**
2041      * Create a database
2042      * @param string $dbname
2043      */
2044     public function createDatabase($dbname)
2045     {
2046         return $this->query("CREATE DATABASE $dbname", true);
2047     }
2048
2049     /**
2050      * Drop a database
2051      * @param string $dbname
2052      */
2053     public function dropDatabase($dbname)
2054     {
2055         return $this->query("DROP DATABASE $dbname", true);
2056     }
2057
2058     /**
2059      * Check if this driver can be used
2060      * @return bool
2061      */
2062     public function valid()
2063     {
2064         return function_exists("mssql_connect");
2065     }
2066
2067     /**
2068      * Check if this DB name is valid
2069      *
2070      * @param string $name
2071      * @return bool
2072      */
2073     public function isDatabaseNameValid($name)
2074     {
2075         // No funny chars, does not begin with number
2076         return preg_match('/^[0-9#@]+|[\"\'\*\/\\?\:\\<\>\-\ \&\!\(\)\[\]\{\}\;\,\.\`\~\|\\\\]+/', $name)==0;
2077     }
2078
2079     public function installConfig()
2080     {
2081         return array(
2082                 'LBL_DBCONFIG_MSG3' =>  array(
2083                 "setup_db_database_name" => array("label" => 'LBL_DBCONF_DB_NAME', "required" => true),
2084             ),
2085             'LBL_DBCONFIG_MSG2' =>  array(
2086                 "setup_db_host_name" => array("label" => 'LBL_DBCONF_HOST_NAME', "required" => true),
2087                 "setup_db_host_instance" => array("label" => 'LBL_DBCONF_HOST_INSTANCE'),
2088             ),
2089             'LBL_DBCONF_TITLE_USER_INFO' => array(),
2090             'LBL_DBCONFIG_B_MSG1' => array(
2091                 "setup_db_admin_user_name" => array("label" => 'LBL_DBCONF_DB_ADMIN_USER', "required" => true),
2092                 "setup_db_admin_password" => array("label" => 'LBL_DBCONF_DB_ADMIN_PASSWORD', "type" => "password"),
2093             )
2094         );
2095     }
2096
2097     /**
2098      * Returns a DB specific FROM clause which can be used to select against functions.
2099      * Note that depending on the database that this may also be an empty string.
2100      * @return string
2101      */
2102     public function getFromDummyTable()
2103     {
2104         return '';
2105     }
2106
2107     /**
2108      * Returns a DB specific piece of SQL which will generate GUID (UUID)
2109      * This string can be used in dynamic SQL to do multiple inserts with a single query.
2110      * I.e. generate a unique Sugar id in a sub select of an insert statement.
2111      * @return string
2112      */
2113
2114         public function getGuidSQL()
2115     {
2116         return 'NEWID()';
2117     }
2118 }