BxDolDb.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  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_show_service_unavailable_error_and_exit($sOutput);
  564. }
  565. protected function isParamInCache($sKey)
  566. {
  567. return is_array(self::$_aParams) && isset(self::$_aParams[$sKey]);
  568. }
  569. public function cacheParams($bForceCacheInvalidate = false, $bForceCacheInvalidateMixed = false)
  570. {
  571. if ($bForceCacheInvalidate)
  572. $this->cacheParamsClear();
  573. self::$_aParams = $this->fromCache(self::$_sParamsCacheName, 'getPairs', "SELECT `name`, `value` FROM `sys_options`", "name", "value");
  574. list($sTmplCode, $sTmplName) = BxDolTemplate::retrieveCode();
  575. if(!empty($sTmplCode) && !empty($sTmplName)) {
  576. $iTmplMix = 0;
  577. if(is_array($sTmplCode))
  578. list($sTmplCode, $iTmplMix) = $sTmplCode;
  579. if(empty($iTmplMix))
  580. $iTmplMix = (int)$this->getParam($sTmplName . '_default_mix');
  581. if(!empty($iTmplMix)) {
  582. $sCacheNameMixed = self::$_sParamsCacheNameMixed . $sTmplCode . '_' . $iTmplMix;
  583. if($bForceCacheInvalidateMixed)
  584. $this->cacheParamsClear($sCacheNameMixed);
  585. $aMixed = $this->fromCache($sCacheNameMixed, 'getPairs', "SELECT `option`, `value` FROM `sys_options_mixes2options` WHERE `mix_id`=:mix_id", "option", "value", array(
  586. 'mix_id' => $iTmplMix
  587. ));
  588. if(!empty($aMixed) && is_array($aMixed))
  589. self::$_aParams = array_merge(self::$_aParams, $aMixed);
  590. }
  591. }
  592. if (empty(self::$_aParams)) {
  593. self::$_aParams = array();
  594. return false;
  595. }
  596. return true;
  597. }
  598. public function cacheParamsClear($sCacheName = '')
  599. {
  600. if(empty($sCacheName))
  601. $sCacheName = self::$_sParamsCacheName;
  602. return $this->cleanCache($sCacheName);
  603. }
  604. public function isParam($sKey, $bFromCache = true)
  605. {
  606. if ($bFromCache && $this->isParamInCache($sKey))
  607. return true;
  608. $sQuery = $this->prepare("SELECT `name` FROM `sys_options` WHERE `name` = ? LIMIT 1", $sKey);
  609. return $this->getOne($sQuery) == $sKey;
  610. }
  611. public function addParam($sName, $sValue, $iKateg, $sDesc, $sType)
  612. {
  613. $sQuery = $this->prepare("INSERT INTO `sys_options` SET `category_id` = ?, `name` = ?, `caption` = ?, `value` = ?, `type` = ?", $iKateg, $sName, $sDesc, $sValue, $sType);
  614. $this->query($sQuery);
  615. // renew params cache
  616. $this->cacheParams(true);
  617. }
  618. public function getParam($sKey, $bFromCache = true)
  619. {
  620. if (!$sKey)
  621. return false;
  622. if ($bFromCache && $this->isParamInCache($sKey)) {
  623. return self::$_aParams[$sKey];
  624. } else {
  625. $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);
  626. $mixedValue = $this->getOne($sQuery);
  627. if($mixedValue !== false)
  628. return $mixedValue;
  629. $sQuery = $this->prepare("SELECT `value` FROM `sys_options` WHERE `name` = ? LIMIT 1", $sKey);
  630. return $this->getOne($sQuery);
  631. }
  632. }
  633. public function setParam($sKey, $mixedValue, $iMixId = 0)
  634. {
  635. if(empty($iMixId))
  636. $sQuery = $this->prepare("UPDATE `sys_options` SET `value` = ? WHERE `name` = ? LIMIT 1", $mixedValue, $sKey);
  637. else
  638. $sQuery = $this->prepare("REPLACE INTO `sys_options_mixes2options` SET `option` = ?, `mix_id` = ?, `value` = ?", $sKey, $iMixId, $mixedValue);
  639. $bResult = (int)$this->query($sQuery) > 0;
  640. // renew params cache
  641. $bResult &= $this->cacheParams(true, !empty($iMixId));
  642. return $bResult;
  643. }
  644. public function getParamsMix($iId)
  645. {
  646. return $this->fromCache(self::$_sParamsCacheNameMix . $iId, 'getRow', 'SELECT * FROM `sys_options_mixes` WHERE `id`=:id', array(
  647. 'id' => $iId
  648. ));
  649. }
  650. public function getParamsMixActive($sType)
  651. {
  652. return $this->getRow("SELECT * FROM `sys_options_mixes` WHERE `type`=:type AND `active`='1'", array(
  653. 'type' => $sType
  654. ));
  655. }
  656. public function getParamsMixes($sType, $mixedPublished = false)
  657. {
  658. $aBindings = array('type' => $sType);
  659. $sQuery = "SELECT * FROM `sys_options_mixes` WHERE `type`=:type";
  660. if($mixedPublished !== false) {
  661. $aBindings['published'] = (int)$mixedPublished;
  662. $sQuery .= " AND `published`=:published";
  663. }
  664. return $this->getAll($sQuery, $aBindings);
  665. }
  666. public function setTimezone($sTimezone)
  667. {
  668. $oDate = new DateTime('now', new DateTimeZone($sTimezone));
  669. return $this->pdoExec('SET time_zone = "' . $oDate->format('P') . '"') !== false;
  670. }
  671. public function getEncoding()
  672. {
  673. $oStatement = $this->pdoQuery('SELECT @@character_set_database');
  674. if($oStatement !== false)
  675. return $this->getOne($oStatement);
  676. return false;
  677. }
  678. public function setErrorChecking ($b)
  679. {
  680. $this->_bErrorChecking = $b;
  681. }
  682. /**
  683. * Cache functions.
  684. */
  685. public function getDbCacheObject ()
  686. {
  687. if($this->_oDbCacheObject != null)
  688. return $this->_oDbCacheObject;
  689. $sEngine = $this->getParam('sys_db_cache_engine');
  690. $this->_oDbCacheObject = bx_instance('BxDolCache'.$sEngine);
  691. if(!$this->_oDbCacheObject->isAvailable())
  692. $this->_oDbCacheObject = bx_instance('BxDolCacheFile');
  693. return $this->_oDbCacheObject;
  694. }
  695. public function genDbCacheKey ($sName)
  696. {
  697. return 'db_' . $sName . '_' . bx_site_hash() . '.php';
  698. }
  699. public function fromCache ($sName, $sFunc)
  700. {
  701. $aArgs = func_get_args();
  702. array_shift ($aArgs); // shift $sName
  703. array_shift ($aArgs); // shift $sFunc
  704. if (!$this->getParam('sys_db_cache_enable'))
  705. return call_user_func_array (array ($this, $sFunc), $aArgs); // pass other function parameters as database function parameters
  706. $oCache = $this->getDbCacheObject ();
  707. $sKey = $this->genDbCacheKey($sName);
  708. $mixedRet = $oCache->getData($sKey);
  709. if ($mixedRet !== null) {
  710. return $mixedRet;
  711. } else {
  712. $mixedRet = call_user_func_array (array ($this, $sFunc), $aArgs); // pass other function parameters as database function parameters
  713. $oCache->setData($sKey, $mixedRet);
  714. }
  715. return $mixedRet;
  716. }
  717. public function cleanCache ($sName)
  718. {
  719. $oCache = $this->getDbCacheObject();
  720. $sKey = $this->genDbCacheKey($sName);
  721. return $oCache->delData($sKey);
  722. }
  723. public function &fromMemory ($sName, $sFunc)
  724. {
  725. if(array_key_exists($sName, self::$_aDbCacheData) && !defined('BX_DOL_INSTALL') && !defined('BX_DOL_CRON_EXECUTE'))
  726. return self::$_aDbCacheData[$sName];
  727. $aArgs = func_get_args();
  728. array_shift($aArgs); // shift $sName
  729. array_shift($aArgs); // shift $sFunc
  730. self::$_aDbCacheData[$sName] = call_user_func_array (array ($this, $sFunc), $aArgs); // pass other function parameters as database function parameters
  731. return self::$_aDbCacheData[$sName];
  732. }
  733. public function cleanMemory ($sName)
  734. {
  735. if(!isset(self::$_aDbCacheData[$sName]))
  736. return false;
  737. unset(self::$_aDbCacheData[$sName]);
  738. return true;
  739. }
  740. public function cleanMemoryAll ()
  741. {
  742. self::$_aDbCacheData = array();
  743. return true;
  744. }
  745. /**
  746. * It escapes string to pass to mysql query.
  747. * Try to use "prepare" function always (@see BxDolDb::prepare), use "escape" only if "prepare" function is not possible at all.
  748. * Also consider using "implode_escape" function (@see BxDolDb::implode_escape).
  749. *
  750. * @param string $s string to escape
  751. * @return escaped string whcich is ready to pass to SQL query.
  752. */
  753. public function escape($s)
  754. {
  755. try {
  756. $s = self::$_rLink->quote($s);
  757. }
  758. catch (PDOException $oException) {
  759. $oException->errorInfo[self::$_sErrorKey] = array(
  760. 'code' => BX_DB_ERR_ESCAPE,
  761. 'message' => $oException->getMessage(),
  762. 'trace' => $oException->getTrace()
  763. );
  764. throw $oException;
  765. }
  766. return $s;
  767. }
  768. /**
  769. * This function is usefull when you need to form array of parameters to pass to IN(...) SQL construction.
  770. * Example:
  771. * @code
  772. * $a = array(2, 4.5, 'apple', 'car');
  773. * $s = "SELECT * FROM `t` WHERE `a` IN (" . $oDb->implode_escape($a) . ")";
  774. * echo $s; // outputs: SELECT * FROM `t` WHERE `a` IN (2, 4.5, 'apple', 'car')
  775. * @endcode
  776. *
  777. * @param $mixed array or parameters or just one paramter
  778. * @return string which is ready to pass to IN(...) SQL construction
  779. */
  780. public function implode_escape ($mixed)
  781. {
  782. if (is_array($mixed)) {
  783. $s = '';
  784. foreach ($mixed as $v)
  785. $s .= (is_numeric($v) ? $v : $this->escape($v)) . ',';
  786. if ($s)
  787. return substr($s, 0, -1);
  788. else
  789. return 'NULL';
  790. }
  791. return is_numeric($mixed) ? $mixed : ($mixed ? $this->escape($mixed) : 'NULL');
  792. }
  793. /**
  794. * @deprecated
  795. */
  796. public function unescape ($mixed)
  797. {
  798. if(is_array($mixed)) {
  799. foreach($mixed as $k => $v)
  800. $mixed[$k] = $this->getOne("SELECT '$v'");
  801. return $mixed;
  802. }
  803. else
  804. return $this->getOne("SELECT '$mixed'");
  805. }
  806. /**
  807. * Prepare SQL query before execution if some arguments are need to be passed to it.
  808. * All parameters marked with question (?) symbol in SQL query are replaced with parameters passed after SQL query parameter.
  809. * Parameters are properly excaped and surrounded by qutes if needed.
  810. * Example:
  811. * @code
  812. * $sSql = $oDb->prepare("SELECT `a`, `b` from `t` WHERE `c` = ? and `d` = ?", 12, 'aa');
  813. * echo $sSql;// outputs: SELECT `a`, `b` from `t` WHERE `c` = 12 and `d` = 'aa'
  814. * $a = $oDb->getAll($sSql);
  815. * @endcode
  816. *
  817. * @param string $sQuery SQL query, parameters for replacing are marked with ? symbol
  818. * @param mixed $mixed any number if parameters to replace, number of parameters whould match number of ? symbols in SQL query
  819. * @return PDOStatement object with SQL query ready for execution
  820. */
  821. public function prepare($sQuery)
  822. {
  823. if(!self::$_rLink)
  824. return false;
  825. if (self::$_bMultuServersMode && (0 != strncasecmp(ltrim($sQuery, " \t\n\r(\0\x0B"), 'SELECT', 6)))
  826. $this->setReadOnlyMode(false);
  827. $aArgs = func_get_args();
  828. $sQuery = array_shift($aArgs);
  829. $oStatement = self::$_rLink->prepare($sQuery);
  830. $iIndex = 1;
  831. foreach($aArgs as $mixedArg) {
  832. if(is_null($mixedArg))
  833. $iValueType = PDO::PARAM_NULL;
  834. else if(is_numeric($mixedArg) && is_int($mixedArg))
  835. $iValueType = PDO::PARAM_INT;
  836. else
  837. $iValueType = PDO::PARAM_STR;
  838. $oStatement->bindValue($iIndex++, $mixedArg, $iValueType);
  839. }
  840. return $oStatement;
  841. }
  842. /**
  843. * Prepare SQL query before execution if some arguments are need to be passed to it.
  844. * All parameters marked with question (?) symbol in SQL query are replaced with parameters passed after SQL query parameter.
  845. * Parameters are properly excaped and surrounded by qutes if needed.
  846. * Example:
  847. * @code
  848. * $sSql = $oDb->prepare("SELECT `a`, `b` from `t` WHERE `c` = ? and `d` = ?", 12, 'aa');
  849. * echo $sSql;// outputs: SELECT `a`, `b` from `t` WHERE `c` = 12 and `d` = 'aa'
  850. * $a = $oDb->getAll($sSql);
  851. * @endcode
  852. *
  853. * @param string $sQuery SQL query, parameters for replacing are marked with ? symbol
  854. * @param mixed $mixed any number if parameters to replace, number of parameters whould match number of ? symbols in SQL query
  855. * @return string with SQL query.
  856. */
  857. function prepareAsString($sQuery)
  858. {
  859. $aArgs = func_get_args();
  860. $sQuery = array_shift($aArgs);
  861. $iPos = 0;
  862. foreach ($aArgs as $mixedArg) {
  863. if (is_null($mixedArg))
  864. $s = 'NULL';
  865. elseif (is_numeric($mixedArg))
  866. $s = $mixedArg;
  867. else
  868. $s = $this->escape($mixedArg);
  869. $i = bx_mb_strpos($sQuery, '?', $iPos);
  870. $sQuery = bx_mb_substr_replace($sQuery, $s, $i, 1);
  871. $iPos = $i + get_mb_len($s);
  872. }
  873. return $sQuery;
  874. }
  875. /**
  876. * Convert array of key => values to SQL query.
  877. * Array keys are field names and array values are field values.
  878. * @param $a array
  879. * @param $sDiv fields separator, by default it is ',', another useful value is ' AND '
  880. * @param $sOperator operator for comparision: '=' or 'LIKE'
  881. * @param $bWildcardSpaceChars substiture any space and dash characters with single wildcard symbol
  882. * @return part of SQL query string
  883. */
  884. public function arrayToSQL($a, $sDiv = ',', $sOperator = '=', $bWildcardSpaceChars = false)
  885. {
  886. $aOperators = ['=', 'LIKE', 'like'];
  887. $sOperator = in_array($sOperator, $aOperators) ? $sOperator : '=';
  888. $s = '';
  889. foreach($a as $k => $v) {
  890. if ($bWildcardSpaceChars)
  891. $v = preg_replace('/[\p{Zs}\p{Cc}\p{Pd}]/', '_', $v);
  892. $s .= "`{$k}` {$sOperator} " . $this->escape($v) . $sDiv;
  893. }
  894. return trim($s, $sDiv);
  895. }
  896. protected function log($s)
  897. {
  898. if (defined('BX_DIRECTORY_PATH_LOGS')) {
  899. $sPath = BX_DIRECTORY_PATH_LOGS;
  900. }
  901. else {
  902. $sDirName = pathinfo(__FILE__, PATHINFO_DIRNAME);
  903. $sPath = $sDirName . '/../../logs/';
  904. }
  905. return file_put_contents($sPath . 'db.err.log', date('Y-m-d H:i:s') . "\t" . $s . "\n", FILE_APPEND);
  906. }
  907. public function executeSQL($sPath, $aReplace = array (), $isBreakOnError = true)
  908. {
  909. if(!file_exists($sPath) || !($rHandler = fopen($sPath, "r")))
  910. return array(array ('query' => "fopen($sPath, 'r')", 'error' => 'file not found or permission denied'));
  911. self::$_rLink->setAttribute(PDO::ATTR_ERRMODE, BX_DB_MODE_SILENT);
  912. $sQuery = "";
  913. $sDelimiter = ';';
  914. $aResult = array();
  915. while(!feof($rHandler)) {
  916. $sStr = trim(fgets($rHandler));
  917. if(empty($sStr) || $sStr[0] == "" || $sStr[0] == "#" || ($sStr[0] == "-" && $sStr[1] == "-"))
  918. continue;
  919. //--- Change delimiter ---//
  920. if(strpos($sStr, "DELIMITER //") !== false || strpos($sStr, "DELIMITER ;") !== false) {
  921. $sDelimiter = trim(str_replace('DELIMITER', '', $sStr));
  922. continue;
  923. }
  924. $sQuery .= $sStr;
  925. //--- Check for multiline query ---//
  926. if(substr($sStr, -strlen($sDelimiter)) != $sDelimiter)
  927. continue;
  928. //--- Execute query ---//
  929. if ($aReplace)
  930. $sQuery = str_replace($aReplace['from'], $aReplace['to'], $sQuery);
  931. if($sDelimiter != ';')
  932. $sQuery = str_replace($sDelimiter, "", $sQuery);
  933. if($this->query(trim($sQuery), array(), false) === false) {
  934. $aResult[] = array('query' => $sQuery, 'error' => $this->_aError['message']);
  935. if ($isBreakOnError)
  936. break;
  937. }
  938. $sQuery = "";
  939. }
  940. fclose($rHandler);
  941. self::$_rLink->setAttribute(PDO::ATTR_ERRMODE, $this->_iPdoErrorMode);
  942. return empty($aResult) ? true : $aResult;
  943. }
  944. protected function executeStatement($oStatement, $aBindings = array(), $bVerbose = null, &$iErrorCode = null)
  945. {
  946. $bResult = false;
  947. if (!isset($aBindings[0])) {
  948. foreach($aBindings as $sKey => $mixedValue) {
  949. if(is_null($mixedValue))
  950. $oStatement->bindValue(":{$sKey}", $mixedValue, PDO::PARAM_NULL);
  951. else if(is_numeric($mixedValue) && is_int($mixedValue))
  952. $oStatement->bindValue(":{$sKey}", $mixedValue, PDO::PARAM_INT);
  953. else
  954. $oStatement->bindValue(":{$sKey}", $mixedValue, PDO::PARAM_STR);
  955. }
  956. $aBindings = array();
  957. }
  958. switch (self::$_rLink->getAttribute(PDO::ATTR_ERRMODE)) {
  959. case PDO::ERRMODE_SILENT:
  960. $bResult = $this->executeStatementSilent($oStatement, $aBindings, $bVerbose);
  961. break;
  962. case PDO::ERRMODE_EXCEPTION:
  963. $bResult = $this->executeStatementException($oStatement, $aBindings, $bVerbose);
  964. break;
  965. }
  966. if (!$bResult && !is_null($iErrorCode)) {
  967. $aError = $oStatement->errorInfo();
  968. $iErrorCode = $aError[1];
  969. }
  970. return $bResult;
  971. }
  972. protected function executeStatementException($oStatement, $aBindings = array(), $bVerbose = null)
  973. {
  974. $bResult = false;
  975. try {
  976. $bResult = $oStatement->execute(!empty($aBindings) && is_array($aBindings) ? $aBindings : null);
  977. }
  978. catch (PDOException $oException) {
  979. $aError = $oStatement->errorInfo();
  980. $oException->errorInfo[self::$_sErrorKey] = array(
  981. 'code' => BX_DB_ERR_QUERY_ERROR,
  982. 'message' => !empty($aError[2]) ? $aError[2] : $oException->getMessage(),
  983. 'query' => $oStatement->queryString,
  984. 'trace' => $oException->getTrace(),
  985. 'verbose' => $bVerbose
  986. );
  987. throw $oException;
  988. }
  989. return $bResult;
  990. }
  991. protected function executeStatementSilent($oStatement, $aBindings = array(), $bVerbose = null)
  992. {
  993. $bResult = $oStatement->execute(!empty($aBindings) && is_array($aBindings) ? $aBindings : null);
  994. if($bResult)
  995. return true;
  996. $aError = $oStatement->errorInfo();
  997. $aTrace = debug_backtrace();
  998. unset($aTrace[0]);
  999. $this->_aError = array(
  1000. 'code' => BX_DB_ERR_QUERY_ERROR,
  1001. 'message' => !empty($aError[2]) ? $aError[2] : '',
  1002. 'query' => $oStatement->queryString,
  1003. 'trace' => $aTrace,
  1004. 'verbose' => $bVerbose
  1005. );
  1006. return false;
  1007. }
  1008. protected function errorOutput($aError)
  1009. {
  1010. $aErrorLocation = array();
  1011. if(!empty($aError['query']) && !empty($aError['trace']))
  1012. foreach($aError['trace'] as $aCall )
  1013. if(isset($aCall['args']) && is_array($aCall['args']))
  1014. foreach($aCall['args'] as $argNum => $argVal)
  1015. if((is_string($argVal) && strcmp($argVal, $aError['query']) == 0) || ($argVal instanceof PDOStatement && strcmp($argVal->queryString, $aError['query']) == 0)) {
  1016. $aErrorLocation['file'] = isset($aCall['file']) ? $aCall['file'] : (isset($aCall['class']) ? 'class: ' . $aCall['class'] : 'undefined');
  1017. $aErrorLocation['line'] = isset($aCall['line']) ? $aCall['line'] : 'undefined';
  1018. $aErrorLocation['function'] = $aCall['function'];
  1019. $aErrorLocation['arg'] = $argNum;
  1020. }
  1021. $sOutput = '';
  1022. if(!empty($aError['query']))
  1023. $sOutput .= '<p><b>Query:</b><br />' . $aError['query'] . '</p>';
  1024. if(!empty($aError['message']))
  1025. $sOutput .= '<p><b>Mysql error:</b><br />' . $aError['message'] . '</p>';
  1026. if(!empty($aErrorLocation))
  1027. $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>';
  1028. $sOutput .= '<p><b>collation_connection:</b><br />' . $this->getOne("SELECT @@collation_connection") . '</p>';
  1029. if(!empty($aError['trace'])) {
  1030. $sBackTrace = print_r($aError['trace'], true);
  1031. if (defined ('BX_DATABASE_USER') && !is_array(BX_DATABASE_USER))
  1032. $sBackTrace = str_replace('[_sUser:protected] => ' . BX_DATABASE_USER, '[_sUser:protected] => *****', $sBackTrace);
  1033. if (defined ('BX_DATABASE_PASS') && !is_array(BX_DATABASE_PASS))
  1034. $sBackTrace = str_replace('[_sPassword:protected] => ' . BX_DATABASE_PASS, '[_sPassword:protected] => *****', $sBackTrace);
  1035. $sOutput .= '<div><b>Debug backtrace:</b></div><div style="overflow:scroll;height:300px;border:1px solid gray;"><pre>' . htmlspecialchars_adv($sBackTrace) . '</pre></div>';
  1036. }
  1037. if(!empty(self::$_aParams)) {
  1038. $sSettings = var_export(self::$_aParams, true);
  1039. $sOutput .= '<div><b>Settings:</b></div><div style="overflow:scroll;height:300px;border:1px solid gray;"><pre>' . htmlspecialchars_adv($sSettings) . '</pre></div>';
  1040. }
  1041. $sOutput .= '<p><b>Called script:</b><br />' . $_SERVER['PHP_SELF'] . '</p>';
  1042. if(!empty($_REQUEST)) {
  1043. $sRequest = var_export($_REQUEST, true);
  1044. $sOutput .= '<p><b>Request parameters:</b><br /><pre>' . htmlspecialchars_adv($sRequest) . '</pre></p>';
  1045. }
  1046. return $sOutput;
  1047. }
  1048. }
  1049. /**
  1050. * Create the very first instance and initiate connetion to database.
  1051. */
  1052. BxDolDb::getInstance();
  1053. function getParam($sParamName, $bUseCache = true)
  1054. {
  1055. $oObj = BxDolDb::getInstance();
  1056. if ($oObj === null)
  1057. return false;
  1058. return $oObj->getParam($sParamName, $bUseCache);
  1059. }
  1060. function setParam($sParamName, $sParamVal)
  1061. {
  1062. $oObj = BxDolDb::getInstance();
  1063. if ($oObj === null)
  1064. return false;
  1065. return $oObj->setParam($sParamName, $sParamVal);
  1066. }
  1067. /** @} */