BxDolDb.php 37 KB

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