]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/database/MssqlManager.php
Release 6.5.15
[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 && $start == 0)
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\b)(.*?\bFROM\b.*\bWHERE\b)(.*)$/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('/^(.*)(\bORDER BY\b)(.*)$/is',$matches[3], $orderByMatch);
451                         if (!empty($orderByMatch[3])) {
452                             $selectPart = array();
453                             preg_match('/^(.*)(\bFROM\b.*)$/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('/^(.*)(\bORDER BY\b)(.*)$/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
501                     require_once('include/php-sql-parser.php');
502                     $parser = new PHPSQLParser();
503                     $sqlArray = $parser->parse($sql);
504
505                     if ($hasDistinct) {
506                         $matches_sql = strtolower($matches[0]);
507                         //remove reference to distinct and select keywords, as we will use a group by instead
508                         //we need to use group by because we are introducing rownumber column which would make every row unique
509
510                         //take out the select and distinct from string so we can reuse in group by
511                         $dist_str = 'distinct';
512                         preg_match('/\b' . $dist_str . '\b/simU', $matches_sql, $matchesPartSQL, PREG_OFFSET_CAPTURE);
513                         $matches_sql = trim(substr($matches_sql,$matchesPartSQL[0][1] + strlen($dist_str)));
514                         //get the position of where and from for further processing
515                         preg_match('/\bfrom\b/simU', $matches_sql, $matchesPartSQL, PREG_OFFSET_CAPTURE);
516                         $from_pos = $matchesPartSQL[0][1];
517                         preg_match('/\where\b/simU', $matches_sql, $matchesPartSQL, PREG_OFFSET_CAPTURE);
518                         $where_pos = $matchesPartSQL[0][1];
519                         //split the sql into a string before and after the from clause
520                         //we will use the columns being selected to construct the group by clause
521                         if ($from_pos>0 ) {
522                             $distinctSQLARRAY[0] = substr($matches_sql, 0, $from_pos);
523                             $distinctSQLARRAY[1] = substr($matches_sql, $from_pos);
524                             //get position of order by (if it exists) so we can strip it from the string
525                             $ob_pos = strpos($distinctSQLARRAY[1], "order by");
526                             if ($ob_pos) {
527                                 $distinctSQLARRAY[1] = substr($distinctSQLARRAY[1],0,$ob_pos);
528                             }
529
530                             // strip off last closing parentheses from the where clause
531                             $distinctSQLARRAY[1] = preg_replace('/\)\s$/',' ',$distinctSQLARRAY[1]);
532                         }
533
534                         $grpByStr = array();
535                         foreach ($sqlArray['SELECT'] as $record) {
536                             if ($record['expr_type'] == 'const') {
537                                 continue;
538                             }
539                             $grpByStr[] = trim($record['base_expr']);
540                         }
541                         $grpByStr = implode(', ', $grpByStr);
542                     }
543
544                     if (!empty($orderByMatch[3])) {
545                         //if there is a distinct clause, form query with rownumber after distinct
546                         if ($hasDistinct) {
547                             $newSQL = "SELECT TOP $count * FROM
548                                         (
549                                             SELECT ROW_NUMBER()
550                                                 OVER (ORDER BY " . preg_replace('/^' . $dist_str . '\s+/', '', $this->returnOrderBy($sql, $orderByMatch[3])) . ") AS row_number,
551                                                 count(*) counter, " . $distinctSQLARRAY[0] . "
552                                                 " . $distinctSQLARRAY[1] . "
553                                                 group by " . $grpByStr . "
554                                         ) AS a
555                                         WHERE row_number > $start";
556                         }
557                         else {
558                         $newSQL = "SELECT TOP $count * FROM
559                                     (
560                                         " . $matches[1] . " ROW_NUMBER()
561                                         OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]) . ") AS row_number,
562                                         " . $matches[2] . $orderByMatch[1]. "
563                                     ) AS a
564                                     WHERE row_number > $start";
565                         }
566                     }else{
567                         //if there is a distinct clause, form query with rownumber after distinct
568                         if ($hasDistinct) {
569                              $newSQL = "SELECT TOP $count * FROM
570                                             (
571                             SELECT ROW_NUMBER() OVER (ORDER BY ".$grpByStr.") AS row_number, count(*) counter, " . $distinctSQLARRAY[0] . "
572                                                         " . $distinctSQLARRAY[1] . "
573                                                     group by " . $grpByStr . "
574                                             )
575                                             AS a
576                                             WHERE row_number > $start";
577                         }
578                         else {
579                              $newSQL = "SELECT TOP $count * FROM
580                                            (
581                                   " . $matches[1] . " ROW_NUMBER() OVER (ORDER BY " . $sqlArray['FROM'][0]['alias'] . ".id) AS row_number, " . $matches[2] . $matches[3]. "
582                                            )
583                                            AS a
584                                            WHERE row_number > $start";
585                         }
586                     }
587                 }
588             }
589         }
590
591         $GLOBALS['log']->debug('Limit Query: ' . $newSQL);
592         if($execute) {
593             $result =  $this->query($newSQL, $dieOnError, $msg);
594             $this->dump_slow_queries($newSQL);
595             return $result;
596         } else {
597             return $newSQL;
598         }
599     }
600
601
602     /**
603      * Searches for begginning and ending characters.  It places contents into
604      * an array and replaces contents in original string.  This is used to account for use of
605      * nested functions while aliasing column names
606      *
607      * @param  string $p_sql     SQL statement
608      * @param  string $strip_beg Beginning character
609      * @param  string $strip_end Ending character
610      * @param  string $patt      Optional, pattern to
611      */
612     private function removePatternFromSQL($p_sql, $strip_beg, $strip_end, $patt = 'patt')
613     {
614         //strip all single quotes out
615         $count = substr_count ( $p_sql, $strip_beg);
616         $increment = 1;
617         if ($strip_beg != $strip_end)
618             $increment = 2;
619
620         $i=0;
621         $offset = 0;
622         $strip_array = array();
623         while ($i<$count && $offset<strlen($p_sql)) {
624             if ($offset > strlen($p_sql))
625             {
626                                 break;
627             }
628
629             $beg_sin = strpos($p_sql, $strip_beg, $offset);
630             if (!$beg_sin)
631             {
632                 break;
633             }
634             $sec_sin = strpos($p_sql, $strip_end, $beg_sin+1);
635             $strip_array[$patt.$i] = substr($p_sql, $beg_sin, $sec_sin - $beg_sin +1);
636             if ($increment > 1) {
637                 //we are in here because beginning and end patterns are not identical, so search for nesting
638                 $exists = strpos($strip_array[$patt.$i], $strip_beg );
639                 if ($exists>=0) {
640                     $nested_pos = (strrpos($strip_array[$patt.$i], $strip_beg ));
641                     $strip_array[$patt.$i] = substr($p_sql,$nested_pos+$beg_sin,$sec_sin - ($nested_pos+$beg_sin)+1);
642                     $p_sql = substr($p_sql, 0, $nested_pos+$beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
643                     $i = $i + 1;
644                     continue;
645                 }
646             }
647             $p_sql = substr($p_sql, 0, $beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
648             //move the marker up
649             $offset = $sec_sin+1;
650
651             $i = $i + 1;
652         }
653         $strip_array['sql_string'] = $p_sql;
654
655         return $strip_array;
656     }
657
658     /**
659      * adds a pattern
660      *
661      * @param  string $token
662      * @param  array  $pattern_array
663      * @return string
664      */
665         private function addPatternToSQL($token, array $pattern_array)
666     {
667         //strip all single quotes out
668         $pattern_array = array_reverse($pattern_array);
669
670         foreach ($pattern_array as $key => $replace) {
671             $token = str_replace( " ##".$key."## ", $replace,$token);
672         }
673
674         return $token;
675     }
676
677     /**
678      * gets an alias from the sql statement
679      *
680      * @param  string $sql
681      * @param  string $alias
682      * @return string
683      */
684         private function getAliasFromSQL($sql, $alias)
685     {
686         $matches = array();
687         preg_match('/^(.*SELECT)(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
688         //parse all single and double  quotes out of array
689         $sin_array = $this->removePatternFromSQL($matches[2], "'", "'","sin_");
690         $new_sql = array_pop($sin_array);
691         $dub_array = $this->removePatternFromSQL($new_sql, "\"", "\"","dub_");
692         $new_sql = array_pop($dub_array);
693
694         //search for parenthesis
695         $paren_array = $this->removePatternFromSQL($new_sql, "(", ")", "par_");
696         $new_sql = array_pop($paren_array);
697
698         //all functions should be removed now, so split the array on commas
699         $mstr_sql_array = explode(",", $new_sql);
700         foreach($mstr_sql_array as $token ) {
701             if (strpos($token, $alias)) {
702                 //found token, add back comments
703                 $token = $this->addPatternToSQL($token, $paren_array);
704                 $token = $this->addPatternToSQL($token, $dub_array);
705                 $token = $this->addPatternToSQL($token, $sin_array);
706
707                 //log and break out of this function
708                 return $token;
709             }
710         }
711         return null;
712     }
713
714
715     /**
716      * Finds the alias of the order by column, and then return the preceding column name
717      *
718      * @param  string $sql
719      * @param  string $orderMatch
720      * @return string
721      */
722     private function findColumnByAlias($sql, $orderMatch)
723     {
724         //change case to lowercase
725         $sql = strtolower($sql);
726         $patt = '/\s+'.trim($orderMatch).'\s*(,|from)/';
727
728         //check for the alias, it should contain comma, may contain space, \n, or \t
729         $matches = array();
730         preg_match($patt, $sql, $matches, PREG_OFFSET_CAPTURE);
731         $found_in_sql = isset($matches[0][1]) ? $matches[0][1] : false;
732
733
734         //set default for found variable
735         $found = $found_in_sql;
736
737         //if still no match found, then we need to parse through the string
738         if (!$found_in_sql){
739             //get count of how many times the match exists in string
740             $found_count = substr_count($sql, $orderMatch);
741             $i = 0;
742             $first_ = 0;
743             $len = strlen($orderMatch);
744             //loop through string as many times as there is a match
745             while ($found_count > $i) {
746                 //get the first match
747                 $found_in_sql = strpos($sql, $orderMatch,$first_);
748                 //make sure there was a match
749                 if($found_in_sql){
750                     //grab the next 2 individual characters
751                     $str_plusone = substr($sql,$found_in_sql + $len,1);
752                     $str_plustwo = substr($sql,$found_in_sql + $len+1,1);
753                     //if one of those characters is a comma, then we have our alias
754                     if ($str_plusone === "," || $str_plustwo === ","){
755                         //keep track of this position
756                         $found = $found_in_sql;
757                     }
758                 }
759                 //set the offset and increase the iteration counter
760                 $first_ = $found_in_sql+$len;
761                 $i = $i+1;
762             }
763         }
764         //return $found, defaults have been set, so if no match was found it will be a negative number
765         return $found;
766     }
767
768
769     /**
770      * Return the order by string to use in case the column has been aliased
771      *
772      * @param  string $sql
773      * @param  string $orig_order_match
774      * @return string
775      */
776     private function returnOrderBy($sql, $orig_order_match)
777     {
778         $sql = strtolower($sql);
779         $orig_order_match = trim($orig_order_match);
780         if (strpos($orig_order_match, ".") != 0)
781             //this has a tablename defined, pass in the order match
782             return $orig_order_match;
783
784         // If there is no ordering direction (ASC/DESC), use ASC by default
785         if (strpos($orig_order_match, " ") === false) {
786                 $orig_order_match .= " ASC";
787         }
788
789         //grab first space in order by
790         $firstSpace = strpos($orig_order_match, " ");
791
792         //split order by into column name and ascending/descending
793         $orderMatch = " " . strtolower(substr($orig_order_match, 0, $firstSpace));
794         $asc_desc = trim(substr($orig_order_match,$firstSpace));
795
796         //look for column name as an alias in sql string
797         $found_in_sql = $this->findColumnByAlias($sql, $orderMatch);
798
799         if (!$found_in_sql) {
800             //check if this column needs the tablename prefixed to it
801             $orderMatch = ".".trim($orderMatch);
802             $colMatchPos = strpos($sql, $orderMatch);
803             if ($colMatchPos !== false) {
804                 //grab sub string up to column name
805                 $containsColStr = substr($sql,0, $colMatchPos);
806                 //get position of first space, so we can grab table name
807                 $lastSpacePos = strrpos($containsColStr, " ");
808                 //use positions of column name, space before name, and length of column to find the correct column name
809                 $col_name = substr($sql, $lastSpacePos, $colMatchPos-$lastSpacePos+strlen($orderMatch));
810                                 //bug 25485. When sorting by a custom field in Account List and then pressing NEXT >, system gives an error
811                                 $containsCommaPos = strpos($col_name, ",");
812                                 if($containsCommaPos !== false) {
813                                         $col_name = substr($col_name, $containsCommaPos+1);
814                                 }
815                 //add the "asc/desc" order back
816                 $col_name = $col_name. " ". $asc_desc;
817
818                 //return column name
819                 return $col_name;
820             }
821             //break out of here, log this
822             $GLOBALS['log']->debug("No match was found for order by, pass string back untouched as: $orig_order_match");
823             return $orig_order_match;
824         }
825         else {
826             //if found, then parse and return
827             //grab string up to the aliased column
828             $GLOBALS['log']->debug("order by found, process sql string");
829
830             $psql = (trim($this->getAliasFromSQL($sql, $orderMatch )));
831             if (empty($psql))
832                 $psql = trim(substr($sql, 0, $found_in_sql));
833
834             //grab the last comma before the alias
835             preg_match('/\s+' . trim($orderMatch). '/', $psql, $match, PREG_OFFSET_CAPTURE);
836             $comma_pos = $match[0][1];
837             //substring between the comma and the alias to find the joined_table alias and column name
838             $col_name = substr($psql,0, $comma_pos);
839
840             //make sure the string does not have an end parenthesis
841             //and is not part of a function (i.e. "ISNULL(leads.last_name,'') as name"  )
842             //this is especially true for unified search from home screen
843
844             $alias_beg_pos = 0;
845             if(strpos($psql, " as "))
846                 $alias_beg_pos = strpos($psql, " as ");
847
848             // Bug # 44923 - This breaks the query and does not properly filter isnull
849             // as there are other functions such as ltrim and rtrim.
850             /* else if (strncasecmp($psql, 'isnull', 6) != 0)
851                 $alias_beg_pos = strpos($psql, " "); */
852
853             if ($alias_beg_pos > 0) {
854                 $col_name = substr($psql,0, $alias_beg_pos );
855             }
856             //add the "asc/desc" order back
857             $col_name = $col_name. " ". $asc_desc;
858
859             //pass in new order by
860             $GLOBALS['log']->debug("order by being returned is " . $col_name);
861             return $col_name;
862         }
863     }
864
865     /**
866      * Take in a string of the module and retrieve the correspondent table name
867      *
868      * @param  string $module_str module name
869      * @param  string $sql        SQL statement
870      * @return string table name
871      */
872     private function getTableNameFromModuleName($module_str, $sql)
873     {
874
875         global $beanList, $beanFiles;
876         $GLOBALS['log']->debug("Module being processed is " . $module_str);
877         //get the right module files
878         //the module string exists in bean list, then process bean for correct table name
879         //note that we exempt the reports module from this, as queries from reporting module should be parsed for
880         //correct table name.
881         if (($module_str != 'Reports' && $module_str != 'SavedReport') && isset($beanList[$module_str])  &&  isset($beanFiles[$beanList[$module_str]])){
882             //if the class is not already loaded, then load files
883             if (!class_exists($beanList[$module_str]))
884                 require_once($beanFiles[$beanList[$module_str]]);
885
886             //instantiate new bean
887             $module_bean = new $beanList[$module_str]();
888             //get table name from bean
889             $tbl_name = $module_bean->table_name;
890             //make sure table name is not just a blank space, or empty
891             $tbl_name = trim($tbl_name);
892
893             if(empty($tbl_name)){
894                 $GLOBALS['log']->debug("Could not find table name for module $module_str. ");
895                 $tbl_name = $module_str;
896             }
897         }
898         else {
899             //since the module does NOT exist in beanlist, then we have to parse the string
900             //and grab the table name from the passed in sql
901             $GLOBALS['log']->debug("Could not find table name from module in request, retrieve from passed in sql");
902             $tbl_name = $module_str;
903             $sql = strtolower($sql);
904
905             // Bug #45625 : Getting Multi-part identifier (reports.id) could not be bound error when navigating to next page in reprots in mssql
906             // there is cases when sql string is multiline string and it we cannot find " from " string in it
907             $sql = str_replace(array("\n", "\r"), " ", $sql);
908
909             //look for the location of the "from" in sql string
910             $fromLoc = strpos($sql," from " );
911             if ($fromLoc>0){
912                 //found from, substring from the " FROM " string in sql to end
913                 $tableEnd = substr($sql, $fromLoc+6);
914                 //We know that tablename will be next parameter after from, so
915                 //grab the next space after table name.
916                 // 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.
917                 $carriage_ret = strpos($tableEnd,"\n");
918                 $next_space = strpos($tableEnd," " );
919                 if ($carriage_ret < $next_space)
920                     $next_space = $carriage_ret;
921                 if ($next_space > 0) {
922                     $tbl_name= substr($tableEnd,0, $next_space);
923                     if(empty($tbl_name)){
924                         $GLOBALS['log']->debug("Could not find table name sql either, return $module_str. ");
925                         $tbl_name = $module_str;
926                     }
927                 }
928
929                 //grab the table, to see if it is aliased
930                 $aliasTableEnd = trim(substr($tableEnd, $next_space));
931                 $alias_space = strpos ($aliasTableEnd, " " );
932                 if ($alias_space > 0){
933                     $alias_tbl_name= substr($aliasTableEnd,0, $alias_space);
934                     strtolower($alias_tbl_name);
935                     if(empty($alias_tbl_name)
936                         || $alias_tbl_name == "where"
937                         || $alias_tbl_name == "inner"
938                         || $alias_tbl_name == "left"
939                         || $alias_tbl_name == "join"
940                         || $alias_tbl_name == "outer"
941                         || $alias_tbl_name == "right") {
942                         //not aliased, do nothing
943                     }
944                     elseif ($alias_tbl_name == "as") {
945                             //the next word is the table name
946                             $aliasTableEnd = trim(substr($aliasTableEnd, $alias_space));
947                             $alias_space = strpos ($aliasTableEnd, " " );
948                             if ($alias_space > 0) {
949                                 $alias_tbl_name= trim(substr($aliasTableEnd,0, $alias_space));
950                                 if (!empty($alias_tbl_name))
951                                     $tbl_name = $alias_tbl_name;
952                             }
953                     }
954                     else {
955                         //this is table alias
956                         $tbl_name = $alias_tbl_name;
957                     }
958                 }
959             }
960         }
961         //return table name
962         $GLOBALS['log']->debug("Table name for module $module_str is: ".$tbl_name);
963         return $tbl_name;
964     }
965
966
967         /**
968      * @see DBManager::getFieldsArray()
969      */
970         public function getFieldsArray($result, $make_lower_case = false)
971         {
972                 $field_array = array();
973
974                 if(! isset($result) || empty($result))
975             return 0;
976
977         $i = 0;
978         while ($i < mssql_num_fields($result)) {
979             $meta = mssql_fetch_field($result, $i);
980             if (!$meta)
981                 return 0;
982             if($make_lower_case==true)
983                 $meta->name = strtolower($meta->name);
984
985             $field_array[] = $meta->name;
986
987             $i++;
988         }
989
990         return $field_array;
991         }
992
993     /**
994      * @see DBManager::getAffectedRowCount()
995      */
996         public function getAffectedRowCount()
997     {
998         return $this->getOne("SELECT @@ROWCOUNT");
999     }
1000
1001         /**
1002          * @see DBManager::fetchRow()
1003          */
1004         public function fetchRow($result)
1005         {
1006                 if (empty($result))     return false;
1007
1008         $row = mssql_fetch_assoc($result);
1009         //MSSQL returns a space " " when a varchar column is empty ("") and not null.
1010         //We need to iterate through the returned row array and strip empty spaces
1011         if(!empty($row)){
1012             foreach($row as $key => $column) {
1013                //notice we only strip if one space is returned.  we do not want to strip
1014                //strings with intentional spaces (" foo ")
1015                if (!empty($column) && $column ==" ") {
1016                    $row[$key] = '';
1017                }
1018             }
1019         }
1020         return $row;
1021         }
1022
1023     /**
1024      * @see DBManager::quote()
1025      */
1026     public function quote($string)
1027     {
1028         if(is_array($string)) {
1029             return $this->arrayQuote($string);
1030         }
1031         return str_replace("'","''", $this->quoteInternal($string));
1032     }
1033
1034     /**
1035      * @see DBManager::tableExists()
1036      */
1037     public function tableExists($tableName)
1038     {
1039         $GLOBALS['log']->info("tableExists: $tableName");
1040
1041         $this->checkConnection();
1042         $result = $this->getOne(
1043             "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME=".$this->quoted($tableName));
1044
1045         return !empty($result);
1046     }
1047
1048     /**
1049      * Get tables like expression
1050      * @param $like string
1051      * @return array
1052      */
1053     public function tablesLike($like)
1054     {
1055         if ($this->getDatabase()) {
1056             $tables = array();
1057             $r = $this->query('SELECT TABLE_NAME tn FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE=\'BASE TABLE\' AND TABLE_NAME LIKE '.$this->quoted($like));
1058             if (!empty($r)) {
1059                 while ($a = $this->fetchByAssoc($r)) {
1060                     $row = array_values($a);
1061                                         $tables[]=$row[0];
1062                 }
1063                 return $tables;
1064             }
1065         }
1066         return false;
1067     }
1068
1069     /**
1070      * @see DBManager::getTablesArray()
1071      */
1072     public function getTablesArray()
1073     {
1074         $GLOBALS['log']->debug('MSSQL fetching table list');
1075
1076         if($this->getDatabase()) {
1077             $tables = array();
1078             $r = $this->query('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES');
1079             if (is_resource($r)) {
1080                 while ($a = $this->fetchByAssoc($r))
1081                     $tables[] = $a['TABLE_NAME'];
1082
1083                 return $tables;
1084             }
1085         }
1086
1087         return false; // no database available
1088     }
1089
1090
1091     /**
1092      * This call is meant to be used during install, when Full Text Search is enabled
1093      * Indexing would always occur after a fresh sql server install, so this code creates
1094      * a catalog and table with full text index.
1095      */
1096     public function full_text_indexing_setup()
1097     {
1098         $GLOBALS['log']->debug('MSSQL about to wakeup FTS');
1099
1100         if($this->getDatabase()) {
1101                 //create wakeup catalog
1102                 $FTSqry[] = "if not exists(  select * from sys.fulltext_catalogs where name ='wakeup_catalog' )
1103                 CREATE FULLTEXT CATALOG wakeup_catalog
1104                 ";
1105
1106                 //drop wakeup table if it exists
1107                 $FTSqry[] = "IF EXISTS(SELECT 'fts_wakeup' FROM sysobjects WHERE name = 'fts_wakeup' AND xtype='U')
1108                     DROP TABLE fts_wakeup
1109                 ";
1110                 //create wakeup table
1111                 $FTSqry[] = "CREATE TABLE fts_wakeup(
1112                     id varchar(36) NOT NULL CONSTRAINT pk_fts_wakeup_id PRIMARY KEY CLUSTERED (id ASC ),
1113                     body text NULL,
1114                     kb_index int IDENTITY(1,1) NOT NULL CONSTRAINT wakeup_fts_unique_idx UNIQUE NONCLUSTERED
1115                 )
1116                 ";
1117                 //create full text index
1118                  $FTSqry[] = "CREATE FULLTEXT INDEX ON fts_wakeup
1119                 (
1120                     body
1121                     Language 0X0
1122                 )
1123                 KEY INDEX wakeup_fts_unique_idx ON wakeup_catalog
1124                 WITH CHANGE_TRACKING AUTO
1125                 ";
1126
1127                 //insert dummy data
1128                 $FTSqry[] = "INSERT INTO fts_wakeup (id ,body)
1129                 VALUES ('".create_guid()."', 'SugarCRM Rocks' )";
1130
1131
1132                 //create queries to stop and restart indexing
1133                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup STOP POPULATION';
1134                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup DISABLE';
1135                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup ENABLE';
1136                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING MANUAL';
1137                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup START FULL POPULATION';
1138                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING AUTO';
1139
1140                 foreach($FTSqry as $q){
1141                     sleep(3);
1142                     $this->query($q);
1143                 }
1144                 $this->create_default_full_text_catalog();
1145         }
1146
1147         return false; // no database available
1148     }
1149
1150     protected $date_formats = array(
1151         '%Y-%m-%d' => 10,
1152         '%Y-%m' => 7,
1153         '%Y' => 4,
1154     );
1155
1156     /**
1157      * @see DBManager::convert()
1158      */
1159     public function convert($string, $type, array $additional_parameters = array())
1160     {
1161         // convert the parameters array into a comma delimited string
1162         if (!empty($additional_parameters)) {
1163             $additional_parameters_string = ','.implode(',',$additional_parameters);
1164         } else {
1165             $additional_parameters_string = '';
1166         }
1167         $all_parameters = $additional_parameters;
1168         if(is_array($string)) {
1169             $all_parameters = array_merge($string, $all_parameters);
1170         } elseif (!is_null($string)) {
1171             array_unshift($all_parameters, $string);
1172         }
1173
1174         switch (strtolower($type)) {
1175             case 'today':
1176                 return "GETDATE()";
1177             case 'left':
1178                 return "LEFT($string$additional_parameters_string)";
1179             case 'date_format':
1180                 if(!empty($additional_parameters[0]) && $additional_parameters[0][0] == "'") {
1181                     $additional_parameters[0] = trim($additional_parameters[0], "'");
1182                 }
1183                 if(!empty($additional_parameters) && isset($this->date_formats[$additional_parameters[0]])) {
1184                     $len = $this->date_formats[$additional_parameters[0]];
1185                     return "LEFT(CONVERT(varchar($len),". $string . ",120),$len)";
1186                 } else {
1187                    return "LEFT(CONVERT(varchar(10),". $string . ",120),10)";
1188                 }
1189             case 'ifnull':
1190                 if(empty($additional_parameters_string)) {
1191                     $additional_parameters_string = ",''";
1192                 }
1193                 return "ISNULL($string$additional_parameters_string)";
1194             case 'concat':
1195                 return implode("+",$all_parameters);
1196             case 'text2char':
1197                 return "CAST($string AS varchar(8000))";
1198             case 'quarter':
1199                 return "DATENAME(quarter, $string)";
1200             case "length":
1201                 return "LEN($string)";
1202             case 'month':
1203                 return "MONTH($string)";
1204             case 'add_date':
1205                 return "DATEADD({$additional_parameters[1]},{$additional_parameters[0]},$string)";
1206             case 'add_time':
1207                 return "DATEADD(hh, {$additional_parameters[0]}, DATEADD(mi, {$additional_parameters[1]}, $string))";
1208             case 'add_tz_offset' :
1209                 $getUserUTCOffset = $GLOBALS['timedate']->getUserUTCOffset();
1210                 $operation = $getUserUTCOffset < 0 ? '-' : '+';
1211                 return 'DATEADD(minute, ' . $operation . abs($getUserUTCOffset) . ', ' . $string. ')';
1212             case 'avg':
1213                 return "avg($string)";
1214         }
1215
1216         return "$string";
1217     }
1218
1219     /**
1220      * @see DBManager::fromConvert()
1221      */
1222     public function fromConvert($string, $type)
1223     {
1224         switch($type) {
1225             case 'datetimecombo':
1226             case 'datetime': return substr($string, 0,19);
1227             case 'date': return substr($string, 0, 10);
1228             case 'time': return substr($string, 11);
1229                 }
1230                 return $string;
1231     }
1232
1233     /**
1234      * @see DBManager::createTableSQLParams()
1235      */
1236         public function createTableSQLParams($tablename, $fieldDefs, $indices)
1237     {
1238         if (empty($tablename) || empty($fieldDefs))
1239             return '';
1240
1241         $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
1242         if (empty($columns))
1243             return '';
1244
1245         return "CREATE TABLE $tablename ($columns)";
1246     }
1247
1248     /**
1249      * Does this type represent text (i.e., non-varchar) value?
1250      * @param string $type
1251      */
1252     public function isTextType($type)
1253     {
1254         $type = strtolower($type);
1255         if(!isset($this->type_map[$type])) return false;
1256         return in_array($this->type_map[$type], array('ntext','text','image', 'nvarchar(max)'));
1257     }
1258
1259     /**
1260      * Return representation of an empty value depending on type
1261      * @param string $type
1262      */
1263     public function emptyValue($type)
1264     {
1265         $ctype = $this->getColumnType($type);
1266         if($ctype == "datetime") {
1267             return $this->convert($this->quoted("1970-01-01 00:00:00"), "datetime");
1268         }
1269         if($ctype == "date") {
1270             return $this->convert($this->quoted("1970-01-01"), "datetime");
1271         }
1272         if($ctype == "time") {
1273             return $this->convert($this->quoted("00:00:00"), "time");
1274         }
1275         return parent::emptyValue($type);
1276     }
1277
1278     public function renameColumnSQL($tablename, $column, $newname)
1279     {
1280         return "SP_RENAME '$tablename.$column', '$newname', 'COLUMN'";
1281     }
1282
1283     /**
1284      * Returns the SQL Alter table statment
1285      *
1286      * MSSQL has a quirky T-SQL alter table syntax. Pay special attention to the
1287      * modify operation
1288      * @param string $action
1289      * @param array  $def
1290      * @param bool   $ignorRequired
1291      * @param string $tablename
1292      */
1293     protected function alterSQLRep($action, array $def, $ignoreRequired, $tablename)
1294     {
1295         switch($action){
1296         case 'add':
1297              $f_def=$this->oneColumnSQLRep($def, $ignoreRequired,$tablename,false);
1298             return "ADD " . $f_def;
1299             break;
1300         case 'drop':
1301             return "DROP COLUMN " . $def['name'];
1302             break;
1303         case 'modify':
1304             //You cannot specify a default value for a column for MSSQL
1305             $f_def  = $this->oneColumnSQLRep($def, $ignoreRequired,$tablename, true);
1306             $f_stmt = "ALTER COLUMN ".$f_def['name'].' '.$f_def['colType'].' '.
1307                         $f_def['required'].' '.$f_def['auto_increment']."\n";
1308             if (!empty( $f_def['default']))
1309                 $f_stmt .= " ALTER TABLE " . $tablename .  " ADD  ". $f_def['default'] . " FOR " . $def['name'];
1310             return $f_stmt;
1311             break;
1312         default:
1313             return '';
1314         }
1315     }
1316
1317     /**
1318      * @see DBManager::changeColumnSQL()
1319      *
1320      * MSSQL uses a different syntax than MySQL for table altering that is
1321      * not quite as simplistic to implement...
1322      */
1323     protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
1324     {
1325         $sql=$sql2='';
1326         $constraints = $this->get_field_default_constraint_name($tablename);
1327         $columns = array();
1328         if ($this->isFieldArray($fieldDefs)) {
1329             foreach ($fieldDefs as $def)
1330                 {
1331                         //if the column is being modified drop the default value
1332                         //constraint if it exists. alterSQLRep will add the constraint back
1333                         if (!empty($constraints[$def['name']])) {
1334                                 $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$def['name']];
1335                         }
1336                         //check to see if we need to drop related indexes before the alter
1337                         $indices = $this->get_indices($tablename);
1338                 foreach ( $indices as $index ) {
1339                     if ( in_array($def['name'],$index['fields']) ) {
1340                         $sql  .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
1341                         $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
1342                     }
1343                 }
1344
1345                         $columns[] = $this->alterSQLRep($action, $def, $ignoreRequired,$tablename);
1346                 }
1347         }
1348         else {
1349             //if the column is being modified drop the default value
1350                 //constraint if it exists. alterSQLRep will add the constraint back
1351                 if (!empty($constraints[$fieldDefs['name']])) {
1352                         $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$fieldDefs['name']];
1353                 }
1354                 //check to see if we need to drop related indexes before the alter
1355             $indices = $this->get_indices($tablename);
1356             foreach ( $indices as $index ) {
1357                 if ( in_array($fieldDefs['name'],$index['fields']) ) {
1358                     $sql  .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
1359                     $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
1360                 }
1361             }
1362
1363
1364                 $columns[] = $this->alterSQLRep($action, $fieldDefs, $ignoreRequired,$tablename);
1365         }
1366
1367         $columns = implode(", ", $columns);
1368         $sql .= " ALTER TABLE $tablename $columns " . $sql2;
1369
1370         return $sql;
1371     }
1372
1373     protected function setAutoIncrement($table, $field_name)
1374     {
1375                 return "identity(1,1)";
1376         }
1377
1378     /**
1379      * @see DBManager::setAutoIncrementStart()
1380      */
1381     public function setAutoIncrementStart($table, $field_name, $start_value)
1382     {
1383         if($start_value > 1)
1384             $start_value -= 1;
1385                 $this->query("DBCC CHECKIDENT ('$table', RESEED, $start_value) WITH NO_INFOMSGS");
1386         return true;
1387     }
1388
1389         /**
1390      * @see DBManager::getAutoIncrement()
1391      */
1392     public function getAutoIncrement($table, $field_name)
1393     {
1394                 $result = $this->getOne("select IDENT_CURRENT('$table') + IDENT_INCR ( '$table' ) as 'Auto_increment'");
1395         return $result;
1396     }
1397
1398     /**
1399      * @see DBManager::get_indices()
1400      */
1401     public function get_indices($tableName)
1402     {
1403         //find all unique indexes and primary keys.
1404         $query = <<<EOSQL
1405 SELECT sys.tables.object_id, sys.tables.name as table_name, sys.columns.name as column_name,
1406                 sys.indexes.name as index_name, sys.indexes.is_unique, sys.indexes.is_primary_key
1407             FROM sys.tables, sys.indexes, sys.index_columns, sys.columns
1408             WHERE (sys.tables.object_id = sys.indexes.object_id
1409                     AND sys.tables.object_id = sys.index_columns.object_id
1410                     AND sys.tables.object_id = sys.columns.object_id
1411                     AND sys.indexes.index_id = sys.index_columns.index_id
1412                     AND sys.index_columns.column_id = sys.columns.column_id)
1413                 AND sys.tables.name = '$tableName'
1414 EOSQL;
1415         $result = $this->query($query);
1416
1417         $indices = array();
1418         while (($row=$this->fetchByAssoc($result)) != null) {
1419             $index_type = 'index';
1420             if ($row['is_primary_key'] == '1')
1421                 $index_type = 'primary';
1422             elseif ($row['is_unique'] == 1 )
1423                 $index_type = 'unique';
1424             $name = strtolower($row['index_name']);
1425             $indices[$name]['name']     = $name;
1426             $indices[$name]['type']     = $index_type;
1427             $indices[$name]['fields'][] = strtolower($row['column_name']);
1428         }
1429         return $indices;
1430     }
1431
1432     /**
1433      * @see DBManager::get_columns()
1434      */
1435     public function get_columns($tablename)
1436     {
1437         //find all unique indexes and primary keys.
1438         $result = $this->query("sp_columns $tablename");
1439
1440         $columns = array();
1441         while (($row=$this->fetchByAssoc($result)) !=null) {
1442             $column_name = strtolower($row['COLUMN_NAME']);
1443             $columns[$column_name]['name']=$column_name;
1444             $columns[$column_name]['type']=strtolower($row['TYPE_NAME']);
1445             if ( $row['TYPE_NAME'] == 'decimal' ) {
1446                 $columns[$column_name]['len']=strtolower($row['PRECISION']);
1447                 $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
1448             }
1449                         elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) )
1450                                 $columns[$column_name]['len']=strtolower($row['PRECISION']);
1451             elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) )
1452                 $columns[$column_name]['len']=strtolower($row['LENGTH']);
1453             if ( stristr($row['TYPE_NAME'],'identity') ) {
1454                 $columns[$column_name]['auto_increment'] = '1';
1455                 $columns[$column_name]['type']=str_replace(' identity','',strtolower($row['TYPE_NAME']));
1456             }
1457
1458             if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI')))
1459                 $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
1460
1461             $column_def = 1;
1462             if ( strtolower($tablename) == 'relationships' ) {
1463                 $column_def = $this->getOne("select cdefault from syscolumns where id = object_id('relationships') and name = '$column_name'");
1464             }
1465             if ( $column_def != 0 && ($row['COLUMN_DEF'] != null)) {    // NOTE Not using !empty as an empty string may be a viable default value.
1466                 $matches = array();
1467                 $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'],ENT_QUOTES);
1468                 if ( preg_match('/\([\(|\'](.*)[\)|\']\)/i',$row['COLUMN_DEF'],$matches) )
1469                     $columns[$column_name]['default'] = $matches[1];
1470                 elseif ( preg_match('/\(N\'(.*)\'\)/i',$row['COLUMN_DEF'],$matches) )
1471                     $columns[$column_name]['default'] = $matches[1];
1472                 else
1473                     $columns[$column_name]['default'] = $row['COLUMN_DEF'];
1474             }
1475         }
1476         return $columns;
1477     }
1478
1479
1480     /**
1481      * Get FTS catalog name for current DB
1482      */
1483     protected function ftsCatalogName()
1484     {
1485         if(isset($this->connectOptions['db_name'])) {
1486             return $this->connectOptions['db_name']."_fts_catalog";
1487         }
1488         return 'sugar_fts_catalog';
1489     }
1490
1491     /**
1492      * @see DBManager::add_drop_constraint()
1493      */
1494     public function add_drop_constraint($table, $definition, $drop = false)
1495     {
1496         $type         = $definition['type'];
1497         $fields       = is_array($definition['fields'])?implode(',',$definition['fields']):$definition['fields'];
1498         $name         = $definition['name'];
1499         $sql          = '';
1500
1501         switch ($type){
1502         // generic indices
1503         case 'index':
1504         case 'alternate_key':
1505             if ($drop)
1506                 $sql = "DROP INDEX {$name} ON {$table}";
1507             else
1508                 $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
1509             break;
1510         case 'clustered':
1511             if ($drop)
1512                 $sql = "DROP INDEX {$name} ON {$table}";
1513             else
1514                 $sql = "CREATE CLUSTERED INDEX $name ON $table ($fields)";
1515             break;
1516             // constraints as indices
1517         case 'unique':
1518             if ($drop)
1519                 $sql = "ALTER TABLE {$table} DROP CONSTRAINT $name";
1520             else
1521                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE ({$fields})";
1522             break;
1523         case 'primary':
1524             if ($drop)
1525                 $sql = "ALTER TABLE {$table} DROP CONSTRAINT {$name}";
1526             else
1527                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} PRIMARY KEY ({$fields})";
1528             break;
1529         case 'foreign':
1530             if ($drop)
1531                 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
1532             else
1533                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name}  FOREIGN KEY ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignFields']})";
1534             break;
1535         case 'fulltext':
1536             if ($this->full_text_indexing_enabled() && $drop) {
1537                 $sql = "DROP FULLTEXT INDEX ON {$table}";
1538             } elseif ($this->full_text_indexing_enabled()) {
1539                 $catalog_name=$this->ftsCatalogName();
1540                 if ( isset($definition['catalog_name']) && $definition['catalog_name'] != 'default')
1541                     $catalog_name = $definition['catalog_name'];
1542
1543                 $language = "Language 1033";
1544                 if (isset($definition['language']) && !empty($definition['language']))
1545                     $language = "Language " . $definition['language'];
1546
1547                 $key_index = $definition['key_index'];
1548
1549                 $change_tracking = "auto";
1550                 if (isset($definition['change_tracking']) && !empty($definition['change_tracking']))
1551                     $change_tracking = $definition['change_tracking'];
1552
1553                 $sql = " CREATE FULLTEXT INDEX ON $table ($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
1554             }
1555             break;
1556         }
1557         return $sql;
1558     }
1559
1560     /**
1561      * Returns true if Full Text Search is installed
1562      *
1563      * @return bool
1564      */
1565     public function full_text_indexing_installed()
1566     {
1567         $ftsChckRes = $this->getOne("SELECT FULLTEXTSERVICEPROPERTY('IsFulltextInstalled') as fts");
1568         return !empty($ftsChckRes);
1569     }
1570
1571     /**
1572      * @see DBManager::full_text_indexing_enabled()
1573      */
1574     protected function full_text_indexing_enabled($dbname = null)
1575     {
1576         // check to see if we already have install setting in session
1577         if(!isset($_SESSION['IsFulltextInstalled']))
1578             $_SESSION['IsFulltextInstalled'] = $this->full_text_indexing_installed();
1579
1580         // check to see if FTS Indexing service is installed
1581         if(empty($_SESSION['IsFulltextInstalled']))
1582             return false;
1583
1584         // grab the dbname if it was not passed through
1585                 if (empty($dbname)) {
1586                         global $sugar_config;
1587                         $dbname = $sugar_config['dbconfig']['db_name'];
1588                 }
1589         //we already know that Indexing service is installed, now check
1590         //to see if it is enabled
1591                 $res = $this->getOne("SELECT DATABASEPROPERTY('$dbname', 'IsFulltextEnabled') ftext");
1592         return !empty($res);
1593         }
1594
1595     /**
1596      * Creates default full text catalog
1597      */
1598         protected function create_default_full_text_catalog()
1599     {
1600                 if ($this->full_text_indexing_enabled()) {
1601                     $catalog = $this->ftsCatalogName();
1602             $GLOBALS['log']->debug("Creating the default catalog for full-text indexing, $catalog");
1603
1604             //drop catalog if exists.
1605                         $ret = $this->query("
1606                 if not exists(
1607                     select *
1608                         from sys.fulltext_catalogs
1609                         where name ='$catalog'
1610                         )
1611                 CREATE FULLTEXT CATALOG $catalog");
1612
1613                         if (empty($ret)) {
1614                                 $GLOBALS['log']->error("Error creating default full-text catalog, $catalog");
1615                         }
1616                 }
1617         }
1618
1619     /**
1620      * Function returns name of the constraint automatically generated by sql-server.
1621      * We request this for default, primary key, required
1622      *
1623      * @param  string $table
1624      * @param  string $column
1625      * @return string
1626      */
1627         private function get_field_default_constraint_name($table, $column = null)
1628     {
1629         static $results = array();
1630
1631         if ( empty($column) && isset($results[$table]) )
1632             return $results[$table];
1633
1634         $query = <<<EOQ
1635 select s.name, o.name, c.name dtrt, d.name ctrt
1636     from sys.default_constraints as d
1637         join sys.objects as o
1638             on o.object_id = d.parent_object_id
1639         join sys.columns as c
1640             on c.object_id = o.object_id and c.column_id = d.parent_column_id
1641         join sys.schemas as s
1642             on s.schema_id = o.schema_id
1643     where o.name = '$table'
1644 EOQ;
1645         if ( !empty($column) )
1646             $query .= " and c.name = '$column'";
1647         $res = $this->query($query);
1648         if ( !empty($column) ) {
1649             $row = $this->fetchByAssoc($res);
1650             if (!empty($row))
1651                 return $row['ctrt'];
1652         }
1653         else {
1654             $returnResult = array();
1655             while ( $row = $this->fetchByAssoc($res) )
1656                 $returnResult[$row['dtrt']] = $row['ctrt'];
1657             $results[$table] = $returnResult;
1658             return $returnResult;
1659         }
1660
1661         return null;
1662         }
1663
1664     /**
1665      * @see DBManager::massageFieldDef()
1666      */
1667     public function massageFieldDef(&$fieldDef, $tablename)
1668     {
1669         parent::massageFieldDef($fieldDef,$tablename);
1670
1671         if ($fieldDef['type'] == 'int')
1672             $fieldDef['len'] = '4';
1673
1674         if(empty($fieldDef['len']))
1675         {
1676             switch($fieldDef['type']) {
1677                 case 'bit'      :
1678                 case 'bool'     : $fieldDef['len'] = '1'; break;
1679                 case 'smallint' : $fieldDef['len'] = '2'; break;
1680                 case 'float'    : $fieldDef['len'] = '8'; break;
1681                 case 'varchar'  :
1682                 case 'nvarchar' :
1683                                   $fieldDef['len'] = $this->isTextType($fieldDef['dbType']) ? 'max' : '255';
1684                                   break;
1685                 case 'image'    : $fieldDef['len'] = '2147483647'; break;
1686                 case 'ntext'    : $fieldDef['len'] = '2147483646'; break;   // Note: this is from legacy code, don't know if this is correct
1687             }
1688         }
1689         if($fieldDef['type'] == 'decimal'
1690            && empty($fieldDef['precision'])
1691            && !strpos($fieldDef['len'], ','))
1692         {
1693              $fieldDef['len'] .= ',0'; // Adding 0 precision if it is not specified
1694         }
1695
1696         if(empty($fieldDef['default'])
1697             && in_array($fieldDef['type'],array('bit','bool')))
1698         {
1699             $fieldDef['default'] = '0';
1700         }
1701                 if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']) )
1702                         $fieldDef['default'] = '';
1703 //        if ($fieldDef['type'] == 'bit' && empty($fieldDef['len']) )
1704 //            $fieldDef['len'] = '1';
1705 //              if ($fieldDef['type'] == 'bool' && empty($fieldDef['len']) )
1706 //            $fieldDef['len'] = '1';
1707 //        if ($fieldDef['type'] == 'float' && empty($fieldDef['len']) )
1708 //            $fieldDef['len'] = '8';
1709 //        if ($fieldDef['type'] == 'varchar' && empty($fieldDef['len']) )
1710 //            $fieldDef['len'] = '255';
1711 //              if ($fieldDef['type'] == 'nvarchar' && empty($fieldDef['len']) )
1712 //            $fieldDef['len'] = '255';
1713 //        if ($fieldDef['type'] == 'image' && empty($fieldDef['len']) )
1714 //            $fieldDef['len'] = '2147483647';
1715 //        if ($fieldDef['type'] == 'ntext' && empty($fieldDef['len']) )
1716 //            $fieldDef['len'] = '2147483646';
1717 //        if ($fieldDef['type'] == 'smallint' && empty($fieldDef['len']) )
1718 //            $fieldDef['len'] = '2';
1719 //        if ($fieldDef['type'] == 'bit' && empty($fieldDef['default']) )
1720 //            $fieldDef['default'] = '0';
1721 //              if ($fieldDef['type'] == 'bool' && empty($fieldDef['default']) )
1722 //            $fieldDef['default'] = '0';
1723
1724     }
1725
1726     /**
1727      * @see DBManager::oneColumnSQLRep()
1728      */
1729     protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
1730     {
1731         //Bug 25814
1732                 if(isset($fieldDef['name'])){
1733                     $colType = $this->getFieldType($fieldDef);
1734                 if(stristr($this->getFieldType($fieldDef), 'decimal') && isset($fieldDef['len'])){
1735                                 $fieldDef['len'] = min($fieldDef['len'],38);
1736                         }
1737                     //bug: 39690 float(8) is interpreted as real and this generates a diff when doing repair
1738                         if(stristr($colType, 'float') && isset($fieldDef['len']) && $fieldDef['len'] == 8){
1739                                 unset($fieldDef['len']);
1740                         }
1741                 }
1742
1743                 // always return as array for post-processing
1744                 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
1745
1746                 // Bug 24307 - Don't add precision for float fields.
1747                 if ( stristr($ref['colType'],'float') )
1748                         $ref['colType'] = preg_replace('/(,\d+)/','',$ref['colType']);
1749
1750         if ( $return_as_array )
1751             return $ref;
1752         else
1753             return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
1754         }
1755
1756     /**
1757      * Saves changes to module's audit table
1758      *
1759      * @param object $bean    Sugarbean instance
1760      * @param array  $changes changes
1761      */
1762     public function save_audit_records(SugarBean $bean, $changes)
1763         {
1764                 //Bug 25078 fixed by Martin Hu: sqlserver haven't 'date' type, trim extra "00:00:00"
1765                 if($changes['data_type'] == 'date'){
1766                         $changes['before'] = str_replace(' 00:00:00','',$changes['before']);
1767                 }
1768                 parent::save_audit_records($bean,$changes);
1769         }
1770
1771     /**
1772      * Disconnects from the database
1773      *
1774      * Also handles any cleanup needed
1775      */
1776     public function disconnect()
1777     {
1778         $GLOBALS['log']->debug('Calling Mssql::disconnect()');
1779         if(!empty($this->database)){
1780             $this->freeResult();
1781             mssql_close($this->database);
1782             $this->database = null;
1783         }
1784     }
1785
1786     /**
1787      * @see DBManager::freeDbResult()
1788      */
1789     protected function freeDbResult($dbResult)
1790     {
1791         if(!empty($dbResult))
1792             mssql_free_result($dbResult);
1793     }
1794
1795         /**
1796          * (non-PHPdoc)
1797          * @see DBManager::lastDbError()
1798          */
1799     public function lastDbError()
1800     {
1801         $sqlmsg = mssql_get_last_message();
1802         if(empty($sqlmsg)) return false;
1803         global $app_strings;
1804         if (empty($app_strings)
1805                     or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
1806                         or !isset($app_strings['ERR_MSSQL_WARNING']) ) {
1807         //ignore the message from sql-server if $app_strings array is empty. This will happen
1808         //only if connection if made before language is set.
1809                     return false;
1810         }
1811
1812         $sqlpos = strpos($sqlmsg, 'Changed database context to');
1813         $sqlpos2 = strpos($sqlmsg, 'Warning:');
1814         $sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
1815         if ( $sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false ) {
1816             return false;
1817         } else {
1818                 global $app_strings;
1819             //ERR_MSSQL_DB_CONTEXT: localized version of 'Changed database context to' message
1820             if (empty($app_strings) or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])) {
1821                 //ignore the message from sql-server if $app_strings array is empty. This will happen
1822                 //only if connection if made before languge is set.
1823                 $GLOBALS['log']->debug("Ignoring this database message: " . $sqlmsg);
1824                 return false;
1825             }
1826             else {
1827                 $sqlpos = strpos($sqlmsg, $app_strings['ERR_MSSQL_DB_CONTEXT']);
1828                 if ( $sqlpos !== false )
1829                     return false;
1830             }
1831         }
1832
1833         if ( strlen($sqlmsg) > 2 ) {
1834                 return "SQL Server error: " . $sqlmsg;
1835         }
1836
1837         return false;
1838     }
1839
1840     /**
1841      * (non-PHPdoc)
1842      * @see DBManager::getDbInfo()
1843      */
1844     public function getDbInfo()
1845     {
1846         return array("version" => $this->version());
1847     }
1848
1849     /**
1850      * (non-PHPdoc)
1851      * @see DBManager::validateQuery()
1852      */
1853     public function validateQuery($query)
1854     {
1855         if(!$this->isSelect($query)) {
1856             return false;
1857         }
1858         $this->query("SET SHOWPLAN_TEXT ON");
1859         $res = $this->getOne($query);
1860         $this->query("SET SHOWPLAN_TEXT OFF");
1861         return !empty($res);
1862     }
1863
1864     /**
1865      * This is a utility function to prepend the "N" character in front of SQL values that are
1866      * surrounded by single quotes.
1867      *
1868      * @param  $sql string SQL statement
1869      * @return string SQL statement with single quote values prepended with "N" character for nvarchar columns
1870      */
1871     protected function _appendN($sql)
1872     {
1873         // If there are no single quotes, don't bother, will just assume there is no character data
1874         if (strpos($sql, "'") === false)
1875             return $sql;
1876
1877         // Flag if there are odd number of single quotes, just continue without trying to append N
1878         if ((substr_count($sql, "'") & 1)) {
1879             $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
1880             return $sql;
1881         }
1882
1883         //The only location of three subsequent ' will be at the beginning or end of a value.
1884         $sql = preg_replace('/(?<!\')(\'{3})(?!\')/', "'<@#@#@PAIR@#@#@>", $sql);
1885
1886         // Remove any remaining '' and do not parse... replace later (hopefully we don't even have any)
1887         $pairs        = array();
1888         $regexp       = '/(\'{2})/';
1889         $pair_matches = array();
1890         preg_match_all($regexp, $sql, $pair_matches);
1891         if ($pair_matches) {
1892             foreach (array_unique($pair_matches[0]) as $key=>$value) {
1893                 $pairs['<@PAIR-'.$key.'@>'] = $value;
1894             }
1895             if (!empty($pairs)) {
1896                 $sql = str_replace($pairs, array_keys($pairs), $sql);
1897             }
1898         }
1899
1900         $regexp  = "/(N?'.+?')/is";
1901         $matches = array();
1902         preg_match_all($regexp, $sql, $matches);
1903         $replace = array();
1904         if (!empty($matches)) {
1905             foreach ($matches[0] as $value) {
1906                 // We are assuming that all nvarchar columns are no more than 200 characters in length
1907                 // One problem we face is the image column type in reports which cannot accept nvarchar data
1908                 if (!empty($value) && !is_numeric(trim(str_replace(array("'", ","), "", $value))) && !preg_match('/^\'[\,]\'$/', $value)) {
1909                     $replace[$value] = 'N' . trim($value, "N");
1910                 }
1911             }
1912         }
1913
1914         if (!empty($replace))
1915             $sql = str_replace(array_keys($replace), $replace, $sql);
1916
1917         if (!empty($pairs))
1918             $sql = str_replace(array_keys($pairs), $pairs, $sql);
1919
1920         if(strpos($sql, "<@#@#@PAIR@#@#@>"))
1921             $sql = str_replace(array('<@#@#@PAIR@#@#@>'), array("''"), $sql);
1922
1923         return $sql;
1924     }
1925
1926     /**
1927      * Quote SQL Server search term
1928      * @param string $term
1929      * @return string
1930      */
1931     protected function quoteTerm($term)
1932     {
1933         $term = str_replace("%", "*", $term); // Mssql wildcard is *
1934         return '"'.str_replace('"', '', $term).'"';
1935     }
1936
1937     /**
1938      * Generate fulltext query from set of terms
1939      * @param string $fields Field to search against
1940      * @param array $terms Search terms that may be or not be in the result
1941      * @param array $must_terms Search terms that have to be in the result
1942      * @param array $exclude_terms Search terms that have to be not in the result
1943      */
1944     public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1945     {
1946         $condition = $or_condition = array();
1947         foreach($must_terms as $term) {
1948             $condition[] = $this->quoteTerm($term);
1949         }
1950
1951         foreach($terms as $term) {
1952             $or_condition[] = $this->quoteTerm($term);
1953         }
1954
1955         if(!empty($or_condition)) {
1956             $condition[] = "(".join(" | ", $or_condition).")";
1957         }
1958
1959         foreach($exclude_terms as $term) {
1960             $condition[] = " NOT ".$this->quoteTerm($term);
1961         }
1962         $condition = $this->quoted(join(" AND ",$condition));
1963         return "CONTAINS($field, $condition)";
1964     }
1965
1966     /**
1967      * Check if certain database exists
1968      * @param string $dbname
1969      */
1970     public function dbExists($dbname)
1971     {
1972         $db = $this->getOne("SELECT name FROM master..sysdatabases WHERE name = N".$this->quoted($dbname));
1973         return !empty($db);
1974     }
1975
1976     /**
1977      * Select database
1978      * @param string $dbname
1979      */
1980     protected function selectDb($dbname)
1981     {
1982         return mssql_select_db($dbname);
1983     }
1984
1985     /**
1986      * Check if certain DB user exists
1987      * @param string $username
1988      */
1989     public function userExists($username)
1990     {
1991         $this->selectDb("master");
1992         $user = $this->getOne("select count(*) from sys.sql_logins where name =".$this->quoted($username));
1993         // FIXME: go back to the original DB
1994         return !empty($user);
1995     }
1996
1997     /**
1998      * Create DB user
1999      * @param string $database_name
2000      * @param string $host_name
2001      * @param string $user
2002      * @param string $password
2003      */
2004     public function createDbUser($database_name, $host_name, $user, $password)
2005     {
2006         $qpassword = $this->quote($password);
2007         $this->selectDb($database_name);
2008         $this->query("CREATE LOGIN $user WITH PASSWORD = '$qpassword'", true);
2009         $this->query("CREATE USER $user FOR LOGIN $user", true);
2010         $this->query("EXEC sp_addRoleMember 'db_ddladmin ', '$user'", true);
2011         $this->query("EXEC sp_addRoleMember 'db_datareader','$user'", true);
2012         $this->query("EXEC sp_addRoleMember 'db_datawriter','$user'", true);
2013     }
2014
2015     /**
2016      * Create a database
2017      * @param string $dbname
2018      */
2019     public function createDatabase($dbname)
2020     {
2021         return $this->query("CREATE DATABASE $dbname", true);
2022     }
2023
2024     /**
2025      * Drop a database
2026      * @param string $dbname
2027      */
2028     public function dropDatabase($dbname)
2029     {
2030         return $this->query("DROP DATABASE $dbname", true);
2031     }
2032
2033     /**
2034      * Check if this driver can be used
2035      * @return bool
2036      */
2037     public function valid()
2038     {
2039         return function_exists("mssql_connect");
2040     }
2041
2042     /**
2043      * Check if this DB name is valid
2044      *
2045      * @param string $name
2046      * @return bool
2047      */
2048     public function isDatabaseNameValid($name)
2049     {
2050         // No funny chars, does not begin with number
2051         return preg_match('/^[0-9#@]+|[\"\'\*\/\\?\:\\<\>\-\ \&\!\(\)\[\]\{\}\;\,\.\`\~\|\\\\]+/', $name)==0;
2052     }
2053
2054     public function installConfig()
2055     {
2056         return array(
2057                 'LBL_DBCONFIG_MSG3' =>  array(
2058                 "setup_db_database_name" => array("label" => 'LBL_DBCONF_DB_NAME', "required" => true),
2059             ),
2060             'LBL_DBCONFIG_MSG2' =>  array(
2061                 "setup_db_host_name" => array("label" => 'LBL_DBCONF_HOST_NAME', "required" => true),
2062                 "setup_db_host_instance" => array("label" => 'LBL_DBCONF_HOST_INSTANCE'),
2063             ),
2064             'LBL_DBCONF_TITLE_USER_INFO' => array(),
2065             'LBL_DBCONFIG_B_MSG1' => array(
2066                 "setup_db_admin_user_name" => array("label" => 'LBL_DBCONF_DB_ADMIN_USER', "required" => true),
2067                 "setup_db_admin_password" => array("label" => 'LBL_DBCONF_DB_ADMIN_PASSWORD', "type" => "password"),
2068             )
2069         );
2070     }
2071
2072     /**
2073      * Returns a DB specific FROM clause which can be used to select against functions.
2074      * Note that depending on the database that this may also be an empty string.
2075      * @return string
2076      */
2077     public function getFromDummyTable()
2078     {
2079         return '';
2080     }
2081
2082     /**
2083      * Returns a DB specific piece of SQL which will generate GUID (UUID)
2084      * This string can be used in dynamic SQL to do multiple inserts with a single query.
2085      * I.e. generate a unique Sugar id in a sub select of an insert statement.
2086      * @return string
2087      */
2088
2089         public function getGuidSQL()
2090     {
2091         return 'NEWID()';
2092     }
2093 }