BxDolDb.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. <?php defined('BX_DOL') or defined('BX_DOL_INSTALL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. define('BX_DB_MODE_SILENT', PDO::ERRMODE_SILENT);
  10. define('BX_DB_MODE_EXCEPTION', PDO::ERRMODE_EXCEPTION);
  11. define('BX_DB_ERR_CONNECT_FAILD', 1);
  12. define('BX_DB_ERR_QUERY_ERROR', 2);
  13. define('BX_DB_ERR_ESCAPE', 3);
  14. define('BX_PDO_STATE_NOT_EXECUTED', NULL);
  15. define('BX_PDO_STATE_SUCCESS', '00000');
  16. class BxDolDb extends BxDolFactory implements iBxDolSingleton
  17. {
  18. protected static $_rLink;
  19. protected static $_aDbCacheData;
  20. protected static $_aParams;
  21. protected static $_sParamsCacheName = 'sys_options';
  22. protected static $_sParamsCacheNameMixed = 'sys_options_mixed_';
  23. protected static $_sParamsCacheNameMix = 'sys_options_mix_';
  24. protected static $_sErrorKey = 'bx_db_error';
  25. protected static $_aErrors = array(
  26. BX_DB_ERR_CONNECT_FAILD => 'Database connect failed',
  27. BX_DB_ERR_QUERY_ERROR => 'Database query error',
  28. BX_DB_ERR_ESCAPE => 'Escape string error'
  29. );
  30. protected static $_bReadOnlyMode = true;
  31. protected static $_bMultuServersMode = false;
  32. protected $_bPdoPersistent;
  33. protected $_iPdoFetchType;
  34. protected $_iPdoErrorMode;
  35. protected $_bErrorChecking;
  36. protected $_aError;
  37. protected $_sHost, $_sPort, $_sSocket, $_sDbname, $_sUser, $_sPassword, $_sCharset, $_sStorageEngine;
  38. protected $_oStatement = null;
  39. protected $_oDbCacheObject = null;
  40. /**
  41. * set database parameters and connect to it
  42. */
  43. protected function __construct($aDbConf = false)
  44. {
  45. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  46. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  47. parent::__construct();
  48. $this->_bPdoPersistent = true;
  49. if (defined('BX_DATABASE_PERSISTENT'))
  50. $this->_bPdoPersistent = (bool)BX_DATABASE_PERSISTENT;
  51. $this->_iPdoFetchType = PDO::FETCH_ASSOC;
  52. $this->_iPdoErrorMode = BX_DB_MODE_EXCEPTION;
  53. $this->_bErrorChecking = true;
  54. $this->_aError = array();
  55. $this->_sStorageEngine = 'MYISAM';
  56. if (defined('BX_DATABASE_ENGINE'))
  57. $this->_sStorageEngine = BX_DATABASE_ENGINE;
  58. $this->_sCharset = 'utf8mb4';
  59. if($aDbConf === false) {
  60. $this->_sHost = BX_DATABASE_HOST;
  61. $this->_sPort = BX_DATABASE_PORT;
  62. $this->_sSocket = BX_DATABASE_SOCK;
  63. $this->_sDbname = BX_DATABASE_NAME;
  64. $this->_sUser = BX_DATABASE_USER;
  65. $this->_sPassword = BX_DATABASE_PASS;
  66. }
  67. else {
  68. $this->_sHost = $aDbConf['host'];
  69. $this->_sPort = $aDbConf['port'];
  70. $this->_sSocket = $aDbConf['sock'];
  71. $this->_sDbname = $aDbConf['name'];
  72. $this->_sUser = $aDbConf['user'];
  73. $this->_sPassword = $aDbConf['pwd'];
  74. if(isset($aDbConf['charset']))
  75. $this->_sCharset = $aDbConf['charset'];
  76. if(isset($aDbConf['error_checking']))
  77. $this->_bErrorChecking = $aDbConf['error_checking'];
  78. if(isset($aDbConf['storage_engine']))
  79. $this->_sStorageEngine = $aDbConf['storage_engine'];
  80. }
  81. @set_exception_handler(array($this, 'pdoExceptionHandler'));
  82. }
  83. /**
  84. * Prevent cloning the instance
  85. */
  86. public function __clone()
  87. {
  88. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  89. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  90. }
  91. /**
  92. * Get singleton instance of the class
  93. */
  94. public static function getInstance()
  95. {
  96. $null = null;
  97. return self::getInstanceWithConf(false, $null);
  98. }
  99. public static function getInstanceWithConf($aDbConf, &$sError)
  100. {
  101. if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
  102. if($aDbConf === false && !defined('BX_DATABASE_HOST'))
  103. return null;
  104. $o = new BxDolDb($aDbConf);
  105. $sErrorMessage = $o->connect();
  106. if($sErrorMessage) {
  107. if($sError !== null)
  108. $sError = $sErrorMessage;
  109. return null;
  110. }
  111. $GLOBALS['bxDolClasses'][__CLASS__] = $o;
  112. }
  113. return $GLOBALS['bxDolClasses'][__CLASS__];
  114. }
  115. public static function getLink()
  116. {
  117. return self::$_rLink;
  118. }
  119. public function setReadOnlyMode($b)
  120. {
  121. if ($b == self::$_bReadOnlyMode)
  122. return;
  123. self::$_bReadOnlyMode = $b;
  124. if (self::$_bMultuServersMode) {
  125. $this->disconnect();
  126. $this->connect();
  127. }
  128. }
  129. protected function balancer()
  130. {
  131. // regular mode - one DB server
  132. if (!is_array($this->_sHost))
  133. return array($this->_sHost, $this->_sPort, $this->_sSocket, $this->_sUser, $this->_sPassword, $this->_sDbname);
  134. $iServersNum = count($this->_sHost);
  135. if ($iServersNum > 1)
  136. self::$_bMultuServersMode = true;
  137. // in read/write mode always use first server, which should be always master (also check for regular mode but with array with 1 item)
  138. if (!self::$_bReadOnlyMode || 1 == $iServersNum)
  139. $i = 0;
  140. // in case of 2 servers - always use second server, in read only mode
  141. elseif (2 == $iServersNum)
  142. $i = 1;
  143. // when there are more that 2 servers, randomly select read only server
  144. else
  145. $i = rand(1, $iServersNum-1);
  146. return array($this->_sHost[$i], $this->_sPort[$i], $this->_sSocket[$i], $this->_sUser[$i], $this->_sPassword[$i], $this->_sDbname[$i]);
  147. }
  148. /**
  149. * connect to database with appointed parameters
  150. */
  151. public function connect()
  152. {
  153. if(self::$_rLink)
  154. return;
  155. list ($sHost, $sPort, $sSocket, $sUser, $sPassword, $sDBName) = $this->balancer();
  156. try {
  157. $sDsn = "mysql:host=" . $sHost . ";";
  158. $sDsn .= $sPort ? "port=" . $sPort . ";" : "";
  159. $sDsn .= $sSocket ? "unix_socket=" . $sSocket . ";" : "";
  160. $sDsn .= "dbname=" . $sDBName . ";charset=" . $this->_sCharset;
  161. self::$_rLink = new PDO($sDsn, $sUser, $sPassword, array(
  162. PDO::ATTR_ERRMODE => $this->_iPdoErrorMode,
  163. PDO::ATTR_DEFAULT_FETCH_MODE => $this->_iPdoFetchType,
  164. PDO::ATTR_PERSISTENT => $this->_bPdoPersistent
  165. ));
  166. $this->pdoExec("SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'");
  167. $this->pdoExec("SET sql_mode = ''");
  168. if (0 == strcasecmp($this->_sStorageEngine, 'INNODB'))
  169. $this->pdoExec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
  170. $sVer = $this->getVersion();
  171. $sStorageEngine = !$sVer || version_compare($sVer, '5.7.5', '>=') ? 'default_storage_engine' : 'storage_engine';
  172. $this->pdoExec("SET $sStorageEngine=" . $this->_sStorageEngine);
  173. $this->cleanMemoryAll();
  174. }
  175. catch (PDOException $oException) {
  176. $oException->errorInfo[self::$_sErrorKey] = array(
  177. 'code' => BX_DB_ERR_CONNECT_FAILD,
  178. 'message' => $oException->getMessage(),
  179. 'trace' => $oException->getTrace()
  180. );
  181. throw $oException;
  182. }
  183. }
  184. /**
  185. * close mysql connection
  186. */
  187. public function disconnect()
  188. {
  189. self::$_rLink = null;
  190. }
  191. /**
  192. * check mysql connection
  193. */
  194. public function ping()
  195. {
  196. try {
  197. $this->pdoQuery("SELECT 1");
  198. }
  199. catch (PDOException $e) {
  200. return false;
  201. }
  202. return true;
  203. }
  204. /**
  205. * Can be used to execute queries which shouldn't return data
  206. */
  207. public function pdoExec($sQuery)
  208. {
  209. return self::$_rLink->exec($sQuery);
  210. }
  211. /**
  212. * Executes query and returns PDOStatement object or false
  213. */
  214. public function pdoQuery($sQuery)
  215. {
  216. return self::$_rLink->query($sQuery);
  217. }
  218. /**
  219. * database query exception handler for exceptions appeared out of the try/catch block
  220. */
  221. public function pdoExceptionHandler($oException)
  222. {
  223. if(!($oException instanceof PDOException)) {
  224. throw $oException;
  225. return;
  226. }
  227. if(!isset($oException->errorInfo[self::$_sErrorKey]))
  228. $oException->errorInfo[self::$_sErrorKey] = array(
  229. 'code' => BX_DB_ERR_QUERY_ERROR,
  230. 'message' => !empty($oException->errorInfo[2]) ? $oException->errorInfo[2] : $oException->getMessage(),
  231. 'trace' => $oException->getTrace()
  232. );
  233. $this->error($oException->errorInfo[self::$_sErrorKey]);
  234. }
  235. /**
  236. * get mysql option
  237. */
  238. function getOption($sName)
  239. {
  240. $oStatement = $this->pdoQuery("SELECT @@{$sName}");
  241. return $this->getOne($oStatement);
  242. }
  243. /**
  244. * execute sql query and return one value result
  245. */
  246. public function getOne($oStatement, $aBindings = array(), $iIndex = 0)
  247. {
  248. if(!$oStatement)
  249. return false;
  250. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  251. $oStatement = $this->prepare($oStatement);
  252. $aResult = array();
  253. if($this->res($oStatement, $aBindings))
  254. $aResult = $oStatement->fetch(PDO::FETCH_NUM);
  255. return is_array($aResult) && count($aResult) ? $aResult[$iIndex] : false;
  256. }
  257. /**
  258. * execute sql query and return one row result
  259. */
  260. function getRow($oStatement, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  261. {
  262. $aResult = array();
  263. if(!$oStatement)
  264. return $aResult;
  265. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  266. $oStatement = $this->prepare($oStatement);
  267. if(!in_array($iFetchType, array(PDO::FETCH_NUM, PDO::FETCH_ASSOC, PDO::FETCH_BOTH)))
  268. $iFetchType = $this->_iPdoFetchType;
  269. if(!$this->res($oStatement, $aBindings))
  270. return array();
  271. $aResult = $oStatement->fetch($iFetchType);
  272. if($aResult === false)
  273. return array();
  274. return $aResult;
  275. }
  276. /**
  277. * execute sql query and return a column as result
  278. */
  279. function getColumn($oStatement, $aBindings = array(), $iFetchColumnNumber = 0)
  280. {
  281. $aResult = array();
  282. if(!$oStatement)
  283. return $aResult;
  284. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  285. $oStatement = $this->prepare($oStatement);
  286. if(!$this->res($oStatement, $aBindings))
  287. return array();
  288. $aResult = $oStatement->fetchAll(PDO::FETCH_COLUMN, $iFetchColumnNumber);
  289. if($aResult === false)
  290. return array();
  291. return $aResult;
  292. }
  293. /**
  294. * execute sql query and return the first row of result
  295. * and keep $array type and poiter to all data
  296. */
  297. public function getFirstRow($oStatement, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  298. {
  299. if(!$oStatement)
  300. return array();
  301. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  302. $oStatement = $this->prepare($oStatement);
  303. if(!in_array($iFetchType, array(PDO::FETCH_NUM, PDO::FETCH_ASSOC, PDO::FETCH_BOTH)))
  304. $iFetchType = $this->_iPdoFetchType;
  305. if(!$this->res($oStatement, $aBindings))
  306. return array();
  307. $aResult = $oStatement->fetch($iFetchType);
  308. if($aResult === false)
  309. return array();
  310. $this->_oStatement = $oStatement;
  311. return $aResult;
  312. }
  313. /**
  314. * return next row of pointed last getFirstRow calling data
  315. */
  316. public function getNextRow($iFetchType = PDO::FETCH_ASSOC)
  317. {
  318. if(!$this->_oStatement)
  319. return array();
  320. if(!in_array($iFetchType, array(PDO::FETCH_NUM, PDO::FETCH_ASSOC, PDO::FETCH_BOTH)))
  321. $iFetchType = $this->_iPdoFetchType;
  322. $aResult = $this->_oStatement->fetch($iFetchType);
  323. if($aResult !== false)
  324. return $aResult;
  325. $this->_oStatement = null;
  326. return array();
  327. }
  328. /**
  329. * execute sql query and return table of records as result
  330. */
  331. public function getAll($oStatement, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  332. {
  333. $aResult = array();
  334. if(!$oStatement)
  335. return $aResult;
  336. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  337. $oStatement = $this->prepare($oStatement);
  338. if(!in_array($iFetchType, array(PDO::FETCH_NUM, PDO::FETCH_ASSOC, PDO::FETCH_BOTH)))
  339. $iFetchType = $this->_iPdoFetchType;
  340. if(!$this->res($oStatement, $aBindings))
  341. return array();
  342. $aResult = $oStatement->fetchAll($iFetchType);
  343. if($aResult === false)
  344. return array();
  345. return $aResult;
  346. }
  347. /**
  348. * Executes sql query and returns table of records as result.
  349. *
  350. * @deprecated use getAll instead.
  351. */
  352. public function fillArray($oStatement, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  353. {
  354. return $this->getAll($oStatement, $aBindings, $iFetchType);
  355. }
  356. /**
  357. * execute sql query and return table of records as result
  358. */
  359. public function getAllWithKey($oStatement, $sFieldKey, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  360. {
  361. $aResult = array();
  362. if(!$oStatement)
  363. return $aResult;
  364. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  365. $oStatement = $this->prepare($oStatement);
  366. $aRow = $this->getFirstRow($oStatement, $aBindings, $iFetchType);
  367. while(!empty($aRow)) {
  368. $aResult[$aRow[$sFieldKey]] = $aRow;
  369. $aRow = $this->getNextRow($iFetchType);
  370. }
  371. return $aResult;
  372. }
  373. /**
  374. * execute sql query and return table of records as result
  375. */
  376. public function getPairs($oStatement, $sFieldKey, $sFieldValue, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  377. {
  378. $aResult = array();
  379. if(!$oStatement)
  380. return $aResult;
  381. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  382. $oStatement = $this->prepare($oStatement);
  383. $aRow = $this->getFirstRow($oStatement, $aBindings, $iFetchType);
  384. while(!empty($aRow)) {
  385. $aResult[$aRow[$sFieldKey]] = $aRow[$sFieldValue];
  386. $aRow = $this->getNextRow($iFetchType);
  387. }
  388. return $aResult;
  389. }
  390. /**
  391. * return number of affected rows in current mysql result
  392. *
  393. * NOTE: PDOStatement::rowCount works for SELECT queries in MySQL.
  394. * So, this method should be rewritten if the other DB engine will be used.
  395. */
  396. public function getNumRows($oStatement = null)
  397. {
  398. if($oStatement && ($oStatement instanceof PDOStatement))
  399. return $oStatement->rowCount();
  400. if($this->_oStatement && ($this->_oStatement instanceof PDOStatement))
  401. return $this->_oStatement->rowCount();
  402. return 0;
  403. }
  404. /**
  405. * returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement.
  406. */
  407. public function getAffectedRows($oStatement = null)
  408. {
  409. return $this->getNumRows($oStatement);
  410. }
  411. public function lastId()
  412. {
  413. return self::$_rLink->lastInsertId();
  414. }
  415. /**
  416. * execute any query return number of rows affected/false
  417. */
  418. public function query($oStatement, $aBindings = array(), $bVerbose = null)
  419. {
  420. if(!$oStatement)
  421. return false;
  422. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  423. $oStatement = $this->prepare($oStatement);
  424. if($this->res($oStatement, $aBindings, $bVerbose))
  425. return $oStatement->rowCount();
  426. return false;
  427. }
  428. /**
  429. * execute any query
  430. */
  431. public function res($oStatement, $aBindings = array(), $bVerbose = null)
  432. {
  433. if(!$oStatement || !($oStatement instanceof PDOStatement))
  434. return false;
  435. if($oStatement->errorCode() == BX_PDO_STATE_SUCCESS)
  436. return true;
  437. if(isset($GLOBALS['bx_profiler']))
  438. $GLOBALS['bx_profiler']->beginQuery($oStatement->queryString);
  439. for ($iAttempts = 3; $iAttempts > 0; --$iAttempts) {
  440. $oException = null;
  441. $iErrorCode = 0;
  442. $bResult = false;
  443. try {
  444. $bResult = $this->executeStatement($oStatement, $aBindings, $bVerbose, $iErrorCode);
  445. } catch (PDOException $oException) {
  446. $iErrorCode = $oException->errorInfo[1];
  447. }
  448. // if deadlock timeout - try again, make sure that deadlock timeout is short
  449. if (!$bResult && (1205 == $iErrorCode || 1213 == $iErrorCode)) {
  450. continue;
  451. }
  452. // if mysql connection is lost - reconnect and try again
  453. if(!$bResult && (2006 == $iErrorCode || !$this->ping())) {
  454. $this->disconnect();
  455. $this->connect();
  456. continue;
  457. }
  458. // in all other cases exit from the loop
  459. if ($oException)
  460. throw $oException;
  461. break;
  462. }
  463. if(isset($GLOBALS['bx_profiler']))
  464. $GLOBALS['bx_profiler']->endQuery($oStatement);
  465. //is needed for SILENT mode
  466. if(!$bResult && !empty($this->_aError))
  467. $this->error($this->_aError);
  468. return $bResult;
  469. }
  470. /**
  471. * get mysql server info
  472. */
  473. public function getServerInfo()
  474. {
  475. return self::$_rLink->getAttribute(PDO::ATTR_SERVER_VERSION);
  476. }
  477. /**
  478. * get mysql version
  479. */
  480. public function getVersion()
  481. {
  482. $s = $this->getOne("SELECT VERSION()");
  483. return preg_match("/([0-9\.]+)/", $s, $m) ? $m[1] : false;
  484. }
  485. /**
  486. * get list of tables in database
  487. */
  488. public function listTables()
  489. {
  490. $oStatement = $this->pdoQuery("SHOW TABLES FROM `" . BX_DATABASE_NAME . "`");
  491. return $this->getColumn($oStatement);
  492. }
  493. public function getFields($sTable)
  494. {
  495. $oStatement = $this->pdoQuery("SHOW COLUMNS FROM `" . $sTable . "`");
  496. $aFields = $this->getAll($oStatement);
  497. $aResult = array('original' => array(), 'uppercase' => array());
  498. foreach($aFields as $aField) {
  499. $aResult['original'][] = $aField['Field'];
  500. $aResult['uppercase'][] = strtoupper($aField['Field']);
  501. }
  502. return $aResult;
  503. }
  504. public function fetchField($oStatement, $iField, $aBindings = array())
  505. {
  506. $aResult = array();
  507. if(!$oStatement)
  508. return $aResult;
  509. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement)) {
  510. $oStatement = $this->prepare($oStatement);
  511. if(!$this->res($oStatement, $aBindings))
  512. return $aResult;
  513. }
  514. return $oStatement->getColumnMeta($iField);
  515. }
  516. public function isTableExists($sTable)
  517. {
  518. $aTableNames = $this->listTables();
  519. foreach($aTableNames as $iKey => $sTableName)
  520. $aTableNames[$iKey] = strtoupper($sTableName);
  521. return in_array(strtoupper($sTable), $aTableNames);
  522. }
  523. public function isFieldExists($sTable, $sFieldName)
  524. {
  525. $aFields = $this->getFields($sTable);
  526. return in_array(strtoupper($sFieldName), $aFields['uppercase']);
  527. }
  528. public function isIndexExists($sTable, $sIndexName)
  529. {
  530. $bIndex = false;
  531. $aIndexes = $this->getAll("SHOW INDEXES FROM `" . $sTable . "`");
  532. foreach($aIndexes as $aIndex)
  533. if($aIndex['Key_name'] == $sIndexName) {
  534. $bIndex = true;
  535. break;
  536. }
  537. return $bIndex;
  538. }
  539. public function error($aError)
  540. {
  541. $sErrorType = self::$_aErrors[$aError['code']];
  542. $bVerbose = isset($aError['verbose']) ? (bool)$aError['verbose'] : $this->_bErrorChecking;
  543. if(!$bVerbose) {
  544. $this->log($sErrorType . ': ' . $aError['message']);
  545. if (!defined('BX_DOL_INSTALL')) // this is needed to display error during installation
  546. return;
  547. }
  548. if((defined('BX_DB_FULL_VISUAL_PROCESSING') && BX_DB_FULL_VISUAL_PROCESSING) || defined('BX_DOL_INSTALL')) {
  549. $sOutput = '<div style="border:2px solid red;padding:4px;width:600px;margin:0px auto;">';
  550. $sOutput .= '<div style="text-align:center;background-color:red;color:white;font-weight:bold;">Error</div>';
  551. $sOutput .= '<div style="text-align:center;">' . $sErrorType . '</div>';
  552. if((defined('BX_DB_FULL_DEBUG_MODE') && BX_DB_FULL_DEBUG_MODE) || defined('BX_DOL_INSTALL'))
  553. $sOutput .= $this->errorOutput($aError);
  554. $sOutput .= '</div>';
  555. }
  556. if(defined('BX_DB_DO_EMAIL_ERROR_REPORT') && BX_DB_DO_EMAIL_ERROR_REPORT) {
  557. $sSiteTitle = $this->getParam('site_title');
  558. $sMailBody = "Database error in " . $sSiteTitle . "<br /><br /> \n";
  559. $sMailBody .= $this->errorOutput($aError);
  560. $sMailBody .= "<hr />Auto-report system";
  561. sendMail($this->getParam('site_email'), "Database error in " . $sSiteTitle, $sMailBody, 0, array(), BX_EMAIL_SYSTEM, 'html', true);
  562. }
  563. bx_log('sys_db', "$sErrorType\n" .
  564. (empty($aError['message']) ? '' : " Error: {$aError['message']}\n") .
  565. (empty($aError['query']) ? '' : " Query: {$aError['query']}\n") .
  566. (!function_exists('getLoggedId') || !getLoggedId() ? '' : " Account ID: " . getLoggedId() . "\n")
  567. );
  568. bx_show_service_unavailable_error_and_exit($sOutput);
  569. }
  570. protected function isParamInCache($sKey)
  571. {
  572. return is_array(self::$_aParams) && isset(self::$_aParams[$sKey]);
  573. }
  574. public function cacheParams($bForceCacheInvalidate = false, $bForceCacheInvalidateMixed = false)
  575. {
  576. if ($bForceCacheInvalidate)
  577. $this->cacheParamsClear();
  578. self::$_aParams = $this->fromCache(self::$_sParamsCacheName, 'getPairs', "SELECT `name`, `value` FROM `sys_options`", "name", "value");
  579. list($sTmplCode, $sTmplName) = BxDolTemplate::retrieveCode();
  580. if(!empty($sTmplCode) && !empty($sTmplName)) {
  581. $iTmplMix = 0;
  582. if(is_array($sTmplCode))
  583. list($sTmplCode, $iTmplMix) = $sTmplCode;
  584. if(empty($iTmplMix))
  585. $iTmplMix = (int)$this->getParam($sTmplName . '_default_mix');
  586. if(!empty($iTmplMix)) {
  587. $sCacheNameMixed = self::$_sParamsCacheNameMixed . $sTmplCode . '_' . $iTmplMix;
  588. if($bForceCacheInvalidateMixed)
  589. $this->cacheParamsClear($sCacheNameMixed);
  590. $aMixed = $this->fromCache($sCacheNameMixed, 'getPairs', "SELECT `option`, `value` FROM `sys_options_mixes2options` WHERE `mix_id`=:mix_id", "option", "value", array(
  591. 'mix_id' => $iTmplMix
  592. ));
  593. if(!empty($aMixed) && is_array($aMixed))
  594. self::$_aParams = array_merge(self::$_aParams, $aMixed);
  595. }
  596. }
  597. if (empty(self::$_aParams)) {
  598. self::$_aParams = array();
  599. return false;
  600. }
  601. return true;
  602. }
  603. public function cacheParamsClear($sCacheName = '')
  604. {
  605. if(empty($sCacheName))
  606. $sCacheName = self::$_sParamsCacheName;
  607. return $this->cleanCache($sCacheName);
  608. }
  609. public function isParam($sKey, $bFromCache = true)
  610. {
  611. if ($bFromCache && $this->isParamInCache($sKey))
  612. return true;
  613. $sQuery = $this->prepare("SELECT `name` FROM `sys_options` WHERE `name` = ? LIMIT 1", $sKey);
  614. return $this->getOne($sQuery) == $sKey;
  615. }
  616. public function addParam($sName, $sValue, $iKateg, $sDesc, $sType)
  617. {
  618. $sQuery = $this->prepare("INSERT INTO `sys_options` SET `category_id` = ?, `name` = ?, `caption` = ?, `value` = ?, `type` = ?", $iKateg, $sName, $sDesc, $sValue, $sType);
  619. $this->query($sQuery);
  620. // renew params cache
  621. $this->cacheParams(true);
  622. }
  623. public function getParam($sKey, $bFromCache = true)
  624. {
  625. if (!$sKey)
  626. return false;
  627. if ($bFromCache && $this->isParamInCache($sKey)) {
  628. return self::$_aParams[$sKey];
  629. } else {
  630. $sQuery = $this->prepare("SELECT `tmo`.`value` AS `value` FROM `sys_options_mixes2options` AS `tmo` INNER JOIN `sys_options_mixes` AS `tm` ON `tmo`.`mix_id`=`tm`.`id` AND `tm`.`active`='1' WHERE `tmo`.`option`=? LIMIT 1", $sKey);
  631. $mixedValue = $this->getOne($sQuery);
  632. if($mixedValue !== false)
  633. return $mixedValue;
  634. $sQuery = $this->prepare("SELECT `value` FROM `sys_options` WHERE `name` = ? LIMIT 1", $sKey);
  635. return $this->getOne($sQuery);
  636. }
  637. }
  638. public function setParam($sKey, $mixedValue, $iMixId = 0)
  639. {
  640. if(empty($iMixId))
  641. $sQuery = $this->prepare("UPDATE `sys_options` SET `value` = ? WHERE `name` = ? LIMIT 1", $mixedValue, $sKey);
  642. else
  643. $sQuery = $this->prepare("REPLACE INTO `sys_options_mixes2options` SET `option` = ?, `mix_id` = ?, `value` = ?", $sKey, $iMixId, $mixedValue);
  644. $bResult = (int)$this->query($sQuery) > 0;
  645. // renew params cache
  646. $bResult &= $this->cacheParams(true, !empty($iMixId));
  647. return $bResult;
  648. }
  649. public function getParamsMix($iId)
  650. {
  651. return $this->fromCache(self::$_sParamsCacheNameMix . $iId, 'getRow', 'SELECT * FROM `sys_options_mixes` WHERE `id`=:id', array(
  652. 'id' => $iId
  653. ));
  654. }
  655. public function getParamsMixActive($sType)
  656. {
  657. return $this->getRow("SELECT * FROM `sys_options_mixes` WHERE `type`=:type AND `active`='1'", array(
  658. 'type' => $sType
  659. ));
  660. }
  661. public function getParamsMixes($sType, $mixedPublished = false)
  662. {
  663. $aBindings = array('type' => $sType);
  664. $sQuery = "SELECT * FROM `sys_options_mixes` WHERE `type`=:type";
  665. if($mixedPublished !== false) {
  666. $aBindings['published'] = (int)$mixedPublished;
  667. $sQuery .= " AND `published`=:published";
  668. }
  669. return $this->getAll($sQuery, $aBindings);
  670. }
  671. public function setTimezone($sTimezone)
  672. {
  673. $oDate = new DateTime('now', new DateTimeZone($sTimezone));
  674. return $this->pdoExec('SET time_zone = "' . $oDate->format('P') . '"') !== false;
  675. }
  676. public function getEncoding()
  677. {
  678. $oStatement = $this->pdoQuery('SELECT @@character_set_database');
  679. if($oStatement !== false)
  680. return $this->getOne($oStatement);
  681. return false;
  682. }
  683. public function setErrorChecking ($b)
  684. {
  685. $this->_bErrorChecking = $b;
  686. }
  687. /**
  688. * Cache functions.
  689. */
  690. public function getDbCacheObject ()
  691. {
  692. if($this->_oDbCacheObject != null)
  693. return $this->_oDbCacheObject;
  694. $sEngine = $this->getParam('sys_db_cache_engine');
  695. $this->_oDbCacheObject = bx_instance('BxDolCache'.$sEngine);
  696. if(!$this->_oDbCacheObject->isAvailable())
  697. $this->_oDbCacheObject = bx_instance('BxDolCacheFile');
  698. return $this->_oDbCacheObject;
  699. }
  700. public function genDbCacheKey ($sName)
  701. {
  702. return 'db_' . $sName . '_' . bx_site_hash() . '.php';
  703. }
  704. public function getCache ($sName, $sFunc)
  705. {
  706. if (!$this->getParam('sys_db_cache_enable'))
  707. return false;
  708. $oCache = $this->getDbCacheObject ();
  709. $sKey = $this->genDbCacheKey($sName);
  710. return $oCache->getData($sKey);
  711. }
  712. public function setCache ($sName, $mData)
  713. {
  714. if (!$this->getParam('sys_db_cache_enable'))
  715. return false;
  716. $oCache = $this->getDbCacheObject ();
  717. $sKey = $this->genDbCacheKey($sName);
  718. $oCache->setData($sKey, $mData);
  719. }
  720. public function fromCache ($sName, $sFunc)
  721. {
  722. $aArgs = func_get_args();
  723. array_shift ($aArgs); // shift $sName
  724. array_shift ($aArgs); // shift $sFunc
  725. if (!$this->getParam('sys_db_cache_enable'))
  726. return call_user_func_array (array ($this, $sFunc), $aArgs); // pass other function parameters as database function parameters
  727. $oCache = $this->getDbCacheObject ();
  728. $sKey = $this->genDbCacheKey($sName);
  729. $mixedRet = $oCache->getData($sKey);
  730. if ($mixedRet !== null) {
  731. return $mixedRet;
  732. } else {
  733. $mixedRet = call_user_func_array (array ($this, $sFunc), $aArgs); // pass other function parameters as database function parameters
  734. $oCache->setData($sKey, $mixedRet);
  735. }
  736. return $mixedRet;
  737. }
  738. public function cleanCache ($sName)
  739. {
  740. $oCache = $this->getDbCacheObject();
  741. $sKey = $this->genDbCacheKey($sName);
  742. return $oCache->delData($sKey);
  743. }
  744. public function &fromMemory ($sName, $sFunc)
  745. {
  746. if(array_key_exists($sName, self::$_aDbCacheData) && !defined('BX_DOL_INSTALL') && !defined('BX_DOL_CRON_EXECUTE'))
  747. return self::$_aDbCacheData[$sName];
  748. $aArgs = func_get_args();
  749. array_shift($aArgs); // shift $sName
  750. array_shift($aArgs); // shift $sFunc
  751. self::$_aDbCacheData[$sName] = call_user_func_array (array ($this, $sFunc), $aArgs); // pass other function parameters as database function parameters
  752. return self::$_aDbCacheData[$sName];
  753. }
  754. public function cleanMemory ($sName)
  755. {
  756. if(!isset(self::$_aDbCacheData[$sName]))
  757. return false;
  758. unset(self::$_aDbCacheData[$sName]);
  759. return true;
  760. }
  761. public function cleanMemoryAll ()
  762. {
  763. self::$_aDbCacheData = array();
  764. return true;
  765. }
  766. /**
  767. * It escapes string to pass to mysql query.
  768. * Try to use "prepare" function always (@see BxDolDb::prepare), use "escape" only if "prepare" function is not possible at all.
  769. * Also consider using "implode_escape" function (@see BxDolDb::implode_escape).
  770. *
  771. * @param string $s string to escape
  772. * @return escaped string whcich is ready to pass to SQL query.
  773. */
  774. public function escape($s)
  775. {
  776. try {
  777. $s = self::$_rLink->quote($s);
  778. }
  779. catch (PDOException $oException) {
  780. $oException->errorInfo[self::$_sErrorKey] = array(
  781. 'code' => BX_DB_ERR_ESCAPE,
  782. 'message' => $oException->getMessage(),
  783. 'trace' => $oException->getTrace()
  784. );
  785. throw $oException;
  786. }
  787. return $s;
  788. }
  789. /**
  790. * This function is usefull when you need to form array of parameters to pass to IN(...) SQL construction.
  791. * Example:
  792. * @code
  793. * $a = array(2, 4.5, 'apple', 'car');
  794. * $s = "SELECT * FROM `t` WHERE `a` IN (" . $oDb->implode_escape($a) . ")";
  795. * echo $s; // outputs: SELECT * FROM `t` WHERE `a` IN (2, 4.5, 'apple', 'car')
  796. * @endcode
  797. *
  798. * @param $mixed array or parameters or just one paramter
  799. * @return string which is ready to pass to IN(...) SQL construction
  800. */
  801. public function implode_escape ($mixed)
  802. {
  803. if (is_array($mixed)) {
  804. $s = '';
  805. foreach ($mixed as $v)
  806. $s .= (is_numeric($v) ? $v : $this->escape($v)) . ',';
  807. if ($s)
  808. return substr($s, 0, -1);
  809. else
  810. return 'NULL';
  811. }
  812. return is_numeric($mixed) ? $mixed : ($mixed ? $this->escape($mixed) : 'NULL');
  813. }
  814. /**
  815. * @deprecated
  816. */
  817. public function unescape ($mixed)
  818. {
  819. if(is_array($mixed)) {
  820. foreach($mixed as $k => $v)
  821. $mixed[$k] = $this->getOne("SELECT '$v'");
  822. return $mixed;
  823. }
  824. else
  825. return $this->getOne("SELECT '$mixed'");
  826. }
  827. /**
  828. * Prepare SQL query before execution if some arguments are need to be passed to it.
  829. * All parameters marked with question (?) symbol in SQL query are replaced with parameters passed after SQL query parameter.
  830. * Parameters are properly excaped and surrounded by qutes if needed.
  831. * Example:
  832. * @code
  833. * $sSql = $oDb->prepare("SELECT `a`, `b` from `t` WHERE `c` = ? and `d` = ?", 12, 'aa');
  834. * echo $sSql;// outputs: SELECT `a`, `b` from `t` WHERE `c` = 12 and `d` = 'aa'
  835. * $a = $oDb->getAll($sSql);
  836. * @endcode
  837. *
  838. * @param string $sQuery SQL query, parameters for replacing are marked with ? symbol
  839. * @param mixed $mixed any number if parameters to replace, number of parameters whould match number of ? symbols in SQL query
  840. * @return PDOStatement object with SQL query ready for execution
  841. */
  842. public function prepare($sQuery)
  843. {
  844. if(!self::$_rLink)
  845. return false;
  846. if (self::$_bMultuServersMode && (0 != strncasecmp(ltrim($sQuery, " \t\n\r(\0\x0B"), 'SELECT', 6)))
  847. $this->setReadOnlyMode(false);
  848. $aArgs = func_get_args();
  849. $sQuery = array_shift($aArgs);
  850. $oStatement = self::$_rLink->prepare($sQuery);
  851. $iIndex = 1;
  852. foreach($aArgs as $mixedArg) {
  853. if(is_null($mixedArg))
  854. $iValueType = PDO::PARAM_NULL;
  855. else if(is_numeric($mixedArg) && is_int($mixedArg))
  856. $iValueType = PDO::PARAM_INT;
  857. else
  858. $iValueType = PDO::PARAM_STR;
  859. $oStatement->bindValue($iIndex++, $mixedArg, $iValueType);
  860. }
  861. return $oStatement;
  862. }
  863. /**
  864. * Prepare SQL query before execution if some arguments are need to be passed to it.
  865. * All parameters marked with question (?) symbol in SQL query are replaced with parameters passed after SQL query parameter.
  866. * Parameters are properly excaped and surrounded by qutes if needed.
  867. * Example:
  868. * @code
  869. * $sSql = $oDb->prepare("SELECT `a`, `b` from `t` WHERE `c` = ? and `d` = ?", 12, 'aa');
  870. * echo $sSql;// outputs: SELECT `a`, `b` from `t` WHERE `c` = 12 and `d` = 'aa'
  871. * $a = $oDb->getAll($sSql);
  872. * @endcode
  873. *
  874. * @param string $sQuery SQL query, parameters for replacing are marked with ? symbol
  875. * @param mixed $mixed any number if parameters to replace, number of parameters whould match number of ? symbols in SQL query
  876. * @return string with SQL query.
  877. */
  878. function prepareAsString($sQuery)
  879. {
  880. $aArgs = func_get_args();
  881. $sQuery = array_shift($aArgs);
  882. $iPos = 0;
  883. foreach ($aArgs as $mixedArg) {
  884. if (is_null($mixedArg))
  885. $s = 'NULL';
  886. elseif (is_numeric($mixedArg))
  887. $s = $mixedArg;
  888. else
  889. $s = $this->escape($mixedArg);
  890. $i = bx_mb_strpos($sQuery, '?', $iPos);
  891. $sQuery = bx_mb_substr_replace($sQuery, $s, $i, 1);
  892. $iPos = $i + get_mb_len($s);
  893. }
  894. return $sQuery;
  895. }
  896. /**
  897. * Convert array of key => values to SQL query.
  898. * Array keys are field names and array values are field values.
  899. * @param $a array
  900. * @param $sDiv fields separator, by default it is ',', another useful value is ' AND '
  901. * @param $sOperator operator for comparision: '=' or 'LIKE'
  902. * @param $bWildcardSpaceChars substiture any space and dash characters with single wildcard symbol
  903. * @return part of SQL query string
  904. */
  905. public function arrayToSQL($a, $sDiv = ',', $sOperator = '=', $bWildcardSpaceChars = false)
  906. {
  907. $aOperators = ['=', 'LIKE', 'like'];
  908. $sOperator = in_array($sOperator, $aOperators) ? $sOperator : '=';
  909. $s = '';
  910. foreach($a as $k => $v) {
  911. if ($bWildcardSpaceChars)
  912. $v = preg_replace('/[\p{Zs}\p{Cc}\p{Pd}]/', '_', $v);
  913. $s .= "`{$k}` {$sOperator} " . $this->escape($v) . $sDiv;
  914. }
  915. return trim($s, $sDiv);
  916. }
  917. protected function log($s)
  918. {
  919. if (defined('BX_DIRECTORY_PATH_LOGS')) {
  920. $sPath = BX_DIRECTORY_PATH_LOGS;
  921. }
  922. else {
  923. $sDirName = pathinfo(__FILE__, PATHINFO_DIRNAME);
  924. $sPath = $sDirName . '/../../logs/';
  925. }
  926. return file_put_contents($sPath . 'db.err.log', date('Y-m-d H:i:s') . "\t" . $s . "\n", FILE_APPEND);
  927. }
  928. public function executeSQL($sPath, $aReplace = array (), $isBreakOnError = true)
  929. {
  930. if(!file_exists($sPath) || !($rHandler = fopen($sPath, "r")))
  931. return array(array ('query' => "fopen($sPath, 'r')", 'error' => 'file not found or permission denied'));
  932. self::$_rLink->setAttribute(PDO::ATTR_ERRMODE, BX_DB_MODE_SILENT);
  933. $sQuery = "";
  934. $sDelimiter = ';';
  935. $aResult = array();
  936. while(!feof($rHandler)) {
  937. $sStr = trim(fgets($rHandler));
  938. if(empty($sStr) || $sStr[0] == "" || $sStr[0] == "#" || ($sStr[0] == "-" && $sStr[1] == "-"))
  939. continue;
  940. //--- Change delimiter ---//
  941. if(strpos($sStr, "DELIMITER //") !== false || strpos($sStr, "DELIMITER ;") !== false) {
  942. $sDelimiter = trim(str_replace('DELIMITER', '', $sStr));
  943. continue;
  944. }
  945. $sQuery .= $sStr;
  946. //--- Check for multiline query ---//
  947. if(substr($sStr, -strlen($sDelimiter)) != $sDelimiter)
  948. continue;
  949. //--- Execute query ---//
  950. if ($aReplace)
  951. $sQuery = str_replace($aReplace['from'], $aReplace['to'], $sQuery);
  952. if($sDelimiter != ';')
  953. $sQuery = str_replace($sDelimiter, "", $sQuery);
  954. if($this->query(trim($sQuery), array(), false) === false) {
  955. $aResult[] = array('query' => $sQuery, 'error' => $this->_aError['message']);
  956. if ($isBreakOnError)
  957. break;
  958. }
  959. $sQuery = "";
  960. }
  961. fclose($rHandler);
  962. self::$_rLink->setAttribute(PDO::ATTR_ERRMODE, $this->_iPdoErrorMode);
  963. return empty($aResult) ? true : $aResult;
  964. }
  965. protected function executeStatement($oStatement, $aBindings = array(), $bVerbose = null, &$iErrorCode = null)
  966. {
  967. $bResult = false;
  968. if (!isset($aBindings[0])) {
  969. foreach($aBindings as $sKey => $mixedValue) {
  970. if(is_null($mixedValue))
  971. $oStatement->bindValue(":{$sKey}", $mixedValue, PDO::PARAM_NULL);
  972. else if(is_numeric($mixedValue) && is_int($mixedValue))
  973. $oStatement->bindValue(":{$sKey}", $mixedValue, PDO::PARAM_INT);
  974. else
  975. $oStatement->bindValue(":{$sKey}", $mixedValue, PDO::PARAM_STR);
  976. }
  977. $aBindings = array();
  978. }
  979. switch (self::$_rLink->getAttribute(PDO::ATTR_ERRMODE)) {
  980. case PDO::ERRMODE_SILENT:
  981. $bResult = $this->executeStatementSilent($oStatement, $aBindings, $bVerbose);
  982. break;
  983. case PDO::ERRMODE_EXCEPTION:
  984. $bResult = $this->executeStatementException($oStatement, $aBindings, $bVerbose);
  985. break;
  986. }
  987. if (!$bResult && !is_null($iErrorCode)) {
  988. $aError = $oStatement->errorInfo();
  989. $iErrorCode = $aError[1];
  990. }
  991. return $bResult;
  992. }
  993. protected function executeStatementException($oStatement, $aBindings = array(), $bVerbose = null)
  994. {
  995. $bResult = false;
  996. try {
  997. $bResult = $oStatement->execute(!empty($aBindings) && is_array($aBindings) ? $aBindings : null);
  998. }
  999. catch (PDOException $oException) {
  1000. $aError = $oStatement->errorInfo();
  1001. $oException->errorInfo[self::$_sErrorKey] = array(
  1002. 'code' => BX_DB_ERR_QUERY_ERROR,
  1003. 'message' => !empty($aError[2]) ? $aError[2] : $oException->getMessage(),
  1004. 'query' => $oStatement->queryString,
  1005. 'trace' => $oException->getTrace(),
  1006. 'verbose' => $bVerbose
  1007. );
  1008. throw $oException;
  1009. }
  1010. return $bResult;
  1011. }
  1012. protected function executeStatementSilent($oStatement, $aBindings = array(), $bVerbose = null)
  1013. {
  1014. $bResult = $oStatement->execute(!empty($aBindings) && is_array($aBindings) ? $aBindings : null);
  1015. if($bResult)
  1016. return true;
  1017. $aError = $oStatement->errorInfo();
  1018. $aTrace = debug_backtrace();
  1019. unset($aTrace[0]);
  1020. $this->_aError = array(
  1021. 'code' => BX_DB_ERR_QUERY_ERROR,
  1022. 'message' => !empty($aError[2]) ? $aError[2] : '',
  1023. 'query' => $oStatement->queryString,
  1024. 'trace' => $aTrace,
  1025. 'verbose' => $bVerbose
  1026. );
  1027. return false;
  1028. }
  1029. protected function errorOutput($aError)
  1030. {
  1031. $aErrorLocation = array();
  1032. if(!empty($aError['query']) && !empty($aError['trace']))
  1033. foreach($aError['trace'] as $aCall )
  1034. if(isset($aCall['args']) && is_array($aCall['args']))
  1035. foreach($aCall['args'] as $argNum => $argVal)
  1036. if((is_string($argVal) && strcmp($argVal, $aError['query']) == 0) || ($argVal instanceof PDOStatement && strcmp($argVal->queryString, $aError['query']) == 0)) {
  1037. $aErrorLocation['file'] = isset($aCall['file']) ? $aCall['file'] : (isset($aCall['class']) ? 'class: ' . $aCall['class'] : 'undefined');
  1038. $aErrorLocation['line'] = isset($aCall['line']) ? $aCall['line'] : 'undefined';
  1039. $aErrorLocation['function'] = $aCall['function'];
  1040. $aErrorLocation['arg'] = $argNum;
  1041. }
  1042. $sOutput = '';
  1043. if(!empty($aError['query']))
  1044. $sOutput .= '<p><b>Query:</b><br />' . bx_process_output($aError['query']) . '</p>';
  1045. if(!empty($aError['message']))
  1046. $sOutput .= '<p><b>Mysql error:</b><br />' . $aError['message'] . '</p>';
  1047. if(!empty($aErrorLocation))
  1048. $sOutput .= '<p><b>Location:</b><br />The error was found in <b>' . $aErrorLocation['function'] . '</b> function in the file <b>' . $aErrorLocation['file'] . '</b> at line <b>' . $aErrorLocation['line'] . '</b>.</p>';
  1049. $sOutput .= '<p><b>collation_connection:</b><br />' . $this->getOne("SELECT @@collation_connection") . '</p>';
  1050. if(!empty($aError['trace'])) {
  1051. $sBackTrace = print_r($aError['trace'], true);
  1052. if (defined ('BX_DATABASE_USER') && !is_array(BX_DATABASE_USER))
  1053. $sBackTrace = str_replace('[_sUser:protected] => ' . BX_DATABASE_USER, '[_sUser:protected] => *****', $sBackTrace);
  1054. if (defined ('BX_DATABASE_PASS') && !is_array(BX_DATABASE_PASS))
  1055. $sBackTrace = str_replace('[_sPassword:protected] => ' . BX_DATABASE_PASS, '[_sPassword:protected] => *****', $sBackTrace);
  1056. $sOutput .= '<div><b>Debug backtrace:</b></div><div style="overflow:scroll;height:300px;border:1px solid gray;"><pre>' . htmlspecialchars_adv($sBackTrace) . '</pre></div>';
  1057. }
  1058. if(!empty(self::$_aParams)) {
  1059. $sSettings = var_export(self::$_aParams, true);
  1060. $sOutput .= '<div><b>Settings:</b></div><div style="overflow:scroll;height:300px;border:1px solid gray;"><pre>' . htmlspecialchars_adv($sSettings) . '</pre></div>';
  1061. }
  1062. $sOutput .= '<p><b>Called script:</b><br />' . $_SERVER['PHP_SELF'] . '</p>';
  1063. if(!empty($_REQUEST)) {
  1064. $sRequest = var_export($_REQUEST, true);
  1065. $sOutput .= '<p><b>Request parameters:</b><br /><pre>' . htmlspecialchars_adv($sRequest) . '</pre></p>';
  1066. }
  1067. return $sOutput;
  1068. }
  1069. }
  1070. /**
  1071. * Create the very first instance and initiate connetion to database.
  1072. */
  1073. BxDolDb::getInstance();
  1074. function getParam($sParamName, $bUseCache = true)
  1075. {
  1076. if (bx_is_api() && $sParamName == 'permalinks_seo_links')
  1077. return true;
  1078. $oObj = BxDolDb::getInstance();
  1079. if ($oObj === null)
  1080. return false;
  1081. return $oObj->getParam($sParamName, $bUseCache);
  1082. }
  1083. function setParam($sParamName, $sParamVal)
  1084. {
  1085. $oObj = BxDolDb::getInstance();
  1086. if ($oObj === null)
  1087. return false;
  1088. return $oObj->setParam($sParamName, $sParamVal);
  1089. }
  1090. /** @} */