]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/database/MysqliManager.php
Release 6.2.0
[Github/sugarcrm.git] / include / database / MysqliManager.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40 * Description: This file handles the Data base functionality for the application.
41 * It acts as the DB abstraction layer for the application. It depends on helper classes
42 * which generate the necessary SQL. This sql is then passed to PEAR DB classes.
43 * The helper class is chosen in DBManagerFactory, which is driven by 'db_type' in 'dbconfig' under config.php.
44 *
45 * All the functions in this class will work with any bean which implements the meta interface.
46 * The passed bean is passed to helper class which uses these functions to generate correct sql.
47 *
48 * The meta interface has the following functions:
49 * getTableName()                Returns table name of the object.
50 * getFieldDefinitions()         Returns a collection of field definitions in order.
51 * getFieldDefintion(name)       Return field definition for the field.
52 * getFieldValue(name)           Returns the value of the field identified by name.
53 *                               If the field is not set, the function will return boolean FALSE.
54 * getPrimaryFieldDefinition()   Returns the field definition for primary key
55 *
56 * The field definition is an array with the following keys:
57 *
58 * name      This represents name of the field. This is a required field.
59 * type      This represents type of the field. This is a required field and valid values are:
60 *           �   int
61 *           �   long
62 *           �   varchar
63 *           �   text
64 *           �   date
65 *           �   datetime
66 *           �   double
67 *           �   float
68 *           �   uint
69 *           �   ulong
70 *           �   time
71 *           �   short
72 *           �   enum
73 * length    This is used only when the type is varchar and denotes the length of the string.
74 *           The max value is 255.
75 * enumvals  This is a list of valid values for an enum separated by "|".
76 *           It is used only if the type is �enum�;
77 * required  This field dictates whether it is a required value.
78 *           The default value is �FALSE�.
79 * isPrimary This field identifies the primary key of the table.
80 *           If none of the fields have this flag set to �TRUE�,
81 *           the first field definition is assume to be the primary key.
82 *           Default value for this field is �FALSE�.
83 * default   This field sets the default value for the field definition.
84 *
85 *
86 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
87 * All Rights Reserved.
88 * Contributor(s): ______________________________________..
89 ********************************************************************************/
90
91 //Technically we can port all the functions in the latest bean to this file
92 // that is what PEAR is doing anyways.
93
94 require_once('include/database/MysqlManager.php');
95
96 class MysqliManager extends MysqlManager
97 {
98     /**
99      * @see DBManager::$dbType
100      */
101     public $dbType = 'mysql';
102
103     /**
104      * @see DBManager::$backendFunctions
105      */
106     protected $backendFunctions = array(
107         'free_result'        => 'mysqli_free_result',
108         'close'              => 'mysqli_close',
109         'row_count'          => 'mysqli_num_rows',
110         'affected_row_count' => 'mysqli_affected_rows',
111         );
112
113     /**
114      * @see DBManager::checkError()
115      */
116     public function checkError(
117         $msg = '',
118         $dieOnError = false
119         )
120     {
121         if (DBManager::checkError($msg, $dieOnError))
122             return true;
123
124         $userMsg = inDeveloperMode()?"$msg: ":"";
125
126         if (mysqli_errno($this->getDatabase())){
127             if($this->dieOnError || $dieOnError){
128                 $GLOBALS['log']->fatal("$msg: MySQL error ".mysqli_errno($this->database).": ".mysqli_error($this->database));
129                 sugar_die ($userMsg.$GLOBALS['app_strings']['ERR_DB_FAIL']);
130             }
131             else{
132                 $this->last_error = $userMsg."MySQL error ".mysqli_errno($this->database).": ".mysqli_error($this->database);
133                 $GLOBALS['log']->error("$msg: MySQL error ".mysqli_errno($this->database).": ".mysqli_error($this->database));
134
135             }
136             return true;
137         }
138         return false;
139     }
140
141     /**
142      * @see MysqlManager::query()
143      */
144     public function query(
145         $sql,
146         $dieOnError = false,
147         $msg = '',
148         $suppress = false,
149         $autofree = false
150         )
151     {
152         static $queryMD5 = array();
153
154         parent::countQuery($sql);
155         $GLOBALS['log']->info('Query:' . $sql);
156         $this->checkConnection();
157         //$this->freeResult();
158         $this->query_time = microtime(true);
159         $this->lastsql = $sql;
160         if ($suppress==true){
161         }
162         else {
163             $result = mysqli_query($this->database,$sql);
164         }
165         $md5 = md5($sql);
166
167         if (empty($queryMD5[$md5]))
168                 $queryMD5[$md5] = true;
169
170         $this->lastmysqlrow = -1;
171         $this->query_time = microtime(true) - $this->query_time;
172         $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
173
174         // This is some heavy duty debugging, leave commented out unless you need this:
175         /*
176         $bt = debug_backtrace();
177         for ( $i = count($bt) ; $i-- ; $i > 0 ) {
178             if ( strpos('MysqliManager.php',$bt[$i]['file']) === false ) {
179                 $line = $bt[$i];
180             }
181         }
182
183         $GLOBALS['log']->fatal("${line['file']}:${line['line']} ${line['function']} \nQuery: $sql\n");
184         */
185
186
187                 $this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
188         if($autofree)
189             $this->lastResult[] =& $result;
190
191         return $result;
192     }
193
194     /**
195      * @see DBManager::getFieldsArray()
196      */
197     public function getFieldsArray(
198         &$result,
199         $make_lower_case = false
200         )
201     {
202         $field_array = array();
203
204         if (!isset($result) || empty($result))
205             return 0;
206
207         $i = 0;
208         while ($i < mysqli_num_fields($result)) {
209             $meta = mysqli_fetch_field_direct($result, $i);
210             if (!$meta)
211                 return 0;
212
213             if($make_lower_case == true)
214                 $meta->name = strtolower($meta->name);
215
216             $field_array[] = $meta->name;
217
218             $i++;
219         }
220
221         return $field_array;
222     }
223
224     /**
225      * @see DBManager::fetchByAssoc()
226      */
227     public function fetchByAssoc(
228         &$result,
229         $rowNum = -1,
230         $encode = true
231         )
232     {
233         if (!$result)
234             return false;
235
236         if ($result && $rowNum > -1) {
237             if ($this->getRowCount($result) > $rowNum)
238                 mysqli_data_seek($result, $rowNum);
239             $this->lastmysqlrow = $rowNum;
240         }
241
242         $row = mysqli_fetch_assoc($result);
243
244         if ($encode && $this->encode && is_array($row))
245             return array_map('to_html', $row);
246
247         return $row;
248     }
249
250     /**
251      * @see DBManager::quote()
252      */
253     public function quote(
254         $string,
255         $isLike = true
256         )
257     {
258         return mysqli_escape_string($this->getDatabase(),DBManager::quote($string));
259     }
260
261     /**
262      * @see DBManager::quoteForEmail()
263      */
264     public function quoteForEmail(
265         $string,
266         $isLike = true
267         )
268     {
269         return mysqli_escape_string($this->getDatabase(),$string);
270     }
271
272     /**
273      * @see DBManager::connect()
274      */
275     public function connect(
276         array $configOptions = null,
277         $dieOnError = false
278         )
279     {
280         global $sugar_config;
281
282         if (is_null($configOptions))
283             $configOptions = $sugar_config['dbconfig'];
284
285         if(!isset($this->database)) {
286
287                 //mysqli connector has a separate parameter for port.. We need to separate it out from the host name
288                         $dbhost=$configOptions['db_host_name'];
289                 $dbport=null;
290                 $pos=strpos($configOptions['db_host_name'],':');
291                 if ($pos !== false) {
292                         $dbhost=substr($configOptions['db_host_name'],0,$pos);
293                         $dbport=substr($configOptions['db_host_name'],$pos+1);
294                 }
295
296                 $this->database = mysqli_connect($dbhost,$configOptions['db_user_name'],$configOptions['db_password'],$configOptions['db_name'],$dbport);
297                 if(empty($this->database)) {
298                     $GLOBALS['log']->fatal("Could not connect to DB server ".$dbhost." as ".$configOptions['db_user_name'].". port " .$dbport . ": " . mysqli_connect_error());
299                 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
300                 }
301         }
302         if(!@mysqli_select_db($this->database,$configOptions['db_name'])) {
303             $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}: " . mysqli_connect_error());
304             sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
305         }
306
307         // cn: using direct calls to prevent this from spamming the Logs
308         mysqli_query($this->database,"SET CHARACTER SET utf8"); // no quotes around "[charset]"
309         mysqli_query($this->database,"SET NAMES 'utf8'");
310
311         if($this->checkError('Could Not Connect', $dieOnError))
312             $GLOBALS['log']->info("connected to db");
313     }
314 }
315
316 ?>