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