BxDolDb.php 43 KB

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