BxDolDb.php 37 KB

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