BxDolDb.php 33 KB

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