]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/database/MssqlManager.php
Release 6.2.0RC1
[Github/sugarcrm.git] / include / database / MssqlManager.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40 * Description: This file handles the Data base functionality for the application.
41 * It acts as the DB abstraction layer for the application. It depends on helper classes
42 * which generate the necessary SQL. This sql is then passed to PEAR DB classes.
43 * The helper class is chosen in DBManagerFactory, which is driven by 'db_type' in 'dbconfig' under config.php.
44 *
45 * All the functions in this class will work with any bean which implements the meta interface.
46 * The passed bean is passed to helper class which uses these functions to generate correct sql.
47 *
48 * The meta interface has the following functions:
49 * getTableName()                        Returns table name of the object.
50 * getFieldDefinitions()         Returns a collection of field definitions in order.
51 * getFieldDefintion(name)               Return field definition for the field.
52 * getFieldValue(name)           Returns the value of the field identified by name.
53 *                               If the field is not set, the function will return boolean FALSE.
54 * getPrimaryFieldDefinition()   Returns the field definition for primary key
55 *
56 * The field definition is an array with the following keys:
57 *
58 * name          This represents name of the field. This is a required field.
59 * type          This represents type of the field. This is a required field and valid values are:
60 *               int
61 *               long
62 *               varchar
63 *               text
64 *               date
65 *               datetime
66 *               double
67 *               float
68 *               uint
69 *               ulong
70 *               time
71 *               short
72 *               enum
73 * length        This is used only when the type is varchar and denotes the length of the string.
74 *                       The max value is 255.
75 * enumvals  This is a list of valid values for an enum separated by "|".
76 *                       It is used only if the type is ?enum?;
77 * required      This field dictates whether it is a required value.
78 *                       The default value is ?FALSE?.
79 * isPrimary     This field identifies the primary key of the table.
80 *                       If none of the fields have this flag set to ?TRUE?,
81 *                       the first field definition is assume to be the primary key.
82 *                       Default value for this field is ?FALSE?.
83 * default       This field sets the default value for the field definition.
84 *
85 *
86 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
87 * All Rights Reserved.
88 * Contributor(s): ______________________________________..
89 ********************************************************************************/
90
91 class MssqlManager extends DBManager
92 {
93     /**
94      * @see DBManager::$dbType
95      */
96     public $dbType = 'mssql';
97
98         /**
99      * @see DBManager::$backendFunctions
100      */
101     protected $backendFunctions = array(
102         'free_result' => 'mssql_free_result',
103         'close'       => 'mssql_close',
104         'row_count'   => 'mssql_num_rows'
105         );
106
107
108         /**
109      * @see DBManager::connect()
110      */
111     public function connect(
112         array $configOptions = null,
113         $dieOnError = false
114         )
115     {
116         global $sugar_config;
117
118         if (is_null($configOptions))
119             $configOptions = $sugar_config['dbconfig'];
120
121         //SET DATEFORMAT to 'YYYY-MM-DD''
122         ini_set('mssql.datetimeconvert', '0');
123
124         //set the text size and textlimit to max number so that blob columns are not truncated
125         ini_set('mssql.textlimit','2147483647');
126         ini_set('mssql.textsize','2147483647');
127
128         //set the connections parameters
129         $connect_param = '';
130         $configOptions['db_host_instance'] = trim($configOptions['db_host_instance']);
131         if (empty($configOptions['db_host_instance']))
132             $connect_param = $configOptions['db_host_name'];
133         else
134             $connect_param = $configOptions['db_host_name']."\\".$configOptions['db_host_instance'];
135
136         //create persistent connection
137         if ($sugar_config['dbconfigoption']['persistent'] == true) {
138             $this->database =@mssql_pconnect(
139                 $connect_param ,
140                 $configOptions['db_user_name'],
141                 $configOptions['db_password']
142                 );
143         }
144         //if no persistent connection created, then create regular connection
145         if(!$this->database){
146             $this->database = mssql_connect(
147                     $connect_param ,
148                     $configOptions['db_user_name'],
149                     $configOptions['db_password']
150                     );
151             if(!$this->database){
152                 $GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name'].
153                     " as ".$configOptions['db_user_name'].".");
154                 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
155             }
156             if($this->database && $sugar_config['dbconfigoption']['persistent'] == true){
157                 $_SESSION['administrator_error'] = "<B>Severe Performance Degradation: Persistent Database Connections "
158                     . "not working.  Please set \$sugar_config['dbconfigoption']['persistent'] to false in your "
159                     . "config.php file</B>";
160             }
161         }
162         //make sure connection exists
163         if(!$this->database){
164             sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
165         }
166
167         //select database
168
169         //Adding sleep and retry for mssql connection. We have come across scenarios when
170         //an error is thrown.' Unable to select database'. Following will try to connect to
171         //mssql db maximum number of 5 times at the interval of .2 second. If can not connect
172         //it will throw an Unable to select database message.
173
174         if(!@mssql_select_db($configOptions['db_name'], $this->database)){
175                         $connected = false;
176                         for($i=0;$i<5;$i++){
177                                 usleep(200000);
178                                 if(@mssql_select_db($configOptions['db_name'], $this->database)){
179                                         $connected = true;
180                                         break;
181                                 }
182                         }
183                         if(!$connected){
184                             $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}");
185                                 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
186                         }
187          }
188
189         if($this->checkError('Could Not Connect', $dieOnError))
190             $GLOBALS['log']->info("connected to db");
191
192         $GLOBALS['log']->info("Connect:".$this->database);
193     }
194
195         /**
196      * @see DBManager::version()
197      */
198     public function version()
199     {
200         return $this->getOne("SELECT @@VERSION as version");
201         }
202
203     /**
204      * @see DBManager::checkError()
205      */
206     public function checkError(
207         $msg = '',
208         $dieOnError = false
209         )
210     {
211         if (parent::checkError($msg, $dieOnError))
212             return true;
213
214         $sqlmsg = mssql_get_last_message();
215         
216         $sqlpos = strpos($sqlmsg, 'Changed database context to');
217         $sqlpos2 = strpos($sqlmsg, 'Warning:');
218         $sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
219         if ( $sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false )
220             $sqlmsg = '';  // empty out sqlmsg if its either of the two error messages described above
221         else {
222                 global $app_strings;
223             //ERR_MSSQL_DB_CONTEXT: localized version of 'Changed database context to' message
224             if (empty($app_strings) or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])) {
225                 //ignore the message from sql-server if $app_strings array is empty. This will happen
226                 //only if connection if made before languge is set.
227                 $GLOBALS['log']->debug("Ignoring this database message: " . $sqlmsg);
228                 $sqlmsg = '';
229             }
230             else {
231                 $sqlpos = strpos($sqlmsg, $app_strings['ERR_MSSQL_DB_CONTEXT']);
232                 if ( $sqlpos !== false )
233                     $sqlmsg = '';
234             }
235         }
236
237         if ( strlen($sqlmsg) > 2 ) {
238                 $GLOBALS['log']->fatal("$msg: SQL Server error: " . $sqlmsg);
239             return true;
240         }
241
242         return false;
243         }
244
245         /**
246      * @see DBManager::query()
247          */
248         public function query(
249         $sql,
250         $dieOnError = false,
251         $msg = '',
252         $suppress = false
253         )
254     {
255         // Flag if there are odd number of single quotes
256         if ((substr_count($sql, "'") & 1))
257             $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
258
259         $this->countQuery($sql);
260         $GLOBALS['log']->info('Query:' . $sql);
261         $this->checkConnection();
262         $this->query_time = microtime(true);
263
264         // Bug 34892 - Clear out previous error message by checking the @@ERROR global variable
265         $errorNumberHandle = mssql_query("SELECT @@ERROR",$this->database);
266                 $errorNumber = array_shift(mssql_fetch_row($errorNumberHandle));
267
268         if ($suppress) {
269         }
270         else {
271             $result = @mssql_query($sql, $this->database);
272         }
273
274         if (!$result) {
275
276             // awu Bug 10657: ignoring mssql error message 'Changed database context to' - an intermittent
277             //                            and difficult to reproduce error. The message is only a warning, and does
278             //                            not affect the functionality of the query
279             $sqlmsg = mssql_get_last_message();
280             $sqlpos = strpos($sqlmsg, 'Changed database context to');
281                         $sqlpos2 = strpos($sqlmsg, 'Warning:');
282                         $sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
283             
284                         if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false)              // if sqlmsg has 'Changed database context to', just log it
285                                 $GLOBALS['log']->debug($sqlmsg . ": " . $sql );
286                         else {
287                                 $GLOBALS['log']->fatal($sqlmsg . ": " . $sql );
288                                 if($dieOnError)
289                                         sugar_die('SQL Error : ' . $sqlmsg);
290                                 else
291                                         echo 'SQL Error : ' . $sqlmsg;
292                         }
293         }
294         $this->lastmysqlrow = -1;
295
296         $this->query_time = microtime(true) - $this->query_time;
297         $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
298
299
300         $this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
301
302         return $result;
303     }
304
305     /**
306      * This function take in the sql for a union query, the start and offset,
307      * and wraps it around an "mssql friendly" limit query
308      *
309      * @param  string $sql
310      * @param  int    $start record to start at
311      * @param  int    $count number of records to retrieve
312      * @return string SQL statement
313      */
314     private function handleUnionLimitQuery(
315         $sql,
316         $start,
317         $count
318         )
319     {
320         //set the start to 0, no negs
321         if ($start < 0)
322             $start=0;
323
324         $GLOBALS['log']->debug(print_r(func_get_args(),true));
325
326         $this->lastsql = $sql;
327
328         //change the casing to lower for easier string comparison, and trim whitespaces
329         $sql = strtolower(trim($sql)) ;
330
331         //set default sql
332         $limitUnionSQL = $sql;
333         $order_by_str = 'order by';
334
335         //make array of order by's.  substring approach was proving too inconsistent
336         $orderByArray = explode($order_by_str, $sql);
337         $unionOrderBy = '';
338         $rowNumOrderBy = '';
339
340         //count the number of array elements
341         $unionOrderByCount = count($orderByArray);
342         $arr_count = 0;
343
344         //process if there are elements
345         if ($unionOrderByCount){
346             //we really want the last ordery by, so reconstruct string
347             //adding a 1 to count, as we dont wish to process the last element
348             $unionsql = '';
349             while ($unionOrderByCount>$arr_count+1) {
350                 $unionsql .= $orderByArray[$arr_count];
351                 $arr_count = $arr_count+1;
352                 //add an "order by" string back if we are coming into loop again
353                 //remember they were taken out when array was created
354                 if ($unionOrderByCount>$arr_count+1) {
355                     $unionsql .= "order by";
356                 }
357             }
358             //grab the last order by element, set both order by's'
359             $unionOrderBy = $orderByArray[$arr_count];
360             $rowNumOrderBy = $unionOrderBy;
361
362             //if last element contains a "select", then this is part of the union query,
363             //and there is no order by to use
364             if (strpos($unionOrderBy, "select")) {
365                 $unionsql = $sql;
366                 //with no guidance on what to use for required order by in rownumber function,
367                 //resort to using name column.
368                 $rowNumOrderBy = 'id';
369                 $unionOrderBy = "";
370             }
371         }
372         else {
373             //there are no order by elements, so just pass back string
374             $unionsql = $sql;
375             //with no guidance on what to use for required order by in rownumber function,
376             //resort to using name column.
377             $rowNumOrderBy = 'id';
378             $unionOrderBy = '';
379         }
380         //Unions need the column name being sorted on to match acroos all queries in Union statement
381         //so we do not want to strip the alias like in other queries.  Just add the "order by" string and
382         //pass column name as is
383         if ($unionOrderBy != '') {
384             $unionOrderBy = ' order by ' . $unionOrderBy;
385         }
386
387         //if start is 0, then just use a top query
388         if($start == 0) {
389             $limitUnionSQL = "select top $count * from (" .$unionsql .") as top_count ".$unionOrderBy;
390         }
391         else {
392             //if start is more than 0, then use top query in conjunction
393             //with rownumber() function to create limit query.
394             $limitUnionSQL = "select top $count * from( select ROW_NUMBER() OVER ( order by "
395             .$rowNumOrderBy.") AS row_number, * from ("
396             .$unionsql .") As numbered) "
397             . "As top_count_limit WHERE row_number > $start "
398             .$unionOrderBy;
399         }
400
401         return $limitUnionSQL;
402     }
403
404         /**
405      * @see DBManager::limitQuery()
406      */
407     public function limitQuery(
408         $sql,
409         $start,
410         $count,
411         $dieOnError = false,
412         $msg = '')
413     {
414         $newSQL = $sql;
415         $distinctSQLARRAY = array();
416         if (strpos($sql, "UNION") && !preg_match("/(\')(UNION).?(\')/i", $sql))
417             $newSQL = $this->handleUnionLimitQuery($sql,$start,$count);
418         else {
419             if ($start < 0)
420                 $start = 0;
421             $GLOBALS['log']->debug(print_r(func_get_args(),true));
422             $this->lastsql = $sql;
423             $matches = array();
424             preg_match('/^(.*SELECT )(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
425             if (!empty($matches[3])) {
426                 if ($start == 0) {
427                     $match_two = strtolower($matches[2]);
428                     if (!strpos($match_two, "distinct")> 0 && strpos($match_two, "distinct") !==0) {
429                                         //proceed as normal
430                         $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
431                     }
432                     else {
433                         $distinct_o = strpos($match_two, "distinct");
434                         $up_to_distinct_str = substr($match_two, 0, $distinct_o);
435                         //check to see if the distinct is within a function, if so, then proceed as normal
436                         if (strpos($up_to_distinct_str,"(")) {
437                             //proceed as normal
438                             $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
439                         }
440                         else {
441                             //if distinct is not within a function, then parse
442                             //string contains distinct clause, "TOP needs to come after Distinct"
443                             //get position of distinct
444                             $match_zero = strtolower($matches[0]);
445                             $distinct_pos = strpos($match_zero , "distinct");
446                             //get position of where
447                             $where_pos = strpos($match_zero, "where");
448                             //parse through string
449                             $beg = substr($matches[0], 0, $distinct_pos+9 );
450                             $mid = substr($matches[0], strlen($beg), ($where_pos+5) - (strlen($beg)));
451                             $end = substr($matches[0], strlen($beg) + strlen($mid) );
452                             //repopulate matches array
453                             $matches[1] = $beg; $matches[2] = $mid; $matches[3] = $end;
454
455                             $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
456                         }
457                     }
458                 }
459                 else {
460                     $orderByMatch = array();
461                     preg_match('/^(.*)(ORDER BY)(.*)$/is',$matches[3], $orderByMatch);
462
463                     //if there is a distinct clause, parse sql string as we will have to insert the rownumber
464                     //for paging, AFTER the distinct clause
465                     $hasDistinct = strpos(strtolower($matches[0]), "distinct");
466                     if ($hasDistinct) {
467                         $matches_sql = strtolower($matches[0]);
468                         //remove reference to distinct and select keywords, as we will use a group by instead
469                         //we need to use group by because we are introducing rownumber column which would make every row unique
470
471                         //take out the select and distinct from string so we can reuse in group by
472                         $dist_str = ' distinct ';
473                         $distinct_pos = strpos($matches_sql, $dist_str);
474                         $matches_sql = substr($matches_sql,$distinct_pos+ strlen($dist_str));
475                         //get the position of where and from for further processing
476                         $from_pos = strpos($matches_sql , " from ");
477                         $where_pos = strpos($matches_sql, "where");
478                         //split the sql into a string before and after the from clause
479                         //we will use the columns being selected to construct the group by clause
480                         if ($from_pos>0 ) {
481                             $distinctSQLARRAY[0] = substr($matches_sql,0, $from_pos+1);
482                             $distinctSQLARRAY[1] = substr($matches_sql,$from_pos+1);
483                             //get position of order by (if it exists) so we can strip it from the string
484                             $ob_pos = strpos($distinctSQLARRAY[1], "order by");
485                             if ($ob_pos) {
486                                 $distinctSQLARRAY[1] = substr($distinctSQLARRAY[1],0,$ob_pos);
487                             }
488                             
489                             $distinctSQLARRAY[1] = preg_replace('/\)\s$/', ' ', $distinctSQLARRAY[1]);
490                         }
491
492                         //place group by string into array
493                         $grpByArr = explode(',', $distinctSQLARRAY[0]);
494                         $grpByStr = '';
495                         $first = true;
496                         //remove the aliases for each group by element, sql server doesnt like these in group by.
497                         foreach ($grpByArr as $gb) {
498                             $gb = trim($gb);
499
500                             //clean out the extra stuff added if we are concating first_name and last_name together
501                             //this way both fields are added in correctly to the group by
502                             $gb = str_replace("isnull(","",$gb);
503                             $gb = str_replace("'') + ' ' + ","",$gb);
504                             
505                             //remove outer reference if they exist
506                             if (strpos($gb,"'")!==false){
507                                 continue;
508                             }
509                             //if there is a space, then an alias exists, remove alias
510                             if (strpos($gb,' ')){
511                                 $gb = substr( $gb, 0,strpos($gb,' '));
512                             }
513
514                             //if resulting string is not empty then add to new group by string
515                             if (!empty($gb)) {
516                                 if ($first) {
517                                     $grpByStr .= " $gb";
518                                     $first = false;
519                                 }
520                                 else {
521                                     $grpByStr .= ", $gb";
522                                 }
523                             }
524                         }
525                     }
526
527                     if (!empty($orderByMatch[3])) {
528                         //if there is a distinct clause, form query with rownumber after distinct
529                         if ($hasDistinct) {
530                             $newSQL = "SELECT TOP $count * FROM
531                                         (
532                                             SELECT ROW_NUMBER()
533                                                 OVER (ORDER BY ".$this->returnOrderBy($sql, $orderByMatch[3]).") AS row_number,
534                                                 count(*) counter, " . $distinctSQLARRAY[0] . "
535                                                 " . $distinctSQLARRAY[1] . "
536                                                 group by " . $grpByStr . "
537                                         ) AS a
538                                         WHERE row_number > $start";
539                         }
540                         else {
541                         $newSQL = "SELECT TOP $count * FROM
542                                     (
543                                         " . $matches[1] . " ROW_NUMBER()
544                                         OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]) . ") AS row_number,
545                                         " . $matches[2] . $orderByMatch[1]. "
546                                     ) AS a
547                                     WHERE row_number > $start";
548                         }
549                     }else{
550                         //bug: 22231 Records in campaigns' subpanel may not come from
551                         //table of $_REQUEST['module']. Get it directly from query
552                         $upperQuery = strtoupper($matches[2]);
553                         if (!strpos($upperQuery,"JOIN")){
554                             $from_pos = strpos($upperQuery , "FROM") + 4;
555                             $where_pos = strpos($upperQuery, "WHERE");
556                             $tablename = trim(substr($upperQuery,$from_pos, $where_pos - $from_pos));
557                         }else{
558                             $tablename = $this->getTableNameFromModuleName($_REQUEST['module'],$sql);
559                         }
560                         //if there is a distinct clause, form query with rownumber after distinct
561                         if ($hasDistinct) {
562                              $newSQL = "SELECT TOP $count * FROM
563                                             (
564                             SELECT ROW_NUMBER() OVER (ORDER BY ".$tablename.".id) AS row_number, count(*) counter, " . $distinctSQLARRAY[0] . "
565                                                         " . $distinctSQLARRAY[1] . "
566                                                     group by " . $grpByStr . "
567                                             )
568                                             AS a
569                                             WHERE row_number > $start";
570                         }
571                         else {
572                              $newSQL = "SELECT TOP $count * FROM
573                                            (
574                                   " . $matches[1] . " ROW_NUMBER() OVER (ORDER BY ".$tablename.".id) AS row_number, " . $matches[2] . $matches[3]. "
575                                            )
576                                            AS a
577                                            WHERE row_number > $start";
578                         }
579                     }
580                 }
581             }
582         }
583
584         $GLOBALS['log']->debug('Limit Query: ' . $newSQL);
585         $result =  $this->query($newSQL, $dieOnError, $msg);
586         $this->dump_slow_queries($newSQL);
587         return $result;
588     }
589
590
591     /**
592      * Searches for begginning and ending characters.  It places contents into
593      * an array and replaces contents in original string.  This is used to account for use of
594      * nested functions while aliasing column names
595      *
596      * @param  string $p_sql     SQL statement
597      * @param  string $strip_beg Beginning character
598      * @param  string $strip_end Ending character
599      * @param  string $patt      Optional, pattern to
600      */
601     private function removePatternFromSQL(
602         $p_sql,
603         $strip_beg,
604         $strip_end,
605         $patt = 'patt')
606     {
607         //strip all single quotes out
608         $beg_sin = 0;
609         $sec_sin = 0;
610         $count = substr_count ( $p_sql, $strip_beg);
611         $increment = 1;
612         if ($strip_beg != $strip_end)
613             $increment = 2;
614
615         $i=0;
616         $offset = 0;
617         $strip_array = array();
618         while ($i<$count && $offset<strlen($p_sql)) {
619             if ($offset > strlen($p_sql))
620             {
621                                 break;   
622             }           
623             $beg_sin = strpos($p_sql, $strip_beg, $offset);
624             if (!$beg_sin)
625             {
626                 break;
627             }
628             $sec_sin = strpos($p_sql, $strip_end, $beg_sin+1);
629             $strip_array[$patt.$i] = substr($p_sql, $beg_sin, $sec_sin - $beg_sin +1);
630             if ($increment > 1) {
631                 //we are in here because beginning and end patterns are not identical, so search for nesting
632                 $exists = strpos($strip_array[$patt.$i], $strip_beg );
633                 if ($exists>=0) {
634                     $nested_pos = (strrpos($strip_array[$patt.$i], $strip_beg ));
635                     $strip_array[$patt.$i] = substr($p_sql,$nested_pos+$beg_sin,$sec_sin - ($nested_pos+$beg_sin)+1);
636                     $p_sql = substr($p_sql, 0, $nested_pos+$beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
637                     $i = $i + 1;
638                     $beg_sin = $nested_pos;
639                     continue;
640                 }
641             }
642             $p_sql = substr($p_sql, 0, $beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
643             //move the marker up
644             $offset = $sec_sin+1;
645
646             $i = $i + 1;
647         }
648         $strip_array['sql_string'] = $p_sql;
649
650         return $strip_array;
651     }
652
653     /**
654      * adds a pattern
655      *
656      * @param  string $token
657      * @param  array  $pattern_array
658      * @return string
659      */
660         private function addPatternToSQL(
661         $token,
662         array $pattern_array
663         )
664     {
665         //strip all single quotes out
666         $pattern_array = array_reverse($pattern_array);
667
668         foreach ($pattern_array as $key => $replace) {
669             $token = str_replace( "##".$key."##", $replace,$token);
670         }
671
672         return $token;
673     }
674
675     /**
676      * gets an alias from the sql statement
677      *
678      * @param  string $sql
679      * @param  string $alias
680      * @return string
681      */
682         private function getAliasFromSQL(
683         $sql,
684         $alias
685         )
686     {
687         $matches = array();
688         preg_match('/^(.*SELECT)(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
689         //parse all single and double  quotes out of array
690         $sin_array = $this->removePatternFromSQL($matches[2], "'", "'","sin_");
691         $new_sql = array_pop($sin_array);
692         $dub_array = $this->removePatternFromSQL($new_sql, "\"", "\"","dub_");
693         $new_sql = array_pop($dub_array);
694
695         //search for parenthesis
696         $paren_array = $this->removePatternFromSQL($new_sql, "(", ")", "par_");
697         $new_sql = array_pop($paren_array);
698
699         //all functions should be removed now, so split the array on comma's
700         $mstr_sql_array = explode(",", $new_sql);
701         foreach($mstr_sql_array as $token ) {
702             if (strpos($token, $alias)) {
703                 //found token, add back comments
704                 $token = $this->addPatternToSQL($token, $paren_array);
705                 $token = $this->addPatternToSQL($token, $dub_array);
706                 $token = $this->addPatternToSQL($token, $sin_array);
707
708                 //log and break out of this function
709                 return $token;
710             }
711         }
712         return null;
713     }
714
715
716     /**
717      * Finds the alias of the order by column, and then return the preceding column name
718      *
719      * @param  string $sql
720      * @param  string $orderMatch
721      * @return string
722      */
723     private function findColumnByAlias(
724         $sql,
725         $orderMatch
726         )
727     {
728         //change case to lowercase
729         $sql = strtolower($sql);
730         $patt = '/\s+'.trim($orderMatch).'\s*,/';
731
732         //check for the alias, it should contain comma, may contain space, \n, or \t
733         $matches = array();
734         preg_match($patt, $sql, $matches, PREG_OFFSET_CAPTURE);
735         $found_in_sql = isset($matches[0][1]) ? $matches[0][1] : false;
736
737
738         //set default for found variable
739         $found = $found_in_sql;
740
741         //if still no match found, then we need to parse through the string
742         if (!$found_in_sql){
743             //get count of how many times the match exists in string
744             $found_count = substr_count($sql, $orderMatch);
745             $i = 0;
746             $first_ = 0;
747             $len = strlen($orderMatch);
748             //loop through string as many times as there is a match
749             while ($found_count > $i) {
750                 //get the first match
751                 $found_in_sql = strpos($sql, $orderMatch,$first_);
752                 //make sure there was a match
753                 if($found_in_sql){
754                     //grab the next 2 individual characters
755                     $str_plusone = substr($sql,$found_in_sql + $len,1);
756                     $str_plustwo = substr($sql,$found_in_sql + $len+1,1);
757                     //if one of those characters is a comma, then we have our alias
758                     if ($str_plusone === "," || $str_plustwo === ","){
759                         //keep track of this position
760                         $found = $found_in_sql;
761                     }
762                 }
763                 //set the offset and increase the iteration counter
764                 $first_ = $found_in_sql+$len;
765                 $i = $i+1;
766             }
767         }
768         //return $found, defaults have been set, so if no match was found it will be a negative number
769         return $found;
770     }
771
772
773     /**
774      * Return the order by string to use in case the column has been aliased
775      *
776      * @param  string $sql
777      * @param  string $orig_order_match
778      * @return string
779      */
780     private function returnOrderBy(
781         $sql,
782         $orig_order_match
783         )
784     {
785         $sql = strtolower($sql);
786         $orig_order_match = trim($orig_order_match);
787         if (strpos($orig_order_match, ".") != 0)
788             //this has a tablename defined, pass in the order match
789             return $orig_order_match;
790
791         //grab first space in order by
792         $firstSpace = strpos($orig_order_match, " ");
793
794         //split order by into column name and ascending/descending
795         $orderMatch = " " . strtolower(substr($orig_order_match, 0, $firstSpace));
796         $asc_desc =  substr($orig_order_match,$firstSpace);
797
798         //look for column name as an alias in sql string
799         $found_in_sql = $this->findColumnByAlias($sql, $orderMatch);
800
801         if (!$found_in_sql) {
802             //check if this column needs the tablename prefixed to it
803             $orderMatch = ".".trim($orderMatch);
804             $colMatchPos = strpos($sql, $orderMatch);
805             if ($colMatchPos !== false) {
806                 //grab sub string up to column name
807                 $containsColStr = substr($sql,0, $colMatchPos);
808                 //get position of first space, so we can grab table name
809                 $lastSpacePos = strrpos($containsColStr, " ");
810                 //use positions of column name, space before name, and length of column to find the correct column name
811                 $col_name = substr($sql, $lastSpacePos, $colMatchPos-$lastSpacePos+strlen($orderMatch));
812                                 //bug 25485. When sorting by a custom field in Account List and then pressing NEXT >, system gives an error
813                                 $containsCommaPos = strpos($col_name, ",");
814                                 if($containsCommaPos !== false) {
815                                         $col_name = substr($col_name, $containsCommaPos+1);
816                                 }
817                 //return column name
818                 return $col_name;
819             }
820             //break out of here, log this
821             $GLOBALS['log']->debug("No match was found for order by, pass string back untouched as: $orig_order_match");
822             return $orig_order_match;
823         }
824         else {
825             //if found, then parse and return
826             //grab string up to the aliased column
827             $GLOBALS['log']->debug("order by found, process sql string");
828
829             $psql = (trim($this->getAliasFromSQL($sql, $orderMatch )));
830             if (empty($psql))
831                 $psql = trim(substr($sql, 0, $found_in_sql));
832
833             //grab the last comma before the alias
834             $comma_pos = strrpos($psql, " ");
835             //substring between the comma and the alias to find the joined_table alias and column name
836             $col_name = substr($psql,0, $comma_pos);
837
838             //make sure the string does not have an end parenthesis
839             //and is not part of a function (i.e. "ISNULL(leads.last_name,'') as name"  )
840             //this is especially true for unified search from home screen
841
842             $alias_beg_pos = 0;
843             if(strpos($psql, " as "))
844                 $alias_beg_pos = strpos($psql, " as ");
845             else if (strncasecmp($psql, 'isnull', 6) != 0)
846                 $alias_beg_pos = strpos($psql, " ");
847
848             if ($alias_beg_pos > 0) {
849                 $col_name = substr($psql,0, $alias_beg_pos );
850             }
851             //add the "asc/desc" order back
852             $col_name = $col_name. " ". $asc_desc;
853
854             //pass in new order by
855             $GLOBALS['log']->debug("order by being returned is " . $col_name);
856             return $col_name;
857         }
858     }
859
860     /**
861      * Take in a string of the module and retrieve the correspondent table name
862      *
863      * @param  string $module_str module name
864      * @param  string $sql        SQL statement
865      * @return string table name
866      */
867     private function getTableNameFromModuleName(
868         $module_str,
869         $sql
870         )
871     {
872
873         global $beanList, $beanFiles;
874         $GLOBALS['log']->debug("Module being processed is " . $module_str);
875         //get the right module files
876         //the module string exists in bean list, then process bean for correct table name
877         //note that we exempt the reports module from this, as queries from reporting module should be parsed for
878         //correct table name.
879         if (($module_str != 'Reports' && $module_str != 'SavedReport') && isset($beanList[$module_str])  &&  isset($beanFiles[$beanList[$module_str]])){
880             //if the class is not already loaded, then load files
881             if (!class_exists($beanList[$module_str]))
882                 require_once($beanFiles[$beanList[$module_str]]);
883
884             //instantiate new bean
885             $module_bean = new $beanList[$module_str]();
886             //get table name from bean
887             $tbl_name = $module_bean->table_name;
888             //make sure table name is not just a blank space, or empty
889             $tbl_name = trim($tbl_name);
890
891             if(empty($tbl_name)){
892                 $GLOBALS['log']->debug("Could not find table name for module $module_str. ");
893                 $tbl_name = $module_str;
894             }
895         }
896         else {
897             //since the module does NOT exist in beanlist, then we have to parse the string
898             //and grab the table name from the passed in sql
899             $GLOBALS['log']->debug("Could not find table name from module in request, retrieve from passed in sql");
900             $tbl_name = $module_str;
901             $sql = strtolower($sql);
902
903             //look for the location of the "from" in sql string
904             $fromLoc = strpos($sql," from " );
905             if ($fromLoc>0){
906                 //found from, substring from the " FROM " string in sql to end
907                 $tableEnd = substr($sql, $fromLoc+6);
908                 //We know that tablename will be next parameter after from, so
909                 //grab the next space after table name.
910                 // MFH BUG #14009: Also check to see if there are any carriage returns before the next space so that we don't grab any arbitrary joins or other tables.
911                 $carriage_ret = strpos($tableEnd,"\n");
912                 $next_space = strpos($tableEnd," " );
913                 if ($carriage_ret < $next_space)
914                     $next_space = $carriage_ret;
915                 if ($next_space > 0) {
916                     $tbl_name= substr($tableEnd,0, $next_space);
917                     if(empty($tbl_name)){
918                         $GLOBALS['log']->debug("Could not find table name sql either, return $module_str. ");
919                         $tbl_name = $module_str;
920                     }
921                 }
922
923                 //grab the table, to see if it is aliased
924                 $aliasTableEnd = trim(substr($tableEnd, $next_space));
925                 $alias_space = strpos ($aliasTableEnd, " " );
926                 if ($alias_space > 0){
927                     $alias_tbl_name= substr($aliasTableEnd,0, $alias_space);
928                     strtolower($alias_tbl_name);
929                     if(empty($alias_tbl_name)
930                         || $alias_tbl_name == "where"
931                         || $alias_tbl_name == "inner"
932                         || $alias_tbl_name == "left"
933                         || $alias_tbl_name == "join"
934                         || $alias_tbl_name == "outer"
935                         || $alias_tbl_name == "right") {
936                         //not aliased, do nothing
937                     }
938                     elseif ($alias_tbl_name == "as") {
939                             //the next word is the table name
940                             $aliasTableEnd = trim(substr($aliasTableEnd, $alias_space));
941                             $alias_space = strpos ($aliasTableEnd, " " );
942                             if ($alias_space > 0) {
943                                 $alias_tbl_name= trim(substr($aliasTableEnd,0, $alias_space));
944                                 if (!empty($alias_tbl_name))
945                                     $tbl_name = $alias_tbl_name;
946                             }
947                     }
948                     else {
949                         //this is table alias
950                         $tbl_name = $alias_tbl_name;
951                     }
952                 }
953             }
954         }
955         //return table name
956         $GLOBALS['log']->debug("Table name for module $module_str is: ".$tbl_name);
957         return $tbl_name;
958     }
959
960
961         /**
962      * @see DBManager::getFieldsArray()
963      */
964         public function getFieldsArray(
965         &$result,
966         $make_lower_case = false
967         )
968         {
969                 $field_array = array();
970
971                 if(! isset($result) || empty($result))
972             return 0;
973
974         $i = 0;
975         while ($i < mssql_num_fields($result)) {
976             $meta = mssql_fetch_field($result, $i);
977             if (!$meta)
978                 return 0;
979             if($make_lower_case==true)
980                 $meta->name = strtolower($meta->name);
981
982             $field_array[] = $meta->name;
983
984             $i++;
985         }
986
987         return $field_array;
988         }
989
990     /**
991      * @see DBManager::getAffectedRowCount()
992      */
993         public function getAffectedRowCount()
994     {
995         return $this->getOne("SELECT @@ROWCOUNT");
996     }
997
998     /**
999      * @see DBManager::describeField()
1000      */
1001         protected function describeField(
1002         $name,
1003         $tablename
1004         )
1005     {
1006         global $table_descriptions;
1007         if(isset($table_descriptions[$tablename]) && isset($table_descriptions[$tablename][$name])){
1008             return      $table_descriptions[$tablename][$name];
1009         }
1010         $table_descriptions[$tablename] = array();
1011
1012         $sql = sprintf( "SELECT COLUMN_NAME AS Field
1013                                 , DATA_TYPE + CASE WHEN CHARACTER_MAXIMUM_LENGTH IS NOT NULL
1014                         THEN '(' + RTRIM(CAST(CHARACTER_MAXIMUM_LENGTH AS CHAR)) + ')' 
1015                                                 ELSE '' END as 'Type'
1016                                 , CHARACTER_MAXIMUM_LENGTH
1017                                 , IS_NULLABLE AS 'Null'
1018                                 , CASE WHEN COLUMN_DEFAULT LIKE '((0))' THEN '(''0'')' ELSE COLUMN_DEFAULT END as 'Default'
1019                         FROM INFORMATION_SCHEMA.COLUMNS
1020                         WHERE TABLE_NAME = '%s'",
1021                         $tablename
1022         );
1023
1024         $result = $this->query($sql);
1025         while ($row = $this->fetchByAssoc($result) )
1026             $table_descriptions[$tablename][$row['Field']] = $row;
1027
1028         if (isset($table_descriptions[$tablename][$name]))
1029             return      $table_descriptions[$tablename][$name];
1030
1031         return array();
1032     }
1033
1034
1035
1036         /**
1037      * @see DBManager::fetchByAssoc()
1038      */
1039     public function fetchByAssoc(
1040         &$result,
1041         $rowNum = -1,
1042         $encode = true
1043         )
1044     {
1045         if (!$result)
1046             return false;
1047
1048                 if ($result && $rowNum < 0) {
1049             $row = mssql_fetch_assoc($result);
1050             //MSSQL returns a space " " when a varchar column is empty ("") and not null.
1051             //We need to iterate through the returned row array and strip empty spaces
1052             if(!empty($row)){
1053                 foreach($row as $key => $column) {
1054                     //notice we only strip if one space is returned.  we do not want to strip
1055                     //strings with intentional spaces (" foo ")
1056                     if (!empty($column) && $column ==" ") {
1057                         $row[$key] = '';
1058                     }
1059                 }
1060             }
1061
1062             if($encode && $this->encode&& is_array($row))
1063                 return array_map('to_html', $row);
1064
1065             return $row;
1066                 }
1067
1068                 if ($this->getRowCount($result) > $rowNum) {
1069                         if ( $rowNum == -1 )
1070                 $rowNum = 0;
1071                         @mssql_data_seek($result, $rowNum);
1072         }
1073
1074         $this->lastmysqlrow = $rowNum;
1075         $row = @mssql_fetch_assoc($result);
1076         if($encode && $this->encode && is_array($row))
1077             return array_map('to_html', $row);
1078         return $row;
1079         }
1080
1081     /**
1082      * @see DBManager::quote()
1083      */
1084     public function quote(
1085         $string,
1086         $isLike = true
1087         )
1088     {
1089         return $string = str_replace("'","''", parent::quote($string));
1090     }
1091
1092     /**
1093      * @see DBManager::quoteForEmail()
1094      */
1095     public function quoteForEmail(
1096         $string,
1097         $isLike = true
1098         )
1099     {
1100         return str_replace("'","''", $string);
1101     }
1102
1103
1104     /**
1105      * @see DBManager::tableExists()
1106      */
1107     public function tableExists(
1108         $tableName
1109         )
1110     {
1111         $GLOBALS['log']->info("tableExists: $tableName");
1112
1113         $this->checkConnection();
1114         $result = $this->query(
1115             "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='".$tableName."'");
1116
1117         $rowCount = $this->getRowCount($result);
1118         $this->freeResult($result);
1119         return ($rowCount == 0) ? false : true;
1120     }
1121
1122     /**
1123      * @see DBManager::addIndexes()
1124      */
1125     public function addIndexes(
1126         $tablename,
1127         $indexes,
1128         $execute = true
1129         )
1130     {
1131         $alters = $this->helper->indexSQL($tablename,array(),$indexes);
1132         if ($execute)
1133             $this->query($alters);
1134
1135         return $alters;
1136     }
1137
1138     /**
1139      * @see DBManager::dropIndexes()
1140      */
1141     public function dropIndexes(
1142         $tablename,
1143         $indexes,
1144         $execute = true
1145         )
1146     {
1147         $sql = '';
1148         foreach ($indexes as $index) {
1149             if ( !empty($sql) ) $sql .= ";";
1150             $name = $index['name'];
1151             if($execute)
1152                 unset($GLOBALS['table_descriptions'][$tablename]['indexes'][$name]);
1153             if ($index['type'] == 'primary')
1154                 $sql .= "ALTER TABLE $tablename DROP CONSTRAINT $name";
1155             else
1156                 $sql .= "DROP INDEX $name on $tablename";
1157         }
1158         if (!empty($sql))
1159             if($execute)
1160                 $this->query($sql);
1161
1162         return $sql;
1163     }
1164
1165     /**
1166      * @see DBManager::checkQuery()
1167      */
1168     protected function checkQuery(
1169         $sql
1170         )
1171     {
1172         return true;
1173     }
1174
1175     /**
1176      * @see DBManager::getTablesArray()
1177      */
1178     public function getTablesArray()
1179     {
1180         $GLOBALS['log']->debug('MSSQL fetching table list');
1181
1182         if($this->getDatabase()) {
1183             $tables = array();
1184             $r = $this->query('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES');
1185             if (is_resource($r)) {
1186                 while ($a = $this->fetchByAssoc($r))
1187                     $tables[] = $a['TABLE_NAME'];
1188
1189                 return $tables;
1190             }
1191         }
1192
1193         return false; // no database available
1194     }
1195
1196
1197     /**
1198      * This call is meant to be used during install, when Full Text Search is enabled
1199      * Indexing would always occur after a fresh sql server install, so this code creates
1200      * a catalog and table with full text index.
1201      */
1202     public function wakeupFTS()
1203     {
1204         $GLOBALS['log']->debug('MSSQL about to wakeup FTS');
1205
1206         if($this->getDatabase()) {
1207                 //create wakup catalog
1208                 $FTSqry[] = "if not exists(  select * from sys.fulltext_catalogs where name ='wakeup_catalog' )
1209                 CREATE FULLTEXT CATALOG wakeup_catalog
1210                 ";
1211
1212                 //drop wakeup table if it exists
1213                 $FTSqry[] = "IF EXISTS(SELECT 'fts_wakeup' FROM sysobjects WHERE name = 'fts_wakeup' AND xtype='U')
1214                     DROP TABLE fts_wakeup
1215                 ";
1216                 //create wakeup table
1217                 $FTSqry[] = "CREATE TABLE fts_wakeup(
1218                     id varchar(36) NOT NULL CONSTRAINT pk_fts_wakeup_id PRIMARY KEY CLUSTERED (id ASC ),
1219                     body text NULL,
1220                     kb_index int IDENTITY(1,1) NOT NULL CONSTRAINT wakeup_fts_unique_idx UNIQUE NONCLUSTERED
1221                 )
1222                 ";
1223                 //create full text index
1224                  $FTSqry[] = "CREATE FULLTEXT INDEX ON fts_wakeup
1225                 (
1226                     body
1227                     Language 0X0
1228                 )
1229                 KEY INDEX wakeup_fts_unique_idx ON wakeup_catalog
1230                 WITH CHANGE_TRACKING AUTO
1231                 ";
1232
1233                 //insert dummy data
1234                 $FTSqry[] = "INSERT INTO fts_wakeup (id ,body)
1235                 VALUES ('".create_guid()."', 'SugarCRM Rocks' )";
1236
1237
1238                 //create queries to stop and restart indexing
1239                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup STOP POPULATION';
1240                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup DISABLE';
1241                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup ENABLE';
1242                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING MANUAL';
1243                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup START FULL POPULATION';
1244                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING AUTO';
1245
1246                 foreach($FTSqry as $q){
1247                     sleep(3);
1248                     $this->query($q);
1249                 }
1250
1251
1252         }
1253
1254         return false; // no database available
1255     }
1256
1257     /**
1258      * @see DBManager::convert()
1259      */
1260     public function convert(
1261         $string,
1262         $type,
1263         array $additional_parameters = array(),
1264         array $additional_parameters_oracle_only = array()
1265         )
1266     {
1267         // convert the parameters array into a comma delimited string
1268         $additional_parameters_string = '';
1269         if (!empty($additional_parameters))
1270             $additional_parameters_string = ','.implode(',',$additional_parameters);
1271
1272         switch ($type) {
1273         case 'today': return "GETDATE()";
1274         case 'left': return "LEFT($string".$additional_parameters_string.")";
1275         case 'date_format':
1276             if(!empty($additional_parameters) && in_array("'%Y-%m'", $additional_parameters))
1277                return "CONVERT(varchar(7),". $string . ",120)";
1278             else
1279                return "CONVERT(varchar(10),". $string . ",120)";
1280         case 'IFNULL': return "ISNULL($string".$additional_parameters_string.")";
1281         case 'CONCAT': return "$string+".implode("+",$additional_parameters);
1282         case 'text2char': return "CAST($string AS varchar(8000))";
1283         }
1284
1285         return "$string";
1286     }
1287
1288     /**
1289      * @see DBManager::concat()
1290      */
1291     public function concat(
1292         $table,
1293         array $fields
1294         )
1295     {
1296         $ret = '';
1297
1298         foreach ( $fields as $index => $field )
1299                         if (empty($ret))
1300                             $ret =  db_convert($table.".".$field,'IFNULL', array("''"));
1301                         else
1302                             $ret .=     " + ' ' + ".db_convert($table.".".$field,'IFNULL', array("''"));
1303
1304                 return empty($ret)?$ret:"LTRIM(RTRIM($ret))";
1305     }
1306
1307     /**
1308      * @see DBManager::fromConvert()
1309      */
1310     public function fromConvert(
1311         $string,
1312         $type)
1313     {
1314         switch($type) {
1315         case 'datetime': return substr($string, 0,19);
1316         case 'date': return substr($string, 0,11);
1317         case 'time': return substr($string, 11);
1318                 }
1319
1320                 return $string;
1321     }
1322 }