]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/database/MssqlManager.php
Release 6.1.5
[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         $sqlpos = strpos($sqlmsg, 'Changed database context to');
216         $sqlpos2 = strpos($sqlmsg, 'Caution: Changing any part of an object name could break scripts and stored procedures.');
217         if ( $sqlpos !== false || $sqlpos2 !== false )
218             $sqlmsg = '';  // empty out sqlmsg if its either of the two error messages described above
219         else {
220                 global $app_strings;
221             //ERR_MSSQL_DB_CONTEXT: localized version of 'Changed database context to' message
222             if (empty($app_strings) or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])) {
223                 //ignore the message from sql-server if $app_strings array is empty. This will happen
224                 //only if connection if made before languge is set.
225                 $GLOBALS['log']->debug("Ignoring this database message: " . $sqlmsg);
226                 $sqlmsg = '';
227             }
228             else {
229                 $sqlpos = strpos($sqlmsg, $app_strings['ERR_MSSQL_DB_CONTEXT']);
230                 if ( $sqlpos !== false )
231                     $sqlmsg = '';
232             }
233         }
234
235         if ( strlen($sqlmsg) > 2 ) {
236                 $GLOBALS['log']->fatal("$msg: SQL Server error: " . $sqlmsg);
237             return true;
238         }
239
240         return false;
241         }
242
243         /**
244      * @see DBManager::query()
245          */
246         public function query(
247         $sql,
248         $dieOnError = false,
249         $msg = '',
250         $suppress = false
251         )
252     {
253         // Flag if there are odd number of single quotes
254         if ((substr_count($sql, "'") & 1))
255             $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
256
257         $this->countQuery($sql);
258         $GLOBALS['log']->info('Query:' . $sql);
259         $this->checkConnection();
260         $this->query_time = microtime(true);
261
262         // Bug 34892 - Clear out previous error message by checking the @@ERROR global variable
263         $errorNumberHandle = mssql_query("SELECT @@ERROR",$this->database);
264                 $errorNumber = array_shift(mssql_fetch_row($errorNumberHandle));
265
266         if ($suppress) {
267         }
268         else {
269             $result = @mssql_query($sql, $this->database);
270         }
271
272         $this->lastmysqlrow = -1;
273
274         $this->query_time = microtime(true) - $this->query_time;
275         $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
276
277
278         $this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
279
280         return $result;
281     }
282
283     /**
284      * This function take in the sql for a union query, the start and offset,
285      * and wraps it around an "mssql friendly" limit query
286      *
287      * @param  string $sql
288      * @param  int    $start record to start at
289      * @param  int    $count number of records to retrieve
290      * @return string SQL statement
291      */
292     private function handleUnionLimitQuery(
293         $sql,
294         $start,
295         $count
296         )
297     {
298         //set the start to 0, no negs
299         if ($start < 0)
300             $start=0;
301
302         $GLOBALS['log']->debug(print_r(func_get_args(),true));
303
304         $this->lastsql = $sql;
305
306         //change the casing to lower for easier string comparison, and trim whitespaces
307         $sql = strtolower(trim($sql)) ;
308
309         //set default sql
310         $limitUnionSQL = $sql;
311         $order_by_str = 'order by';
312
313         //make array of order by's.  substring approach was proving too inconsistent
314         $orderByArray = explode($order_by_str, $sql);
315         $unionOrderBy = '';
316         $rowNumOrderBy = '';
317
318         //count the number of array elements
319         $unionOrderByCount = count($orderByArray);
320         $arr_count = 0;
321
322         //process if there are elements
323         if ($unionOrderByCount){
324             //we really want the last ordery by, so reconstruct string
325             //adding a 1 to count, as we dont wish to process the last element
326             $unionsql = '';
327             while ($unionOrderByCount>$arr_count+1) {
328                 $unionsql .= $orderByArray[$arr_count];
329                 $arr_count = $arr_count+1;
330                 //add an "order by" string back if we are coming into loop again
331                 //remember they were taken out when array was created
332                 if ($unionOrderByCount>$arr_count+1) {
333                     $unionsql .= "order by";
334                 }
335             }
336             //grab the last order by element, set both order by's'
337             $unionOrderBy = $orderByArray[$arr_count];
338             $rowNumOrderBy = $unionOrderBy;
339
340             //if last element contains a "select", then this is part of the union query,
341             //and there is no order by to use
342             if (strpos($unionOrderBy, "select")) {
343                 $unionsql = $sql;
344                 //with no guidance on what to use for required order by in rownumber function,
345                 //resort to using name column.
346                 $rowNumOrderBy = 'id';
347                 $unionOrderBy = "";
348             }
349         }
350         else {
351             //there are no order by elements, so just pass back string
352             $unionsql = $sql;
353             //with no guidance on what to use for required order by in rownumber function,
354             //resort to using name column.
355             $rowNumOrderBy = 'id';
356             $unionOrderBy = '';
357         }
358         //Unions need the column name being sorted on to match acroos all queries in Union statement
359         //so we do not want to strip the alias like in other queries.  Just add the "order by" string and
360         //pass column name as is
361         if ($unionOrderBy != '') {
362             $unionOrderBy = ' order by ' . $unionOrderBy;
363         }
364
365         //if start is 0, then just use a top query
366         if($start == 0) {
367             $limitUnionSQL = "select top $count * from (" .$unionsql .") as top_count ".$unionOrderBy;
368         }
369         else {
370             //if start is more than 0, then use top query in conjunction
371             //with rownumber() function to create limit query.
372             $limitUnionSQL = "select top $count * from( select ROW_NUMBER() OVER ( order by "
373             .$rowNumOrderBy.") AS row_number, * from ("
374             .$unionsql .") As numbered) "
375             . "As top_count_limit WHERE row_number > $start "
376             .$unionOrderBy;
377         }
378
379         return $limitUnionSQL;
380     }
381
382         /**
383      * @see DBManager::limitQuery()
384      */
385     public function limitQuery(
386         $sql,
387         $start,
388         $count,
389         $dieOnError = false,
390         $msg = '')
391     {
392         $newSQL = $sql;
393         $distinctSQLARRAY = array();
394         if (strpos($sql, "UNION") && !preg_match("/(\')(UNION).?(\')/i", $sql))
395             $newSQL = $this->handleUnionLimitQuery($sql,$start,$count);
396         else {
397             if ($start < 0)
398                 $start = 0;
399             $GLOBALS['log']->debug(print_r(func_get_args(),true));
400             $this->lastsql = $sql;
401             $matches = array();
402             preg_match('/^(.*SELECT )(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
403             if (!empty($matches[3])) {
404                 if ($start == 0) {
405                     $match_two = strtolower($matches[2]);
406                     if (!strpos($match_two, "distinct")> 0 && strpos($match_two, "distinct") !==0) {
407                                         //proceed as normal
408                         $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
409                     }
410                     else {
411                         $distinct_o = strpos($match_two, "distinct");
412                         $up_to_distinct_str = substr($match_two, 0, $distinct_o);
413                         //check to see if the distinct is within a function, if so, then proceed as normal
414                         if (strpos($up_to_distinct_str,"(")) {
415                             //proceed as normal
416                             $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
417                         }
418                         else {
419                             //if distinct is not within a function, then parse
420                             //string contains distinct clause, "TOP needs to come after Distinct"
421                             //get position of distinct
422                             $match_zero = strtolower($matches[0]);
423                             $distinct_pos = strpos($match_zero , "distinct");
424                             //get position of where
425                             $where_pos = strpos($match_zero, "where");
426                             //parse through string
427                             $beg = substr($matches[0], 0, $distinct_pos+9 );
428                             $mid = substr($matches[0], strlen($beg), ($where_pos+5) - (strlen($beg)));
429                             $end = substr($matches[0], strlen($beg) + strlen($mid) );
430                             //repopulate matches array
431                             $matches[1] = $beg; $matches[2] = $mid; $matches[3] = $end;
432
433                             $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
434                         }
435                     }
436                 }
437                 else {
438                     $orderByMatch = array();
439                     preg_match('/^(.*)(ORDER BY)(.*)$/is',$matches[3], $orderByMatch);
440
441                     //if there is a distinct clause, parse sql string as we will have to insert the rownumber
442                     //for paging, AFTER the distinct clause
443                     $hasDistinct = strpos(strtolower($matches[0]), "distinct");
444                     if ($hasDistinct) {
445                         $matches_sql = strtolower($matches[0]);
446                         //remove reference to distinct and select keywords, as we will use a group by instead
447                         //we need to use group by because we are introducing rownumber column which would make every row unique
448
449                         //take out the select and distinct from string so we can reuse in group by
450                         $dist_str = ' distinct ';
451                         $distinct_pos = strpos($matches_sql, $dist_str);
452                         $matches_sql = substr($matches_sql,$distinct_pos+ strlen($dist_str));
453                         //get the position of where and from for further processing
454                         $from_pos = strpos($matches_sql , " from ");
455                         $where_pos = strpos($matches_sql, "where");
456                         //split the sql into a string before and after the from clause
457                         //we will use the columns being selected to construct the group by clause
458                         if ($from_pos>0 ) {
459                             $distinctSQLARRAY[0] = substr($matches_sql,0, $from_pos+1);
460                             $distinctSQLARRAY[1] = substr($matches_sql,$from_pos+1);
461                             //get position of order by (if it exists) so we can strip it from the string
462                             $ob_pos = strpos($distinctSQLARRAY[1], "order by");
463                             if ($ob_pos) {
464                                 $distinctSQLARRAY[1] = substr($distinctSQLARRAY[1],0,$ob_pos);
465                             }
466                             // strip off last closing parathese from the where clause
467                             $distinctSQLARRAY[1] = preg_replace("/\)\s$/"," ",$distinctSQLARRAY[1]);
468                         }
469
470                         //place group by string into array
471                         $grpByArr = explode(',', $distinctSQLARRAY[0]);
472                         $grpByStr = '';
473                         $first = true;
474                         //remove the aliases for each group by element, sql server doesnt like these in group by.
475                         foreach ($grpByArr as $gb) {
476                             $gb = trim($gb);
477
478                             //clean out the extra stuff added if we are concating first_name and last_name together
479                             //this way both fields are added in correctly to the group by
480                             $gb = str_replace("isnull(","",$gb);
481                             $gb = str_replace("'') + ' ' + ","",$gb);
482
483                             //remove outer reference if they exist
484                             if (strpos($gb,"'")!==false){
485                                 continue;
486                             }
487                             //if there is a space, then an alias exists, remove alias
488                             if (strpos($gb,' ')){
489                                 $gb = substr( $gb, 0,strpos($gb,' '));
490                             }
491
492                             //if resulting string is not empty then add to new group by string
493                             if (!empty($gb)) {
494                                 if ($first) {
495                                     $grpByStr .= " $gb";
496                                     $first = false;
497                                 }
498                                 else {
499                                     $grpByStr .= ", $gb";
500                                 }
501                             }
502                         }
503                     }
504
505                     if (!empty($orderByMatch[3])) {
506                         //if there is a distinct clause, form query with rownumber after distinct
507                         if ($hasDistinct) {
508                             $newSQL = "SELECT TOP $count * FROM
509                                         (
510                                             SELECT ROW_NUMBER()
511                                                 OVER (ORDER BY ".$this->returnOrderBy($sql, $orderByMatch[3]).") AS row_number,
512                                                 count(*) counter, " . $distinctSQLARRAY[0] . "
513                                                 " . $distinctSQLARRAY[1] . "
514                                                 group by " . $grpByStr . "
515                                         ) AS a
516                                         WHERE row_number > $start";
517                         }
518                         else {
519                         $newSQL = "SELECT TOP $count * FROM
520                                     (
521                                         " . $matches[1] . " ROW_NUMBER()
522                                         OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]) . ") AS row_number,
523                                         " . $matches[2] . $orderByMatch[1]. "
524                                     ) AS a
525                                     WHERE row_number > $start";
526                         }
527                     }else{
528                         //bug: 22231 Records in campaigns' subpanel may not come from
529                         //table of $_REQUEST['module']. Get it directly from query
530                         $upperQuery = strtoupper($matches[2]);
531                         if (!strpos($upperQuery,"JOIN")){
532                             $from_pos = strpos($upperQuery , "FROM") + 4;
533                             $where_pos = strpos($upperQuery, "WHERE");
534                             $tablename = trim(substr($upperQuery,$from_pos, $where_pos - $from_pos));
535                         }else{
536                             $tablename = $this->getTableNameFromModuleName($_REQUEST['module'],$sql);
537                         }
538                         //if there is a distinct clause, form query with rownumber after distinct
539                         if ($hasDistinct) {
540                              $newSQL = "SELECT TOP $count * FROM
541                                             (
542                             SELECT ROW_NUMBER() OVER (ORDER BY ".$tablename.".id) AS row_number, count(*) counter, " . $distinctSQLARRAY[0] . "
543                                                         " . $distinctSQLARRAY[1] . "
544                                                     group by " . $grpByStr . "
545                                             )
546                                             AS a
547                                             WHERE row_number > $start";
548                         }
549                         else {
550                              $newSQL = "SELECT TOP $count * FROM
551                                            (
552                                   " . $matches[1] . " ROW_NUMBER() OVER (ORDER BY ".$tablename.".id) AS row_number, " . $matches[2] . $matches[3]. "
553                                            )
554                                            AS a
555                                            WHERE row_number > $start";
556                         }
557                     }
558                 }
559             }
560         }
561
562         $GLOBALS['log']->debug('Limit Query: ' . $newSQL);
563         $result =  $this->query($newSQL, $dieOnError, $msg);
564         $this->dump_slow_queries($newSQL);
565         return $result;
566     }
567
568
569     /**
570      * Searches for begginning and ending characters.  It places contents into
571      * an array and replaces contents in original string.  This is used to account for use of
572      * nested functions while aliasing column names
573      *
574      * @param  string $p_sql     SQL statement
575      * @param  string $strip_beg Beginning character
576      * @param  string $strip_end Ending character
577      * @param  string $patt      Optional, pattern to
578      */
579     private function removePatternFromSQL(
580         $p_sql,
581         $strip_beg,
582         $strip_end,
583         $patt = 'patt')
584     {
585         //strip all single quotes out
586         $beg_sin = 0;
587         $sec_sin = 0;
588         $count = substr_count ( $p_sql, $strip_beg);
589         $increment = 1;
590         if ($strip_beg != $strip_end)
591             $increment = 2;
592
593         $i=0;
594         $offset = 0;
595         $strip_array = array();
596         while ($i<$count && $offset<strlen($p_sql)) {
597             if ($offset > strlen($p_sql))
598                                 break;
599             $beg_sin = strpos($p_sql, $strip_beg, $offset);
600             if (!$beg_sin)
601                 break;
602             $sec_sin = strpos($p_sql, $strip_end, $beg_sin+1);
603             $strip_array[$patt.$i] = substr($p_sql, $beg_sin, $sec_sin - $beg_sin +1);
604             if ($increment > 1) {
605                 //we are in here because beginning and end patterns are not identical, so search for nesting
606                 $exists = strpos($strip_array[$patt.$i], $strip_beg );
607                 if ($exists>=0) {
608                     $nested_pos = (strrpos($strip_array[$patt.$i], $strip_beg ));
609                     $strip_array[$patt.$i] = substr($p_sql,$nested_pos+$beg_sin,$sec_sin - ($nested_pos+$beg_sin)+1);
610                     $p_sql = substr($p_sql, 0, $nested_pos+$beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
611                     $i = $i + 1;
612                     $beg_sin = $nested_pos;
613                     continue;
614                 }
615             }
616             $p_sql = substr($p_sql, 0, $beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
617             //move the marker up
618             $offset = $sec_sin+1;
619
620             $i = $i + 1;
621         }
622         $strip_array['sql_string'] = $p_sql;
623
624         return $strip_array;
625     }
626
627     /**
628      * adds a pattern
629      *
630      * @param  string $token
631      * @param  array  $pattern_array
632      * @return string
633      */
634         private function addPatternToSQL(
635         $token,
636         array $pattern_array
637         )
638     {
639         //strip all single quotes out
640         $pattern_array = array_reverse($pattern_array);
641
642         foreach ($pattern_array as $key => $replace) {
643             $token = str_replace( "##".$key."##", $replace,$token);
644         }
645
646         return $token;
647     }
648
649     /**
650      * gets an alias from the sql statement
651      *
652      * @param  string $sql
653      * @param  string $alias
654      * @return string
655      */
656         private function getAliasFromSQL(
657         $sql,
658         $alias
659         )
660     {
661         $matches = array();
662         preg_match('/^(.*SELECT)(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
663         //parse all single and double  quotes out of array
664         $sin_array = $this->removePatternFromSQL($matches[2], "'", "'","sin_");
665         $new_sql = array_pop($sin_array);
666         $dub_array = $this->removePatternFromSQL($new_sql, "\"", "\"","dub_");
667         $new_sql = array_pop($dub_array);
668
669         //search for parenthesis
670         $paren_array = $this->removePatternFromSQL($new_sql, "(", ")", "par_");
671         $new_sql = array_pop($paren_array);
672
673         //all functions should be removed now, so split the array on comma's
674         $mstr_sql_array = explode(",", $new_sql);
675         foreach($mstr_sql_array as $token ) {
676             if (strpos($token, $alias)) {
677                 //found token, add back comments
678                 $token = $this->addPatternToSQL($token, $paren_array);
679                 $token = $this->addPatternToSQL($token, $dub_array);
680                 $token = $this->addPatternToSQL($token, $sin_array);
681
682                 //log and break out of this function
683                 return $token;
684             }
685         }
686         return null;
687     }
688
689
690     /**
691      * Finds the alias of the order by column, and then return the preceding column name
692      *
693      * @param  string $sql
694      * @param  string $orderMatch
695      * @return string
696      */
697     private function findColumnByAlias(
698         $sql,
699         $orderMatch
700         )
701     {
702         //change case to lowercase
703         $sql = strtolower($sql);
704         $patt = '/\s+'.trim($orderMatch).'\s*,/';
705
706         //check for the alias, it should contain comma, may contain space, \n, or \t
707         $matches = array();
708         preg_match($patt, $sql, $matches, PREG_OFFSET_CAPTURE);
709         $found_in_sql = isset($matches[0][1]) ? $matches[0][1] : false;
710
711
712         //set default for found variable
713         $found = $found_in_sql;
714
715         //if still no match found, then we need to parse through the string
716         if (!$found_in_sql){
717             //get count of how many times the match exists in string
718             $found_count = substr_count($sql, $orderMatch);
719             $i = 0;
720             $first_ = 0;
721             $len = strlen($orderMatch);
722             //loop through string as many times as there is a match
723             while ($found_count > $i) {
724                 //get the first match
725                 $found_in_sql = strpos($sql, $orderMatch,$first_);
726                 //make sure there was a match
727                 if($found_in_sql){
728                     //grab the next 2 individual characters
729                     $str_plusone = substr($sql,$found_in_sql + $len,1);
730                     $str_plustwo = substr($sql,$found_in_sql + $len+1,1);
731                     //if one of those characters is a comma, then we have our alias
732                     if ($str_plusone === "," || $str_plustwo === ","){
733                         //keep track of this position
734                         $found = $found_in_sql;
735                     }
736                 }
737                 //set the offset and increase the iteration counter
738                 $first_ = $found_in_sql+$len;
739                 $i = $i+1;
740             }
741         }
742         //return $found, defaults have been set, so if no match was found it will be a negative number
743         return $found;
744     }
745
746
747     /**
748      * Return the order by string to use in case the column has been aliased
749      *
750      * @param  string $sql
751      * @param  string $orig_order_match
752      * @return string
753      */
754     private function returnOrderBy(
755         $sql,
756         $orig_order_match
757         )
758     {
759         $sql = strtolower($sql);
760         $orig_order_match = trim($orig_order_match);
761         if (strpos($orig_order_match, ".") != 0)
762             //this has a tablename defined, pass in the order match
763             return $orig_order_match;
764
765         //grab first space in order by
766         $firstSpace = strpos($orig_order_match, " ");
767
768         //split order by into column name and ascending/descending
769         $orderMatch = " " . strtolower(substr($orig_order_match, 0, $firstSpace));
770         $asc_desc =  substr($orig_order_match,$firstSpace);
771
772         //look for column name as an alias in sql string
773         $found_in_sql = $this->findColumnByAlias($sql, $orderMatch);
774
775         if (!$found_in_sql) {
776             //check if this column needs the tablename prefixed to it
777             $orderMatch = ".".trim($orderMatch);
778             $colMatchPos = strpos($sql, $orderMatch);
779             if ($colMatchPos !== false) {
780                 //grab sub string up to column name
781                 $containsColStr = substr($sql,0, $colMatchPos);
782                 //get position of first space, so we can grab table name
783                 $lastSpacePos = strrpos($containsColStr, " ");
784                 //use positions of column name, space before name, and length of column to find the correct column name
785                 $col_name = substr($sql, $lastSpacePos, $colMatchPos-$lastSpacePos+strlen($orderMatch));
786                                 //bug 25485. When sorting by a custom field in Account List and then pressing NEXT >, system gives an error
787                                 $containsCommaPos = strpos($col_name, ",");
788                                 if($containsCommaPos !== false) {
789                                         $col_name = substr($col_name, $containsCommaPos+1);
790                                 }
791                 //return column name
792                 return $col_name;
793             }
794             //break out of here, log this
795             $GLOBALS['log']->debug("No match was found for order by, pass string back untouched as: $orig_order_match");
796             return $orig_order_match;
797         }
798         else {
799             //if found, then parse and return
800             //grab string up to the aliased column
801             $GLOBALS['log']->debug("order by found, process sql string");
802
803             $psql = (trim($this->getAliasFromSQL($sql, $orderMatch )));
804             if (empty($psql))
805                 $psql = trim(substr($sql, 0, $found_in_sql));
806
807             //grab the last comma before the alias
808             $comma_pos = strrpos($psql, " ");
809             //substring between the comma and the alias to find the joined_table alias and column name
810             $col_name = substr($psql,0, $comma_pos);
811
812             //make sure the string does not have an end parenthesis
813             //and is not part of a function (i.e. "ISNULL(leads.last_name,'') as name"  )
814             //this is especially true for unified search from home screen
815
816             $alias_beg_pos = 0;
817             if(strpos($psql, " as "))
818                 $alias_beg_pos = strpos($psql, " as ");
819             else if (strncasecmp($psql, 'isnull', 6) != 0)
820                 $alias_beg_pos = strpos($psql, " ");
821
822             if ($alias_beg_pos > 0) {
823                 $col_name = substr($psql,0, $alias_beg_pos );
824             }
825             //add the "asc/desc" order back
826             $col_name = $col_name. " ". $asc_desc;
827
828             //pass in new order by
829             $GLOBALS['log']->debug("order by being returned is " . $col_name);
830             return $col_name;
831         }
832     }
833
834     /**
835      * Take in a string of the module and retrieve the correspondent table name
836      *
837      * @param  string $module_str module name
838      * @param  string $sql        SQL statement
839      * @return string table name
840      */
841     private function getTableNameFromModuleName(
842         $module_str,
843         $sql
844         )
845     {
846
847         global $beanList, $beanFiles;
848         $GLOBALS['log']->debug("Module being processed is " . $module_str);
849         //get the right module files
850         //the module string exists in bean list, then process bean for correct table name
851         //note that we exempt the reports module from this, as queries from reporting module should be parsed for
852         //correct table name.
853         if (($module_str != 'Reports' && $module_str != 'SavedReport') && isset($beanList[$module_str])  &&  isset($beanFiles[$beanList[$module_str]])){
854             //if the class is not already loaded, then load files
855             if (!class_exists($beanList[$module_str]))
856                 require_once($beanFiles[$beanList[$module_str]]);
857
858             //instantiate new bean
859             $module_bean = new $beanList[$module_str]();
860             //get table name from bean
861             $tbl_name = $module_bean->table_name;
862             //make sure table name is not just a blank space, or empty
863             $tbl_name = trim($tbl_name);
864
865             if(empty($tbl_name)){
866                 $GLOBALS['log']->debug("Could not find table name for module $module_str. ");
867                 $tbl_name = $module_str;
868             }
869         }
870         else {
871             //since the module does NOT exist in beanlist, then we have to parse the string
872             //and grab the table name from the passed in sql
873             $GLOBALS['log']->debug("Could not find table name from module in request, retrieve from passed in sql");
874             $tbl_name = $module_str;
875             $sql = strtolower($sql);
876
877             //look for the location of the "from" in sql string
878             $fromLoc = strpos($sql," from " );
879             if ($fromLoc>0){
880                 //found from, substring from the " FROM " string in sql to end
881                 $tableEnd = substr($sql, $fromLoc+6);
882                 //We know that tablename will be next parameter after from, so
883                 //grab the next space after table name.
884                 // 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.
885                 $carriage_ret = strpos($tableEnd,"\n");
886                 $next_space = strpos($tableEnd," " );
887                 if ($carriage_ret < $next_space)
888                     $next_space = $carriage_ret;
889                 if ($next_space > 0) {
890                     $tbl_name= substr($tableEnd,0, $next_space);
891                     if(empty($tbl_name)){
892                         $GLOBALS['log']->debug("Could not find table name sql either, return $module_str. ");
893                         $tbl_name = $module_str;
894                     }
895                 }
896
897                 //grab the table, to see if it is aliased
898                 $aliasTableEnd = trim(substr($tableEnd, $next_space));
899                 $alias_space = strpos ($aliasTableEnd, " " );
900                 if ($alias_space > 0){
901                     $alias_tbl_name= substr($aliasTableEnd,0, $alias_space);
902                     strtolower($alias_tbl_name);
903                     if(empty($alias_tbl_name)
904                         || $alias_tbl_name == "where"
905                         || $alias_tbl_name == "inner"
906                         || $alias_tbl_name == "left"
907                         || $alias_tbl_name == "join"
908                         || $alias_tbl_name == "outer"
909                         || $alias_tbl_name == "right") {
910                         //not aliased, do nothing
911                     }
912                     elseif ($alias_tbl_name == "as") {
913                             //the next word is the table name
914                             $aliasTableEnd = trim(substr($aliasTableEnd, $alias_space));
915                             $alias_space = strpos ($aliasTableEnd, " " );
916                             if ($alias_space > 0) {
917                                 $alias_tbl_name= trim(substr($aliasTableEnd,0, $alias_space));
918                                 if (!empty($alias_tbl_name))
919                                     $tbl_name = $alias_tbl_name;
920                             }
921                     }
922                     else {
923                         //this is table alias
924                         $tbl_name = $alias_tbl_name;
925                     }
926                 }
927             }
928         }
929         //return table name
930         $GLOBALS['log']->debug("Table name for module $module_str is: ".$tbl_name);
931         return $tbl_name;
932     }
933
934
935         /**
936      * @see DBManager::getFieldsArray()
937      */
938         public function getFieldsArray(
939         &$result,
940         $make_lower_case = false
941         )
942         {
943                 $field_array = array();
944
945                 if(! isset($result) || empty($result))
946             return 0;
947
948         $i = 0;
949         while ($i < mssql_num_fields($result)) {
950             $meta = mssql_fetch_field($result, $i);
951             if (!$meta)
952                 return 0;
953             if($make_lower_case==true)
954                 $meta->name = strtolower($meta->name);
955
956             $field_array[] = $meta->name;
957
958             $i++;
959         }
960
961         return $field_array;
962         }
963
964     /**
965      * @see DBManager::getAffectedRowCount()
966      */
967         public function getAffectedRowCount()
968     {
969         return $this->getOne("SELECT @@ROWCOUNT");
970     }
971
972     /**
973      * @see DBManager::describeField()
974      */
975         protected function describeField(
976         $name,
977         $tablename
978         )
979     {
980         global $table_descriptions;
981         if(isset($table_descriptions[$tablename]) && isset($table_descriptions[$tablename][$name])){
982             return      $table_descriptions[$tablename][$name];
983         }
984         $table_descriptions[$tablename] = array();
985
986         $sql = sprintf( "SELECT COLUMN_NAME AS Field
987                                 , DATA_TYPE + CASE WHEN CHARACTER_MAXIMUM_LENGTH IS NOT NULL " .
988                                                         "THEN '(' + RTRIM(CAST(CHARACTER_MAXIMUM_LENGTH AS CHAR)) + ')' " .
989                                                         "ELSE '' END as 'Type'
990                                 , CHARACTER_MAXIMUM_LENGTH
991                                 , IS_NULLABLE AS 'Null'
992                                 , CASE WHEN COLUMN_DEFAULT LIKE '((0))' THEN \"('0')\" ELSE COLUMN_DEFAULT END as 'Default'
993                         FROM INFORMATION_SCHEMA.COLUMNS
994                         WHERE TABLE_NAME = '%s'",
995                         $tablename
996         );
997
998         $result = $this->query($sql);
999         while ($row = $this->fetchByAssoc($result) )
1000             $table_descriptions[$tablename][$row['Field']] = $row;
1001
1002         if (isset($table_descriptions[$tablename][$name]))
1003             return      $table_descriptions[$tablename][$name];
1004
1005         return array();
1006     }
1007
1008
1009
1010         /**
1011      * @see DBManager::fetchByAssoc()
1012      */
1013     public function fetchByAssoc(
1014         &$result,
1015         $rowNum = -1,
1016         $encode = true
1017         )
1018     {
1019         if (!$result)
1020             return false;
1021
1022                 if ($result && $rowNum < 0) {
1023             $row = mssql_fetch_assoc($result);
1024             //MSSQL returns a space " " when a varchar column is empty ("") and not null.
1025             //We need to iterate through the returned row array and strip empty spaces
1026             if(!empty($row)){
1027                 foreach($row as $key => $column) {
1028                     //notice we only strip if one space is returned.  we do not want to strip
1029                     //strings with intentional spaces (" foo ")
1030                     if (!empty($column) && $column ==" ") {
1031                         $row[$key] = '';
1032                     }
1033                 }
1034             }
1035
1036             if($encode && $this->encode&& is_array($row))
1037                 return array_map('to_html', $row);
1038
1039             return $row;
1040                 }
1041
1042                 if ($this->getRowCount($result) > $rowNum) {
1043                         if ( $rowNum == -1 )
1044                 $rowNum = 0;
1045                         @mssql_data_seek($result, $rowNum);
1046         }
1047
1048         $this->lastmysqlrow = $rowNum;
1049         $row = @mssql_fetch_assoc($result);
1050         if($encode && $this->encode && is_array($row))
1051             return array_map('to_html', $row);
1052         return $row;
1053         }
1054
1055     /**
1056      * @see DBManager::quote()
1057      */
1058     public function quote(
1059         $string,
1060         $isLike = true
1061         )
1062     {
1063         return $string = str_replace("'","''", parent::quote($string));
1064     }
1065
1066     /**
1067      * @see DBManager::quoteForEmail()
1068      */
1069     public function quoteForEmail(
1070         $string,
1071         $isLike = true
1072         )
1073     {
1074         return str_replace("'","''", $string);
1075     }
1076
1077
1078     /**
1079      * @see DBManager::tableExists()
1080      */
1081     public function tableExists(
1082         $tableName
1083         )
1084     {
1085         $GLOBALS['log']->info("tableExists: $tableName");
1086
1087         $this->checkConnection();
1088         $result = $this->query(
1089             "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='".$tableName."'");
1090
1091         $rowCount = $this->getRowCount($result);
1092         $this->freeResult($result);
1093         return ($rowCount == 0) ? false : true;
1094     }
1095
1096     /**
1097      * @see DBManager::addIndexes()
1098      */
1099     public function addIndexes(
1100         $tablename,
1101         $indexes,
1102         $execute = true
1103         )
1104     {
1105         $alters = $this->helper->indexSQL($tablename,array(),$indexes);
1106         if ($execute)
1107             $this->query($alters);
1108
1109         return $alters;
1110     }
1111
1112     /**
1113      * @see DBManager::dropIndexes()
1114      */
1115     public function dropIndexes(
1116         $tablename,
1117         $indexes,
1118         $execute = true
1119         )
1120     {
1121         $sql = '';
1122         foreach ($indexes as $index) {
1123             if ( !empty($sql) ) $sql .= ";";
1124             $name = $index['name'];
1125             if($execute)
1126                 unset($GLOBALS['table_descriptions'][$tablename]['indexes'][$name]);
1127             if ($index['type'] == 'primary')
1128                 $sql .= "ALTER TABLE $tablename DROP CONSTRAINT $name";
1129             else
1130                 $sql .= "DROP INDEX $name on $tablename";
1131         }
1132         if (!empty($sql))
1133             if($execute)
1134                 $this->query($sql);
1135
1136         return $sql;
1137     }
1138
1139     /**
1140      * @see DBManager::checkQuery()
1141      */
1142     protected function checkQuery(
1143         $sql
1144         )
1145     {
1146         return true;
1147     }
1148
1149     /**
1150      * @see DBManager::getTablesArray()
1151      */
1152     public function getTablesArray()
1153     {
1154         $GLOBALS['log']->debug('MSSQL fetching table list');
1155
1156         if($this->getDatabase()) {
1157             $tables = array();
1158             $r = $this->query('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES');
1159             if (is_resource($r)) {
1160                 while ($a = $this->fetchByAssoc($r))
1161                     $tables[] = $a['TABLE_NAME'];
1162
1163                 return $tables;
1164             }
1165         }
1166
1167         return false; // no database available
1168     }
1169
1170
1171     /**
1172      * This call is meant to be used during install, when Full Text Search is enabled
1173      * Indexing would always occur after a fresh sql server install, so this code creates
1174      * a catalog and table with full text index.
1175      */
1176     public function wakeupFTS()
1177     {
1178         $GLOBALS['log']->debug('MSSQL about to wakeup FTS');
1179
1180         if($this->getDatabase()) {
1181                 //create wakup catalog
1182                 $FTSqry[] = "if not exists(  select * from sys.fulltext_catalogs where name ='wakeup_catalog' )
1183                 CREATE FULLTEXT CATALOG wakeup_catalog
1184                 ";
1185
1186                 //drop wakeup table if it exists
1187                 $FTSqry[] = "IF EXISTS(SELECT 'fts_wakeup' FROM sysobjects WHERE name = 'fts_wakeup' AND xtype='U')
1188                     DROP TABLE fts_wakeup
1189                 ";
1190                 //create wakeup table
1191                 $FTSqry[] = "CREATE TABLE fts_wakeup(
1192                     id varchar(36) NOT NULL CONSTRAINT pk_fts_wakeup_id PRIMARY KEY CLUSTERED (id ASC ),
1193                     body text NULL,
1194                     kb_index int IDENTITY(1,1) NOT NULL CONSTRAINT wakeup_fts_unique_idx UNIQUE NONCLUSTERED
1195                 )
1196                 ";
1197                 //create full text index
1198                  $FTSqry[] = "CREATE FULLTEXT INDEX ON fts_wakeup
1199                 (
1200                     body
1201                     Language 0X0
1202                 )
1203                 KEY INDEX wakeup_fts_unique_idx ON wakeup_catalog
1204                 WITH CHANGE_TRACKING AUTO
1205                 ";
1206
1207                 //insert dummy data
1208                 $FTSqry[] = "INSERT INTO fts_wakeup (id ,body)
1209                 VALUES ('".create_guid()."', 'SugarCRM Rocks' )";
1210
1211
1212                 //create queries to stop and restart indexing
1213                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup STOP POPULATION';
1214                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup DISABLE';
1215                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup ENABLE';
1216                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING MANUAL';
1217                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup START FULL POPULATION';
1218                 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING AUTO';
1219
1220                 foreach($FTSqry as $q){
1221                     sleep(3);
1222                     $this->query($q);
1223                 }
1224
1225
1226         }
1227
1228         return false; // no database available
1229     }
1230
1231     /**
1232      * @see DBManager::convert()
1233      */
1234     public function convert(
1235         $string,
1236         $type,
1237         array $additional_parameters = array(),
1238         array $additional_parameters_oracle_only = array()
1239         )
1240     {
1241         // convert the parameters array into a comma delimited string
1242         $additional_parameters_string = '';
1243         if (!empty($additional_parameters))
1244             $additional_parameters_string = ','.implode(',',$additional_parameters);
1245
1246         switch ($type) {
1247         case 'today': return "GETDATE()";
1248         case 'left': return "LEFT($string".$additional_parameters_string.")";
1249         case 'date_format':
1250             if(!empty($additional_parameters) && in_array("'%Y-%m'", $additional_parameters))
1251                return "CONVERT(varchar(7),". $string . ",120)";
1252             else
1253                return "CONVERT(varchar(10),". $string . ",120)";
1254         case 'IFNULL': return "ISNULL($string".$additional_parameters_string.")";
1255         case 'CONCAT': return "$string+".implode("+",$additional_parameters);
1256         case 'text2char': return "CAST($string AS varchar(8000))";
1257         }
1258
1259         return "$string";
1260     }
1261
1262     /**
1263      * @see DBManager::concat()
1264      */
1265     public function concat(
1266         $table,
1267         array $fields
1268         )
1269     {
1270         $ret = '';
1271
1272         foreach ( $fields as $index => $field )
1273                         if (empty($ret))
1274                             $ret =  db_convert($table.".".$field,'IFNULL', array("''"));
1275                         else
1276                             $ret .=     " + ' ' + ".db_convert($table.".".$field,'IFNULL', array("''"));
1277
1278                 return $ret;
1279     }
1280
1281     /**
1282      * @see DBManager::fromConvert()
1283      */
1284     public function fromConvert(
1285         $string,
1286         $type)
1287     {
1288         switch($type) {
1289         case 'datetime': return substr($string, 0,19);
1290         case 'date': return substr($string, 0,11);
1291         case 'time': return substr($string, 11);
1292                 }
1293
1294                 return $string;
1295     }
1296 }