1
0

BxDolDb.php 34 KB

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