BxDolDb.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  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. $oStatement->closeCursor();
  317. return array();
  318. }
  319. $this->_oStatement = $oStatement;
  320. return $aResult;
  321. }
  322. /**
  323. * return next row of pointed last getFirstRow calling data
  324. */
  325. public function getNextRow($iFetchType = PDO::FETCH_ASSOC)
  326. {
  327. if(!$this->_oStatement)
  328. return array();
  329. if(!in_array($iFetchType, array(PDO::FETCH_NUM, PDO::FETCH_ASSOC, PDO::FETCH_BOTH)))
  330. $iFetchType = $this->_iPdoFetchType;
  331. $aResult = $this->_oStatement->fetch($iFetchType);
  332. if($aResult !== false)
  333. return $aResult;
  334. $this->_oStatement->closeCursor();
  335. $this->_oStatement = null;
  336. return array();
  337. }
  338. /**
  339. * execute sql query and return table of records as result
  340. */
  341. public function getAll($oStatement, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  342. {
  343. $aResult = array();
  344. if(!$oStatement)
  345. return $aResult;
  346. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  347. $oStatement = $this->prepare($oStatement);
  348. if(!in_array($iFetchType, array(PDO::FETCH_NUM, PDO::FETCH_ASSOC, PDO::FETCH_BOTH)))
  349. $iFetchType = $this->_iPdoFetchType;
  350. if(!$this->res($oStatement, $aBindings))
  351. return array();
  352. $aResult = $oStatement->fetchAll($iFetchType);
  353. if($aResult === false)
  354. return array();
  355. return $aResult;
  356. }
  357. /**
  358. * Executes sql query and returns table of records as result.
  359. *
  360. * @deprecated use getAll instead.
  361. */
  362. public function fillArray($oStatement, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  363. {
  364. return $this->getAll($oStatement, $aBindings, $iFetchType);
  365. }
  366. /**
  367. * execute sql query and return table of records as result
  368. */
  369. public function getAllWithKey($oStatement, $sFieldKey, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  370. {
  371. $aResult = array();
  372. if(!$oStatement)
  373. return $aResult;
  374. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  375. $oStatement = $this->prepare($oStatement);
  376. $aRow = $this->getFirstRow($oStatement, $aBindings, $iFetchType);
  377. while(!empty($aRow)) {
  378. $aResult[$aRow[$sFieldKey]] = $aRow;
  379. $aRow = $this->getNextRow($iFetchType);
  380. }
  381. return $aResult;
  382. }
  383. /**
  384. * execute sql query and return table of records as result
  385. */
  386. public function getPairs($oStatement, $sFieldKey, $sFieldValue, $aBindings = [], $iFetchType = PDO::FETCH_ASSOC)
  387. {
  388. $aResult = [];
  389. if(!$oStatement)
  390. return $aResult;
  391. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  392. $oStatement = $this->prepare($oStatement);
  393. $aRow = $this->getFirstRow($oStatement, $aBindings, $iFetchType);
  394. while(!empty($aRow)) {
  395. $aResult[$aRow[$sFieldKey] ?? ''] = $aRow[$sFieldValue];
  396. $aRow = $this->getNextRow($iFetchType);
  397. }
  398. return $aResult;
  399. }
  400. /**
  401. * return number of affected rows in current mysql result
  402. *
  403. * NOTE: PDOStatement::rowCount works for SELECT queries in MySQL.
  404. * So, this method should be rewritten if the other DB engine will be used.
  405. */
  406. public function getNumRows($oStatement = null)
  407. {
  408. if($oStatement && ($oStatement instanceof PDOStatement))
  409. return $oStatement->rowCount();
  410. if($this->_oStatement && ($this->_oStatement instanceof PDOStatement))
  411. return $this->_oStatement->rowCount();
  412. return 0;
  413. }
  414. /**
  415. * returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement.
  416. */
  417. public function getAffectedRows($oStatement = null)
  418. {
  419. return $this->getNumRows($oStatement);
  420. }
  421. public function lastId()
  422. {
  423. return self::$_rLink->lastInsertId();
  424. }
  425. /**
  426. * execute any query return number of rows affected/false
  427. */
  428. public function query($oStatement, $aBindings = array(), $bVerbose = null)
  429. {
  430. if(!$oStatement)
  431. return false;
  432. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  433. $oStatement = $this->prepare($oStatement);
  434. if($this->res($oStatement, $aBindings, $bVerbose))
  435. return $oStatement->rowCount();
  436. return false;
  437. }
  438. /**
  439. * execute any query
  440. */
  441. public function res($oStatement, $aBindings = array(), $bVerbose = null)
  442. {
  443. if(!$oStatement || !($oStatement instanceof PDOStatement))
  444. return false;
  445. if($oStatement->errorCode() == BX_PDO_STATE_SUCCESS)
  446. return true;
  447. if(isset($GLOBALS['bx_profiler']))
  448. $GLOBALS['bx_profiler']->beginQuery($oStatement->queryString);
  449. for ($iAttempts = 3; $iAttempts > 0; --$iAttempts) {
  450. $oException = null;
  451. $iErrorCode = 0;
  452. $bResult = false;
  453. try {
  454. $bResult = $this->executeStatement($oStatement, $aBindings, $bVerbose, $iErrorCode);
  455. } catch (PDOException $oException) {
  456. $iErrorCode = $oException->errorInfo[1];
  457. }
  458. // if deadlock timeout - try again, make sure that deadlock timeout is short
  459. if (!$bResult && (1205 == $iErrorCode || 1213 == $iErrorCode)) {
  460. continue;
  461. }
  462. // if mysql connection is lost - reconnect and try again
  463. if(!$bResult && (2006 == $iErrorCode || !$this->ping())) {
  464. $this->disconnect();
  465. $this->connect();
  466. continue;
  467. }
  468. // in all other cases exit from the loop
  469. if ($oException)
  470. throw $oException;
  471. break;
  472. }
  473. if(isset($GLOBALS['bx_profiler']))
  474. $GLOBALS['bx_profiler']->endQuery($oStatement);
  475. ++self::$_iQueriesCounter;
  476. //is needed for SILENT mode
  477. if(!$bResult && !empty($this->_aError))
  478. $this->error($this->_aError);
  479. return $bResult;
  480. }
  481. /**
  482. * get mysql server info
  483. */
  484. public function getServerInfo()
  485. {
  486. return self::$_rLink->getAttribute(PDO::ATTR_SERVER_VERSION);
  487. }
  488. /**
  489. * get mysql version
  490. */
  491. public function getVersion()
  492. {
  493. $s = $this->getOne("SELECT VERSION()");
  494. return preg_match("/([0-9\.]+)/", $s, $m) ? $m[1] : false;
  495. }
  496. /**
  497. * get list of tables in database
  498. */
  499. public function listTables()
  500. {
  501. $sDBName = is_array($this->_sDbname) ? $this->_sDbname[0] : $this->_sDbname;
  502. $oStatement = $this->pdoQuery("SHOW TABLES FROM `" . $sDBName . "`");
  503. return $this->getColumn($oStatement);
  504. }
  505. public function getFields($sTable)
  506. {
  507. $oStatement = $this->pdoQuery("SHOW COLUMNS FROM `" . $sTable . "`");
  508. $aFields = $this->getAll($oStatement);
  509. $aResult = array('original' => array(), 'uppercase' => array());
  510. foreach($aFields as $aField) {
  511. $aResult['original'][] = $aField['Field'];
  512. $aResult['uppercase'][] = strtoupper($aField['Field']);
  513. }
  514. return $aResult;
  515. }
  516. public function fetchField($oStatement, $iField, $aBindings = array())
  517. {
  518. $aResult = array();
  519. if(!$oStatement)
  520. return $aResult;
  521. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement)) {
  522. $oStatement = $this->prepare($oStatement);
  523. if(!$this->res($oStatement, $aBindings))
  524. return $aResult;
  525. }
  526. return $oStatement->getColumnMeta($iField);
  527. }
  528. public function isTableExists($sTable)
  529. {
  530. $aTableNames = $this->listTables();
  531. foreach($aTableNames as $iKey => $sTableName)
  532. $aTableNames[$iKey] = strtoupper($sTableName);
  533. return in_array(strtoupper($sTable), $aTableNames);
  534. }
  535. public function isFieldExists($sTable, $sFieldName)
  536. {
  537. $aFields = $this->getFields($sTable);
  538. return in_array(strtoupper($sFieldName), $aFields['uppercase']);
  539. }
  540. public function isIndexExists($sTable, $sIndexName)
  541. {
  542. $bIndex = false;
  543. $aIndexes = $this->getAll("SHOW INDEXES FROM `" . $sTable . "`");
  544. foreach($aIndexes as $aIndex)
  545. if($aIndex['Key_name'] == $sIndexName) {
  546. $bIndex = true;
  547. break;
  548. }
  549. return $bIndex;
  550. }
  551. public function error($aError)
  552. {
  553. $sErrorType = self::$_aErrors[$aError['code']];
  554. $bVerbose = isset($aError['verbose']) ? (bool)$aError['verbose'] : $this->_bErrorChecking;
  555. if(!$bVerbose) {
  556. $this->log($sErrorType . ': ' . $aError['message']);
  557. if (!defined('BX_DOL_INSTALL')) // this is needed to display error during installation
  558. return;
  559. }
  560. if((defined('BX_DB_FULL_VISUAL_PROCESSING') && BX_DB_FULL_VISUAL_PROCESSING) || defined('BX_DOL_INSTALL')) {
  561. $sOutput = '<div style="border:2px solid red;padding:4px;width:600px;margin:0px auto;">'."\n";
  562. $sOutput .= '<div style="text-align:center;background-color:red;color:white;font-weight:bold;">Error</div>'."\n";
  563. $sOutput .= '<div style="text-align:center;">' . $sErrorType . '</div>'."\n";
  564. if((defined('BX_DB_FULL_DEBUG_MODE') && BX_DB_FULL_DEBUG_MODE) || defined('BX_DOL_INSTALL'))
  565. $sOutput .= $this->errorOutput($aError);
  566. $sOutput .= '</div>';
  567. }
  568. if (self::$_rLink) { // connection errors aren't logged since bx_log required DB connection
  569. bx_log('sys_db', "$sErrorType\n" .
  570. (empty($aError['message']) ? '' : " Error: {$aError['message']}\n") .
  571. (empty($aError['query']) ? '' : " Query: {$aError['query']}\n") .
  572. (!function_exists('getLoggedId') || !getLoggedId() ? '' : " Account ID: " . getLoggedId() . "\n"),
  573. BX_LOG_ERR
  574. );
  575. }
  576. if(defined('BX_DB_DO_EMAIL_ERROR_REPORT') && BX_DB_DO_EMAIL_ERROR_REPORT) {
  577. $sSiteTitle = $this->getParam('site_title');
  578. $sMailBody = "Database error in " . $sSiteTitle . "<br /><br /> \n";
  579. $sMailBody .= $this->errorOutput($aError);
  580. $sMailBody .= "<hr />Auto-report system";
  581. sendMail($this->getParam('site_email'), "Database error in " . $sSiteTitle, $sMailBody, 0, array(), BX_EMAIL_SYSTEM, 'html', true);
  582. }
  583. bx_show_service_unavailable_error_and_exit($sOutput);
  584. }
  585. public function isParamInCache($sKey)
  586. {
  587. return is_array(self::$_aParams) && isset(self::$_aParams[$sKey]);
  588. }
  589. public function cacheParams($bForceCacheInvalidate = false, $bForceCacheInvalidateMixed = false)
  590. {
  591. if ($bForceCacheInvalidate)
  592. $this->cacheParamsClear();
  593. self::$_aParams = $this->getPairs("SELECT `name`, `value` FROM `sys_options`", "name", "value");
  594. list($sTmplCode, $sTmplName) = BxDolTemplate::retrieveCode();
  595. if(!empty($sTmplCode) && !empty($sTmplName)) {
  596. $iTmplMix = 0;
  597. if(is_array($sTmplCode))
  598. list($sTmplCode, $iTmplMix) = $sTmplCode;
  599. $bMixesDiabled = ($GLOBALS['glMixesDisabled'] ?? false);
  600. if(empty($iTmplMix) && !$bMixesDiabled)
  601. $iTmplMix = (int)$this->getParam($sTmplName . '_default_mix');
  602. if(!empty($iTmplMix) && !$bMixesDiabled) {
  603. $sCacheNameMixed = self::$_sParamsCacheNameMixed . $sTmplCode . '_' . $iTmplMix;
  604. if($bForceCacheInvalidateMixed)
  605. $this->cacheParamsClear($sCacheNameMixed);
  606. $aMixed = $this->fromCache($sCacheNameMixed, 'getPairs', "SELECT `option`, `value` FROM `sys_options_mixes2options` WHERE `mix_id`=:mix_id", "option", "value", array(
  607. 'mix_id' => $iTmplMix
  608. ));
  609. if(!empty($aMixed) && is_array($aMixed))
  610. self::$_aParams = array_merge(self::$_aParams, $aMixed);
  611. }
  612. }
  613. if (empty(self::$_aParams)) {
  614. self::$_aParams = array();
  615. return false;
  616. }
  617. return true;
  618. }
  619. public function cacheParamsClear($sCacheName = '')
  620. {
  621. if(empty($sCacheName)) {
  622. self::$_aParams = [];
  623. $sCacheName = self::$_sParamsCacheName;
  624. }
  625. return $this->cleanCache($sCacheName);
  626. }
  627. public function isParam($sKey, $bFromCache = true)
  628. {
  629. if ($bFromCache && $this->isParamInCache($sKey))
  630. return true;
  631. $sQuery = $this->prepare("SELECT `name` FROM `sys_options` WHERE `name` = ? LIMIT 1", $sKey);
  632. return $this->getOne($sQuery) == $sKey;
  633. }
  634. public function addParam($sName, $sValue, $iKateg, $sDesc, $sType)
  635. {
  636. $sQuery = $this->prepare("INSERT INTO `sys_options` SET `category_id` = ?, `name` = ?, `caption` = ?, `value` = ?, `type` = ?", $iKateg, $sName, $sDesc, $sValue, $sType);
  637. $this->query($sQuery);
  638. // renew params cache
  639. $this->cacheParams(true);
  640. }
  641. public function getParam($sKey, $bFromCache = true)
  642. {
  643. if (!$sKey)
  644. return false;
  645. if ($bFromCache) {
  646. return $this->isParamInCache($sKey) ? self::$_aParams[$sKey] : false;
  647. } else {
  648. $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);
  649. $s = $this->getOne($sQuery);
  650. if($s === false) {
  651. $sQuery = $this->prepare("SELECT `value` FROM `sys_options` WHERE `name` = ? LIMIT 1", $sKey);
  652. $s = $this->getOne($sQuery);
  653. }
  654. self::$_aParams[$sKey] = $s; // cache it
  655. return $s;
  656. }
  657. }
  658. public function setParam($sKey, $mixedValue, $iMixId = 0)
  659. {
  660. if(empty($iMixId))
  661. $sQuery = $this->prepare("UPDATE `sys_options` SET `value` = ? WHERE `name` = ? LIMIT 1", $mixedValue, $sKey);
  662. else
  663. $sQuery = $this->prepare("REPLACE INTO `sys_options_mixes2options` SET `option` = ?, `mix_id` = ?, `value` = ?", $sKey, $iMixId, $mixedValue);
  664. $bResult = (int)$this->query($sQuery) > 0;
  665. // renew params cache
  666. self::$_aParams[$sKey] = $mixedValue;
  667. return $bResult;
  668. }
  669. public function getParamsMix($iId)
  670. {
  671. return $this->fromCache(self::$_sParamsCacheNameMix . $iId, 'getRow', 'SELECT * FROM `sys_options_mixes` WHERE `id`=:id', array(
  672. 'id' => $iId
  673. ));
  674. }
  675. public function getParamsMixActive($sType)
  676. {
  677. return $this->getRow("SELECT * FROM `sys_options_mixes` WHERE `type`=:type AND `active`='1'", array(
  678. 'type' => $sType
  679. ));
  680. }
  681. public function getParamsMixes($sType, $mixedPublished = false)
  682. {
  683. $aBindings = array('type' => $sType);
  684. $sQuery = "SELECT * FROM `sys_options_mixes` WHERE `type`=:type";
  685. if($mixedPublished !== false) {
  686. $aBindings['published'] = (int)$mixedPublished;
  687. $sQuery .= " AND `published`=:published";
  688. }
  689. return $this->getAll($sQuery, $aBindings);
  690. }
  691. public function setTimezone($sTimezone)
  692. {
  693. $oDate = new DateTime('now', new DateTimeZone($sTimezone));
  694. return $this->pdoExec('SET time_zone = "' . $oDate->format('P') . '"') !== false;
  695. }
  696. public function getEncoding()
  697. {
  698. $oStatement = $this->pdoQuery('SELECT @@character_set_database');
  699. if($oStatement !== false)
  700. return $this->getOne($oStatement);
  701. return false;
  702. }
  703. public function setErrorChecking ($b)
  704. {
  705. $this->_bErrorChecking = $b;
  706. }
  707. /**
  708. * Cache functions.
  709. */
  710. public function getDbCacheObject ()
  711. {
  712. if($this->_oDbCacheObject != null)
  713. return $this->_oDbCacheObject;
  714. $sEngine = $this->getParam('sys_db_cache_engine');
  715. $this->_oDbCacheObject = bx_instance('BxDolCache'.$sEngine);
  716. if(!$this->_oDbCacheObject->isAvailable())
  717. $this->_oDbCacheObject = bx_instance('BxDolCacheFile');
  718. return $this->_oDbCacheObject;
  719. }
  720. public function genDbCacheKey ($sName)
  721. {
  722. return 'db_' . $sName . '_' . bx_site_hash() . '.php';
  723. }
  724. /**
  725. * @param mixed $iTTL seconds, when an integer. A non-integer third argument is ignored:
  726. * existing callers pass a query string in that position. The file engine only
  727. * drops the entry when this read passes a TTL; other engines expire on write.
  728. */
  729. public function getCache ($sName, $sFunc, $iTTL = false)
  730. {
  731. if (!$this->getParam('sys_db_cache_enable'))
  732. return false;
  733. if (!is_int($iTTL) || $iTTL < 1)
  734. $iTTL = false;
  735. $oCache = $this->getDbCacheObject ();
  736. $sKey = $this->genDbCacheKey($sName);
  737. return $oCache->getData($sKey, $iTTL);
  738. }
  739. /**
  740. * @param mixed $iTTL seconds, when an integer greater than zero. Otherwise the engine default
  741. * (the file engine keeps the entry until it is deleted).
  742. */
  743. public function setCache ($sName, $mData, $iTTL = false)
  744. {
  745. if (!$this->getParam('sys_db_cache_enable'))
  746. return false;
  747. if (!is_int($iTTL) || $iTTL < 1)
  748. $iTTL = false;
  749. $oCache = $this->getDbCacheObject ();
  750. $sKey = $this->genDbCacheKey($sName);
  751. $oCache->setData($sKey, $mData, $iTTL);
  752. }
  753. public function fromCache ($sName, $sFunc)
  754. {
  755. $aArgs = func_get_args();
  756. array_shift ($aArgs); // shift $sName
  757. array_shift ($aArgs); // shift $sFunc
  758. if (!$this->getParam('sys_db_cache_enable'))
  759. return call_user_func_array (array ($this, $sFunc), $aArgs); // pass other function parameters as database function parameters
  760. $oCache = $this->getDbCacheObject ();
  761. $sKey = $this->genDbCacheKey($sName);
  762. $mixedRet = $oCache->getData($sKey);
  763. if ($mixedRet !== null) {
  764. return $mixedRet;
  765. } else {
  766. $mixedRet = call_user_func_array (array ($this, $sFunc), $aArgs); // pass other function parameters as database function parameters
  767. $oCache->setData($sKey, $mixedRet);
  768. }
  769. return $mixedRet;
  770. }
  771. public function cleanCache ($sName)
  772. {
  773. $oCache = $this->getDbCacheObject();
  774. $sKey = $this->genDbCacheKey($sName);
  775. return $oCache->delData($sKey);
  776. }
  777. public function &fromMemory ($sName, $sFunc)
  778. {
  779. if(array_key_exists($sName, self::$_aDbCacheData) && !defined('BX_DOL_INSTALL') && !defined('BX_DOL_CRON_EXECUTE'))
  780. return self::$_aDbCacheData[$sName];
  781. $aArgs = func_get_args();
  782. array_shift($aArgs); // shift $sName
  783. array_shift($aArgs); // shift $sFunc
  784. self::$_aDbCacheData[$sName] = call_user_func_array (array ($this, $sFunc), $aArgs); // pass other function parameters as database function parameters
  785. return self::$_aDbCacheData[$sName];
  786. }
  787. public function cleanMemory ($sName)
  788. {
  789. if(!isset(self::$_aDbCacheData[$sName]))
  790. return false;
  791. unset(self::$_aDbCacheData[$sName]);
  792. return true;
  793. }
  794. public function cleanMemoryAll ()
  795. {
  796. self::$_aDbCacheData = array();
  797. return true;
  798. }
  799. /**
  800. * It escapes string to pass to mysql query.
  801. * Try to use "prepare" function always (@see BxDolDb::prepare), use "escape" only if "prepare" function is not possible at all.
  802. * Also consider using "implode_escape" function (@see BxDolDb::implode_escape).
  803. *
  804. * @param string $s string to escape
  805. * @return escaped string whcich is ready to pass to SQL query.
  806. */
  807. public function escape($s)
  808. {
  809. try {
  810. $s = self::$_rLink->quote($s);
  811. }
  812. catch (PDOException $oException) {
  813. $oException->errorInfo[self::$_sErrorKey] = array(
  814. 'code' => BX_DB_ERR_ESCAPE,
  815. 'message' => $oException->getMessage(),
  816. 'trace' => $oException->getTrace()
  817. );
  818. throw $oException;
  819. }
  820. return $s;
  821. }
  822. /**
  823. * @param bool $bStrict one identifier of letters, digits and underscores. The loose check also allows a qualified name and most characters inside backticks.
  824. */
  825. public function isValidFieldName($s, $bStrict = false)
  826. {
  827. if ($bStrict)
  828. return is_string($s) && (bool)preg_match('/^[A-Za-z0-9_]+$/', $s);
  829. if (!is_string($s))
  830. return false;
  831. if (false !== strpos($s, '`.`')) {
  832. $a = explode('`.`', $s, 2);
  833. foreach ($a as $sField) {
  834. if (false === $this->isValidFieldName($sField, $bStrict))
  835. return false;
  836. }
  837. return true;
  838. }
  839. $inner = $s;
  840. // Disallow trailing space
  841. if ($inner === '' || preg_match('/\s$/u', $inner)) {
  842. return false;
  843. }
  844. // Disallow all-numeric content (even if quoted)
  845. if (preg_match('/^\d+$/u', $inner)) {
  846. return false;
  847. }
  848. $i = 0;
  849. $len = mb_strlen($inner, 'UTF-8');
  850. while ($i < $len) {
  851. $char = mb_substr($inner, $i, 1, 'UTF-8');
  852. // Allow escaped backtick (``)
  853. if ($char === '`') {
  854. if ($i + 1 >= $len || mb_substr($inner, $i + 1, 1, 'UTF-8') !== '`') {
  855. return false; // Single backtick is invalid
  856. }
  857. $i += 2;
  858. continue;
  859. }
  860. // Convert to UTF-8 bytes to check for supplementary chars
  861. $utf8 = mb_convert_encoding($char, 'UTF-8');
  862. $byteLen = strlen($utf8);
  863. // 1-byte to 3-byte UTF-8 sequences = BMP (valid)
  864. // 4-byte UTF-8 sequences = Supplementary chars (invalid)
  865. if ($byteLen === 4) {
  866. return false;
  867. }
  868. // Disallow ASCII NUL (0x00)
  869. if ($utf8 === "\x00") {
  870. return false;
  871. }
  872. $i++;
  873. }
  874. return true;
  875. /*
  876. // alternative quick checking without checking BMP range
  877. if (preg_match('/^[0-9]+$/', $s))
  878. return false;
  879. return preg_match('/^(?:(?!`)[\x01-\x7F\x{0080}-\x{FFFF}]|``)*[^[:space:]]$/u', $s);
  880. */
  881. }
  882. /**
  883. * This function is usefull when you need to form array of parameters to pass to IN(...) SQL construction.
  884. * Example:
  885. * @code
  886. * $a = array(2, 4.5, 'apple', 'car');
  887. * $s = "SELECT * FROM `t` WHERE `a` IN (" . $oDb->implode_escape($a) . ")";
  888. * echo $s; // outputs: SELECT * FROM `t` WHERE `a` IN (2, 4.5, 'apple', 'car')
  889. * @endcode
  890. *
  891. * @param $mixed array or parameters or just one paramter
  892. * @return string which is ready to pass to IN(...) SQL construction
  893. */
  894. public function implode_escape ($mixed)
  895. {
  896. if (is_array($mixed)) {
  897. $s = '';
  898. foreach ($mixed as $v)
  899. $s .= (is_numeric($v) ? $v : $this->escape($v)) . ',';
  900. if ($s)
  901. return substr($s, 0, -1);
  902. else
  903. return 'NULL';
  904. }
  905. return is_numeric($mixed) ? $mixed : ($mixed ? $this->escape($mixed) : 'NULL');
  906. }
  907. /**
  908. * @deprecated
  909. */
  910. public function unescape ($mixed)
  911. {
  912. if(is_array($mixed)) {
  913. foreach($mixed as $k => $v)
  914. $mixed[$k] = $this->getOne("SELECT '$v'");
  915. return $mixed;
  916. }
  917. else
  918. return $this->getOne("SELECT '$mixed'");
  919. }
  920. /**
  921. * Prepare SQL query before execution if some arguments are need to be passed to it.
  922. * All parameters marked with question (?) symbol in SQL query are replaced with parameters passed after SQL query parameter.
  923. * Parameters are properly excaped and surrounded by qutes if needed.
  924. * Example:
  925. * @code
  926. * $sSql = $oDb->prepare("SELECT `a`, `b` from `t` WHERE `c` = ? and `d` = ?", 12, 'aa');
  927. * echo $sSql;// outputs: SELECT `a`, `b` from `t` WHERE `c` = 12 and `d` = 'aa'
  928. * $a = $oDb->getAll($sSql);
  929. * @endcode
  930. *
  931. * @param string $sQuery SQL query, parameters for replacing are marked with ? symbol
  932. * @param mixed $mixed any number if parameters to replace, number of parameters whould match number of ? symbols in SQL query
  933. * @return PDOStatement object with SQL query ready for execution
  934. */
  935. public function prepare($sQuery)
  936. {
  937. if(!self::$_rLink)
  938. return false;
  939. if (self::$_bMultuServersMode && (0 != strncasecmp(ltrim($sQuery, " \t\n\r(\0\x0B"), 'SELECT', 6)))
  940. $this->setReadOnlyMode(false);
  941. $aArgs = func_get_args();
  942. $sQuery = array_shift($aArgs);
  943. $oStatement = self::$_rLink->prepare($sQuery);
  944. $iIndex = 1;
  945. foreach($aArgs as $mixedArg) {
  946. if(is_null($mixedArg))
  947. $iValueType = PDO::PARAM_NULL;
  948. else if(is_numeric($mixedArg) && is_int($mixedArg))
  949. $iValueType = PDO::PARAM_INT;
  950. else
  951. $iValueType = PDO::PARAM_STR;
  952. $oStatement->bindValue($iIndex++, $mixedArg, $iValueType);
  953. }
  954. return $oStatement;
  955. }
  956. /**
  957. * Prepare SQL query before execution if some arguments are need to be passed to it.
  958. * All parameters marked with question (?) symbol in SQL query are replaced with parameters passed after SQL query parameter.
  959. * Parameters are properly excaped and surrounded by qutes if needed.
  960. * Example:
  961. * @code
  962. * $sSql = $oDb->prepare("SELECT `a`, `b` from `t` WHERE `c` = ? and `d` = ?", 12, 'aa');
  963. * echo $sSql;// outputs: SELECT `a`, `b` from `t` WHERE `c` = 12 and `d` = 'aa'
  964. * $a = $oDb->getAll($sSql);
  965. * @endcode
  966. *
  967. * @param string $sQuery SQL query, parameters for replacing are marked with ? symbol
  968. * @param mixed $mixed any number if parameters to replace, number of parameters whould match number of ? symbols in SQL query
  969. * @return string with SQL query.
  970. */
  971. function prepareAsString($sQuery)
  972. {
  973. $aArgs = func_get_args();
  974. $sQuery = array_shift($aArgs);
  975. $iPos = 0;
  976. foreach ($aArgs as $mixedArg) {
  977. if (is_null($mixedArg))
  978. $s = 'NULL';
  979. elseif (is_numeric($mixedArg))
  980. $s = $mixedArg;
  981. else
  982. $s = $this->escape($mixedArg);
  983. $i = bx_mb_strpos($sQuery, '?', $iPos);
  984. $sQuery = bx_mb_substr_replace($sQuery, $s, $i, 1);
  985. $iPos = $i + get_mb_len($s);
  986. }
  987. return $sQuery;
  988. }
  989. /**
  990. * Convert array of key => values to SQL query.
  991. * Array keys are field names and array values are field values.
  992. * @param $a array
  993. * @param $sDiv fields separator, by default it is ',', another useful value is ' AND '
  994. * @param $sOperator operator for comparision: '=' or 'LIKE'
  995. * @param $bWildcardSpaceChars substiture any space and dash characters with single wildcard symbol
  996. * @return part of SQL query string
  997. */
  998. public function arrayToSQL($a, $sDiv = ',', $sOperator = '=', $bWildcardSpaceChars = false)
  999. {
  1000. $aOperators = ['=', 'LIKE', 'like'];
  1001. $sOperator = in_array($sOperator, $aOperators) ? $sOperator : '=';
  1002. $s = '';
  1003. foreach($a as $k => $v) {
  1004. if (!$this->isValidFieldName($k))
  1005. throw new Exception('Invalid field name in arrayToSQL method');
  1006. if ($bWildcardSpaceChars)
  1007. $v = preg_replace('/[\p{Zs}\p{Cc}\p{Pd}]/', '_', $v);
  1008. $s .= "`{$k}` {$sOperator} " . (is_null($v) ? 'NULL' : $this->escape($v)) . $sDiv;
  1009. }
  1010. return trim($s, $sDiv);
  1011. }
  1012. function isValidOperator(string $operator): bool
  1013. {
  1014. static $operators = [
  1015. // Comparison
  1016. '=', '!=', '<>', '<', '>', '<=', '>=',
  1017. '<=>',
  1018. // Logical
  1019. 'AND', 'OR', 'XOR', 'NOT',
  1020. // Arithmetic
  1021. '+', '-', '*', '/', '%',
  1022. 'DIV', 'MOD',
  1023. // Bitwise
  1024. '&', '|', '^', '<<', '>>',
  1025. // Other MySQL operators
  1026. 'IS', 'IS NOT',
  1027. 'LIKE', 'NOT LIKE',
  1028. 'REGEXP', 'NOT REGEXP',
  1029. 'IN', 'NOT IN',
  1030. 'BETWEEN', 'NOT BETWEEN',
  1031. // Custom functions/operators
  1032. 'COUNT', 'LOCATE',
  1033. 'EMPTY VALUE',
  1034. 'NOT EMPTY VALUE',
  1035. 'NOTHING',
  1036. 'IN_SET',
  1037. ];
  1038. return in_array(strtoupper(trim($operator)), $operators, true);
  1039. }
  1040. protected function log($s)
  1041. {
  1042. if (defined('BX_DIRECTORY_PATH_LOGS')) {
  1043. $sPath = BX_DIRECTORY_PATH_LOGS;
  1044. }
  1045. else {
  1046. $sDirName = pathinfo(__FILE__, PATHINFO_DIRNAME);
  1047. $sPath = $sDirName . '/../../logs/';
  1048. }
  1049. return file_put_contents($sPath . 'db.err.log', date('Y-m-d H:i:s') . "\t" . $s . "\n", FILE_APPEND);
  1050. }
  1051. public function executeSQL($sPath, $aReplace = array (), $isBreakOnError = true)
  1052. {
  1053. if(!file_exists($sPath) || !($rHandler = fopen($sPath, "r")))
  1054. return array(array ('query' => "fopen($sPath, 'r')", 'error' => 'file not found or permission denied'));
  1055. self::$_rLink->setAttribute(PDO::ATTR_ERRMODE, BX_DB_MODE_SILENT);
  1056. $sQuery = "";
  1057. $sDelimiter = ';';
  1058. $aResult = array();
  1059. while(!feof($rHandler)) {
  1060. $sStr = trim(fgets($rHandler));
  1061. if(empty($sStr) || $sStr[0] == "" || $sStr[0] == "#" || ($sStr[0] == "-" && $sStr[1] == "-"))
  1062. continue;
  1063. //--- Change delimiter ---//
  1064. if(strpos($sStr, "DELIMITER //") !== false || strpos($sStr, "DELIMITER ;") !== false) {
  1065. $sDelimiter = trim(str_replace('DELIMITER', '', $sStr));
  1066. continue;
  1067. }
  1068. $sQuery .= $sStr;
  1069. //--- Check for multiline query ---//
  1070. if(substr($sStr, -strlen($sDelimiter)) != $sDelimiter)
  1071. continue;
  1072. //--- Execute query ---//
  1073. if ($aReplace)
  1074. $sQuery = str_replace($aReplace['from'], $aReplace['to'], $sQuery);
  1075. if($sDelimiter != ';')
  1076. $sQuery = str_replace($sDelimiter, "", $sQuery);
  1077. if($this->query(trim($sQuery), array(), false) === false) {
  1078. $aResult[] = array('query' => $sQuery, 'error' => $this->_aError['message']);
  1079. if ($isBreakOnError)
  1080. break;
  1081. }
  1082. $sQuery = "";
  1083. }
  1084. fclose($rHandler);
  1085. self::$_rLink->setAttribute(PDO::ATTR_ERRMODE, $this->_iPdoErrorMode);
  1086. return empty($aResult) ? true : $aResult;
  1087. }
  1088. protected function executeStatement($oStatement, $aBindings = array(), $bVerbose = null, &$iErrorCode = null)
  1089. {
  1090. $bResult = false;
  1091. if (!isset($aBindings[0])) {
  1092. foreach($aBindings as $sKey => $mixedValue) {
  1093. if(is_null($mixedValue))
  1094. $oStatement->bindValue(":{$sKey}", $mixedValue, PDO::PARAM_NULL);
  1095. else if(is_numeric($mixedValue) && is_int($mixedValue))
  1096. $oStatement->bindValue(":{$sKey}", $mixedValue, PDO::PARAM_INT);
  1097. else
  1098. $oStatement->bindValue(":{$sKey}", $mixedValue, PDO::PARAM_STR);
  1099. }
  1100. $aBindings = array();
  1101. }
  1102. switch (self::$_rLink->getAttribute(PDO::ATTR_ERRMODE)) {
  1103. case PDO::ERRMODE_SILENT:
  1104. $bResult = $this->executeStatementSilent($oStatement, $aBindings, $bVerbose);
  1105. break;
  1106. case PDO::ERRMODE_EXCEPTION:
  1107. $bResult = $this->executeStatementException($oStatement, $aBindings, $bVerbose);
  1108. break;
  1109. }
  1110. if (!$bResult && !is_null($iErrorCode)) {
  1111. $aError = $oStatement->errorInfo();
  1112. $iErrorCode = $aError[1];
  1113. }
  1114. return $bResult;
  1115. }
  1116. protected function executeStatementException($oStatement, $aBindings = array(), $bVerbose = null)
  1117. {
  1118. $bResult = false;
  1119. try {
  1120. $bResult = $oStatement->execute(!empty($aBindings) && is_array($aBindings) ? $aBindings : null);
  1121. }
  1122. catch (PDOException $oException) {
  1123. $aError = $oStatement->errorInfo();
  1124. $oException->errorInfo[self::$_sErrorKey] = array(
  1125. 'code' => BX_DB_ERR_QUERY_ERROR,
  1126. 'message' => !empty($aError[2]) ? $aError[2] : $oException->getMessage(),
  1127. 'query' => $oStatement->queryString,
  1128. 'trace' => $oException->getTrace(),
  1129. 'verbose' => $bVerbose
  1130. );
  1131. throw $oException;
  1132. }
  1133. return $bResult;
  1134. }
  1135. protected function executeStatementSilent($oStatement, $aBindings = array(), $bVerbose = null)
  1136. {
  1137. $bResult = $oStatement->execute(!empty($aBindings) && is_array($aBindings) ? $aBindings : null);
  1138. if($bResult)
  1139. return true;
  1140. $aError = $oStatement->errorInfo();
  1141. $aTrace = debug_backtrace();
  1142. unset($aTrace[0]);
  1143. $this->_aError = array(
  1144. 'code' => BX_DB_ERR_QUERY_ERROR,
  1145. 'message' => !empty($aError[2]) ? $aError[2] : '',
  1146. 'query' => $oStatement->queryString,
  1147. 'trace' => $aTrace,
  1148. 'verbose' => $bVerbose
  1149. );
  1150. return false;
  1151. }
  1152. protected function errorOutput($aError)
  1153. {
  1154. $aErrorLocation = [];
  1155. if(!empty($aError['query']) && !empty($aError['trace']))
  1156. foreach($aError['trace'] as $aCall )
  1157. if(isset($aCall['args']) && is_array($aCall['args']))
  1158. foreach($aCall['args'] as $argNum => $argVal)
  1159. if((is_string($argVal) && strcmp($argVal, $aError['query']) == 0) || ($argVal instanceof PDOStatement && strcmp($argVal->queryString, $aError['query']) == 0)) {
  1160. $aErrorLocation['file'] = isset($aCall['file']) ? $aCall['file'] : (isset($aCall['class']) ? 'class: ' . $aCall['class'] : 'undefined');
  1161. $aErrorLocation['line'] = isset($aCall['line']) ? $aCall['line'] : 'undefined';
  1162. $aErrorLocation['function'] = $aCall['function'];
  1163. $aErrorLocation['arg'] = $argNum;
  1164. }
  1165. $sOutput = '';
  1166. if(!empty($aError['query']))
  1167. $sOutput .= '<p><b>Query:</b><br />' . bx_process_output($aError['query']) . '</p>'."\n";
  1168. if(!empty($aError['message']))
  1169. $sOutput .= '<p><b>Mysql error:</b><br />' . $aError['message'] . '</p>'."\n";
  1170. if(!empty($aErrorLocation))
  1171. $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";
  1172. $sOutput .= '<p><b>collation_connection:</b><br />' . $this->getOne("SELECT @@collation_connection") . '</p>'."\n";
  1173. if(!empty($aError['trace'])) {
  1174. $sBackTrace = print_r($aError['trace'], true);
  1175. if(defined ('BX_DATABASE_USER') && !is_array(BX_DATABASE_USER))
  1176. $sBackTrace = str_replace('[_sUser:protected] => ' . BX_DATABASE_USER, '[_sUser:protected] => *****', $sBackTrace);
  1177. if(defined ('BX_DATABASE_PASS') && !is_array(BX_DATABASE_PASS))
  1178. $sBackTrace = str_replace('[_sPassword:protected] => ' . BX_DATABASE_PASS, '[_sPassword:protected] => *****', $sBackTrace);
  1179. $sOutput .= '<div><b>Debug backtrace:</b></div><div style="overflow:scroll;height:300px;border:1px solid gray;"><pre>' . htmlspecialchars_adv($sBackTrace) . '</pre></div>';
  1180. }
  1181. if(!empty(self::$_aParams)) {
  1182. $aParams = self::$_aParams;
  1183. $aParamsSecret = $this->getColumn("SELECT `name` FROM `sys_options` WHERE `type`='secret'", "name");
  1184. if($aParamsSecret && is_array($aParamsSecret))
  1185. array_walk($aParams, function(&$sValue, $sKey) use ($aParamsSecret) {
  1186. if(in_array($sKey, $aParamsSecret)) {
  1187. $sValue = bx_gen_secret($sValue);
  1188. } elseif (mb_strlen($sValue) > 100) {
  1189. $sValue = mb_substr($sValue, 0, 100) . '...';
  1190. }
  1191. });
  1192. $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>';
  1193. }
  1194. $sOutput .= '<p><b>Called script:</b><br />' . htmlspecialchars_adv($_SERVER['PHP_SELF']) . '</p>';
  1195. if(!empty($_REQUEST))
  1196. $sOutput .= '<p><b>Request parameters:</b><br /><pre>' . htmlspecialchars_adv(var_export($_REQUEST, true)) . '</pre></p>';
  1197. return $sOutput;
  1198. }
  1199. }
  1200. /**
  1201. * Create the very first instance and initiate connetion to database.
  1202. */
  1203. BxDolDb::getInstance();
  1204. function getParam($sParamName, $bUseCache = true)
  1205. {
  1206. if (bx_is_api() && $sParamName == 'permalinks_seo_links')
  1207. return true;
  1208. $oObj = BxDolDb::getInstance();
  1209. if ($oObj === null)
  1210. return false;
  1211. return $oObj->getParam($sParamName, $bUseCache);
  1212. }
  1213. function setParam($sParamName, $sParamVal)
  1214. {
  1215. $oObj = BxDolDb::getInstance();
  1216. if ($oObj === null)
  1217. return false;
  1218. return $oObj->setParam($sParamName, $sParamVal);
  1219. }
  1220. /** @} */