BxDolDb.php 37 KB

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