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