BxDolDb.php 35 KB

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