BxDolDb.php 47 KB

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