BxDolUpgradeDb.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaUpgrade UNA Upgrade Script
  7. * @{
  8. */
  9. define('BX_UPGRADE_DB_FULL_VISUAL_PROCESSING', true);
  10. define('BX_UPGRADE_DB_FULL_DEBUG_MODE', true);
  11. define('BX_UPGRADE_DB_ERR_CONNECT_FAILD', 1);
  12. define('BX_UPGRADE_DB_ERR_QUERY_ERROR', 2);
  13. define('BX_UPGRADE_DB_ERR_ESCAPE', 3);
  14. define('BX_UPGRADE_PDO_STATE_SUCCESS', '00000');
  15. class BxDolUpgradeDb
  16. {
  17. protected static $_rLink;
  18. protected static $_aDbCacheData;
  19. protected static $_aParams;
  20. protected static $_sParamsCacheName = 'sys_options';
  21. protected static $_sParamsCacheNameMixed = 'sys_options_mixed';
  22. protected static $_sErrorKey = 'bx_db_error';
  23. protected static $_aErrors = array(
  24. BX_UPGRADE_DB_ERR_CONNECT_FAILD => 'Database connect failed',
  25. BX_UPGRADE_DB_ERR_QUERY_ERROR => 'Database query error',
  26. BX_UPGRADE_DB_ERR_ESCAPE => 'Escape string error'
  27. );
  28. protected $_bPdoPersistent;
  29. protected $_iPdoFetchType;
  30. protected $_iPdoErrorMode;
  31. protected $_bErrorChecking;
  32. protected $_aError;
  33. protected $_sHost, $_sPort, $_sSocket, $_sDbname, $_sUser, $_sPassword, $_sCharset, $_sStorageEngine;
  34. protected $_oStatement = null;
  35. protected $_oDbCacheObject = null;
  36. /**
  37. * set database parameters and connect to it
  38. */
  39. protected function __construct()
  40. {
  41. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  42. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  43. $this->_bPdoPersistent = true;
  44. $this->_iPdoFetchType = PDO::FETCH_ASSOC;
  45. $this->_iPdoErrorMode = PDO::ERRMODE_EXCEPTION;
  46. $this->_bErrorChecking = true;
  47. $this->_aError = array();
  48. $this->_sStorageEngine = 'MYISAM';
  49. $this->_sCharset = 'utf8mb4';
  50. $this->_sHost = is_array(BX_DATABASE_HOST) ? array_values(BX_DATABASE_HOST)[0] : BX_DATABASE_HOST;
  51. $this->_sPort = is_array(BX_DATABASE_PORT) ? array_values(BX_DATABASE_PORT)[0] : BX_DATABASE_PORT;
  52. $this->_sSocket = is_array(BX_DATABASE_SOCK) ? array_values(BX_DATABASE_SOCK)[0] : BX_DATABASE_SOCK;
  53. $this->_sDbname = is_array(BX_DATABASE_NAME) ? array_values(BX_DATABASE_NAME)[0] : BX_DATABASE_NAME;
  54. $this->_sUser = is_array(BX_DATABASE_USER) ? array_values(BX_DATABASE_USER)[0] : BX_DATABASE_USER;
  55. $this->_sPassword = is_array(BX_DATABASE_PASS) ? array_values(BX_DATABASE_PASS)[0] : BX_DATABASE_PASS;
  56. if (defined('BX_DATABASE_ENGINE'))
  57. $this->_sStorageEngine = is_array(BX_DATABASE_ENGINE) ? array_values(BX_DATABASE_ENGINE)[0] : BX_DATABASE_ENGINE;
  58. @set_exception_handler(array($this, 'pdoExceptionHandler'));
  59. }
  60. /**
  61. * Get singleton instance of the class
  62. */
  63. public static function getInstance()
  64. {
  65. if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
  66. if(!defined('BX_DATABASE_HOST'))
  67. return null;
  68. $o = new BxDolUpgradeDb();
  69. $o->connect();
  70. $GLOBALS['bxDolClasses'][__CLASS__] = $o;
  71. }
  72. return $GLOBALS['bxDolClasses'][__CLASS__];
  73. }
  74. public static function getLink()
  75. {
  76. return self::$_rLink;
  77. }
  78. /**
  79. * connect to database with appointed parameters
  80. */
  81. public function connect()
  82. {
  83. if(self::$_rLink)
  84. return;
  85. try {
  86. $sDsn = "mysql:host=" . $this->_sHost . ";";
  87. $sDsn .= $this->_sPort ? "port=" . $this->_sPort . ";" : "";
  88. $sDsn .= $this->_sSocket ? "unix_socket=" . $this->_sSocket . ";" : "";
  89. $sDsn .= "dbname=" . $this->_sDbname . ";charset=" . $this->_sCharset;
  90. self::$_rLink = new PDO($sDsn, $this->_sUser, $this->_sPassword, array(
  91. PDO::ATTR_ERRMODE => $this->_iPdoErrorMode,
  92. PDO::ATTR_DEFAULT_FETCH_MODE => $this->_iPdoFetchType,
  93. PDO::ATTR_PERSISTENT => $this->_bPdoPersistent
  94. ));
  95. $this->pdoExec("SET NAMES 'utf8mb4' COLLATE '" . (defined('BX_DATABASE_COLLATE') ? BX_DATABASE_COLLATE : 'utf8mb4_unicode_ci') . "'");
  96. $this->pdoExec("SET sql_mode = ''");
  97. $sVer = $this->getVersion();
  98. $sStorageEngine = !$sVer || version_compare($sVer, '5.7.5', '>=') ? 'default_storage_engine' : 'storage_engine';
  99. $this->pdoExec("SET $sStorageEngine=" . $this->_sStorageEngine);
  100. self::$_aDbCacheData = array();
  101. }
  102. catch (PDOException $oException) {
  103. $oException->errorInfo[self::$_sErrorKey] = array(
  104. 'code' => BX_UPGRADE_DB_ERR_CONNECT_FAILD,
  105. 'message' => $oException->getMessage(),
  106. 'trace' => $oException->getTrace()
  107. );
  108. throw $oException;
  109. }
  110. }
  111. /**
  112. * close mysql connection
  113. */
  114. public function disconnect()
  115. {
  116. self::$_rLink = null;
  117. }
  118. /**
  119. * check mysql connection
  120. */
  121. public function ping()
  122. {
  123. try {
  124. $this->pdoQuery("SELECT 1");
  125. }
  126. catch (PDOException $e) {
  127. return false;
  128. }
  129. return true;
  130. }
  131. /**
  132. * Can be used to execute queries which shouldn't return data
  133. */
  134. public function pdoExec($sQuery)
  135. {
  136. return self::$_rLink->exec($sQuery);
  137. }
  138. /**
  139. * Executes query and returns PDOStatement object or false
  140. */
  141. public function pdoQuery($sQuery)
  142. {
  143. return self::$_rLink->query($sQuery);
  144. }
  145. /**
  146. * database query exception handler for exceptions appeared out of the try/catch block
  147. */
  148. public function pdoExceptionHandler($oException)
  149. {
  150. if(!($oException instanceof PDOException))
  151. return;
  152. $this->error($oException->errorInfo[self::$_sErrorKey]);
  153. return;
  154. }
  155. /**
  156. * get mysql option
  157. */
  158. function getOption($sName)
  159. {
  160. $oStatement = $this->pdoQuery("SELECT @@{$sName}");
  161. return $this->getOne($oStatement);
  162. }
  163. /**
  164. * execute sql query and return one value result
  165. */
  166. public function getOne($oStatement, $aBindings = array(), $iIndex = 0)
  167. {
  168. if(!$oStatement)
  169. return false;
  170. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  171. $oStatement = $this->prepare($oStatement);
  172. $aResult = array();
  173. if($this->res($oStatement, $aBindings))
  174. $aResult = $oStatement->fetch(PDO::FETCH_NUM);
  175. return is_array($aResult) && count($aResult) ? $aResult[$iIndex] : false;
  176. }
  177. /**
  178. * execute sql query and return one row result
  179. */
  180. function getRow($oStatement, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  181. {
  182. $aResult = array();
  183. if(!$oStatement)
  184. return $aResult;
  185. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  186. $oStatement = $this->prepare($oStatement);
  187. if(!in_array($iFetchType, array(PDO::FETCH_NUM, PDO::FETCH_ASSOC, PDO::FETCH_BOTH)))
  188. $iFetchType = $this->_iPdoFetchType;
  189. if(!$this->res($oStatement, $aBindings))
  190. return array();
  191. $aResult = $oStatement->fetch($iFetchType);
  192. if($aResult === false)
  193. return array();
  194. return $aResult;
  195. }
  196. /**
  197. * execute sql query and return a column as result
  198. */
  199. function getColumn($oStatement, $aBindings = array(), $iFetchColumnNumber = 0)
  200. {
  201. $aResult = array();
  202. if(!$oStatement)
  203. return $aResult;
  204. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  205. $oStatement = $this->prepare($oStatement);
  206. if(!$this->res($oStatement, $aBindings))
  207. return array();
  208. $aResult = $oStatement->fetchAll(PDO::FETCH_COLUMN, $iFetchColumnNumber);
  209. if($aResult === false)
  210. return array();
  211. return $aResult;
  212. }
  213. /**
  214. * execute sql query and return the first row of result
  215. * and keep $array type and poiter to all data
  216. */
  217. public function getFirstRow($oStatement, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  218. {
  219. if(!$oStatement)
  220. return array();
  221. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  222. $oStatement = $this->prepare($oStatement);
  223. if(!in_array($iFetchType, array(PDO::FETCH_NUM, PDO::FETCH_ASSOC, PDO::FETCH_BOTH)))
  224. $iFetchType = $this->_iPdoFetchType;
  225. if(!$this->res($oStatement, $aBindings))
  226. return array();
  227. $aResult = $oStatement->fetch($iFetchType);
  228. if($aResult === false)
  229. return array();
  230. $this->_oStatement = $oStatement;
  231. return $aResult;
  232. }
  233. /**
  234. * return next row of pointed last getFirstRow calling data
  235. */
  236. public function getNextRow($iFetchType = PDO::FETCH_ASSOC)
  237. {
  238. if(!$this->_oStatement)
  239. return array();
  240. if(!in_array($iFetchType, array(PDO::FETCH_NUM, PDO::FETCH_ASSOC, PDO::FETCH_BOTH)))
  241. $iFetchType = $this->_iPdoFetchType;
  242. $aResult = $this->_oStatement->fetch($iFetchType);
  243. if($aResult !== false)
  244. return $aResult;
  245. $this->_oStatement = null;
  246. return array();
  247. }
  248. /**
  249. * execute sql query and return table of records as result
  250. */
  251. public function getAll($oStatement, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  252. {
  253. $aResult = array();
  254. if(!$oStatement)
  255. return $aResult;
  256. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  257. $oStatement = $this->prepare($oStatement);
  258. if(!in_array($iFetchType, array(PDO::FETCH_NUM, PDO::FETCH_ASSOC, PDO::FETCH_BOTH)))
  259. $iFetchType = $this->_iPdoFetchType;
  260. if(!$this->res($oStatement, $aBindings))
  261. return array();
  262. $aResult = $oStatement->fetchAll($iFetchType);
  263. if($aResult === false)
  264. return array();
  265. return $aResult;
  266. }
  267. /**
  268. * Executes sql query and returns table of records as result.
  269. *
  270. * @deprecated use getAll instead.
  271. */
  272. public function fillArray($oStatement, $aBindings = array(), $iFetchType = PDO::FETCH_ASSOC)
  273. {
  274. return $this->getAll($oStatement, $aBindings);
  275. }
  276. /**
  277. * execute sql query and return table of records as result
  278. */
  279. public function getAllWithKey($oStatement, $sFieldKey, $aBindings = array())
  280. {
  281. $aResult = array();
  282. if(!$oStatement)
  283. return $aResult;
  284. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  285. $oStatement = $this->prepare($oStatement);
  286. $aRow = $this->getFirstRow($oStatement, $aBindings, PDO::FETCH_ASSOC);
  287. while(!empty($aRow)) {
  288. $aResult[$aRow[$sFieldKey]] = $aRow;
  289. $aRow = $this->getNextRow(PDO::FETCH_ASSOC);
  290. }
  291. return $aResult;
  292. }
  293. /**
  294. * execute sql query and return table of records as result
  295. */
  296. public function getPairs($oStatement, $sFieldKey, $sFieldValue, $aBindings = array())
  297. {
  298. $aResult = array();
  299. if(!$oStatement)
  300. return $aResult;
  301. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  302. $oStatement = $this->prepare($oStatement);
  303. $aRow = $this->getFirstRow($oStatement, $aBindings, PDO::FETCH_ASSOC);
  304. while(!empty($aRow)) {
  305. $aResult[$aRow[$sFieldKey]] = $aRow[$sFieldValue];
  306. $aRow = $this->getNextRow(PDO::FETCH_ASSOC);
  307. }
  308. return $aResult;
  309. }
  310. /**
  311. * return number of affected rows in current mysql result
  312. *
  313. * NOTE: PDOStatement::rowCount works for SELECT queries in MySQL.
  314. * So, this method should be rewritten if the other DB engine will be used.
  315. */
  316. public function getNumRows($oStatement = null)
  317. {
  318. if($oStatement && ($oStatement instanceof PDOStatement))
  319. return $oStatement->rowCount();
  320. if($this->_oStatement && ($this->_oStatement instanceof PDOStatement))
  321. return $this->_oStatement->rowCount();
  322. return 0;
  323. }
  324. /**
  325. * returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement.
  326. */
  327. public function getAffectedRows($oStatement = null)
  328. {
  329. return $this->getNumRows($oStatement);
  330. }
  331. public function lastId()
  332. {
  333. return self::$_rLink->lastInsertId();
  334. }
  335. /**
  336. * execute any query return number of rows affected/false
  337. */
  338. public function query($oStatement, $aBindings = array(), $bVerbose = null)
  339. {
  340. if(!$oStatement)
  341. return false;
  342. else if(!($oStatement instanceof PDOStatement) && is_string($oStatement))
  343. $oStatement = $this->prepare($oStatement);
  344. if($this->res($oStatement, $aBindings, $bVerbose))
  345. return $oStatement->rowCount();
  346. return false;
  347. }
  348. /**
  349. * execute any query
  350. */
  351. public function res($oStatement, $aBindings = array(), $bVerbose = null)
  352. {
  353. if(!$oStatement || !($oStatement instanceof PDOStatement))
  354. return false;
  355. if($oStatement->errorCode() == BX_UPGRADE_PDO_STATE_SUCCESS)
  356. return true;
  357. if(isset($GLOBALS['bx_profiler']))
  358. $GLOBALS['bx_profiler']->beginQuery($oStatement->queryString);
  359. $bResult = $this->executeStatement($oStatement, $aBindings, $bVerbose);
  360. //if mysql connection is lost - reconnect and try again
  361. if(!$bResult && !$this->ping()) {
  362. $this->disconnect();
  363. $this->connect();
  364. $bResult = $this->executeStatement($oStatement, $aBindings, $bVerbose);
  365. }
  366. if(isset($GLOBALS['bx_profiler']))
  367. $GLOBALS['bx_profiler']->endQuery($bResult);
  368. //is needed for SILENT mode
  369. if(!$bResult && !empty($this->_aError))
  370. $this->error($this->_aError);
  371. return $bResult;
  372. }
  373. /**
  374. * get mysql server info
  375. */
  376. public function getServerInfo()
  377. {
  378. return self::$_rLink->getAttribute(PDO::ATTR_SERVER_VERSION);
  379. }
  380. /**
  381. * get mysql version
  382. */
  383. public function getVersion()
  384. {
  385. $s = $this->getOne("SELECT VERSION()");
  386. return preg_match("/([0-9\.]+)/", $s, $m) ? $m[1] : false;
  387. }
  388. /**
  389. * get list of tables in database
  390. */
  391. public function listTables()
  392. {
  393. $oStatement = $this->pdoQuery("SHOW TABLES FROM `" . BX_DATABASE_NAME . "`");
  394. return $this->getColumn($oStatement);
  395. }
  396. public function getFields($sTable)
  397. {
  398. $oStatement = $this->pdoQuery("SHOW COLUMNS FROM `" . $sTable . "`");
  399. $aFields = $this->getAll($oStatement);
  400. $aResult = array('original' => array(), 'uppercase' => array());
  401. foreach($aFields as $aField) {
  402. $aResult['original'][] = $aField['Field'];
  403. $aResult['uppercase'][] = strtoupper($aField['Field']);
  404. }
  405. return $aResult;
  406. }
  407. public function isFieldExists($sTable, $sFieldName)
  408. {
  409. $aFields = $this->getFields($sTable);
  410. return in_array(strtoupper($sFieldName), $aFields['uppercase']);
  411. }
  412. public function isIndexExists($sTable, $sIndexName)
  413. {
  414. $aIndexes = $this->getAll("SHOW INDEXES FROM `" . $sTable . "`");
  415. foreach ($aIndexes as $aIndex)
  416. if ($aIndex['Key_name'] == $sIndexName)
  417. return true;
  418. return false;
  419. }
  420. public function error($aError)
  421. {
  422. $sErrorType = self::$_aErrors[$aError['code']];
  423. $bVerbose = isset($aError['verbose']) ? (bool)$aError['verbose'] : $this->_bErrorChecking;
  424. if(!$bVerbose) {
  425. $this->log($sErrorType . ': ' . $aError['message']);
  426. return;
  427. }
  428. if(defined('BX_UPGRADE_DB_FULL_VISUAL_PROCESSING') && BX_UPGRADE_DB_FULL_VISUAL_PROCESSING) {
  429. $sOutput = '<div style="border:2px solid red;padding:4px;width:600px;margin:0px auto;">';
  430. $sOutput .= '<div style="text-align:center;background-color:red;color:white;font-weight:bold;">Error</div>';
  431. $sOutput .= '<div style="text-align:center;">' . $sErrorType . '</div>';
  432. if(defined('BX_UPGRADE_DB_FULL_DEBUG_MODE') && BX_UPGRADE_DB_FULL_DEBUG_MODE)
  433. $sOutput .= $this->errorOutput($aError);
  434. $sOutput .= '</div>';
  435. echo $sOutput;
  436. }
  437. }
  438. public function setTimezone($sTimezone)
  439. {
  440. $oDate = new DateTime('now', new DateTimeZone($sTimezone));
  441. return $this->pdoExec('SET time_zone = "' . $oDate->format('P') . '"') !== false;
  442. }
  443. public function getEncoding()
  444. {
  445. $oStatement = $this->pdoQuery('SELECT @@character_set_database');
  446. if($oStatement !== false)
  447. return $this->getOne($oStatement);
  448. return false;
  449. }
  450. public function setErrorChecking ($b)
  451. {
  452. $this->_bErrorChecking = $b;
  453. }
  454. /**
  455. * It escapes string to pass to mysql query.
  456. * Try to use "prepare" function always (@see BxDolDb::prepare), use "escape" only if "prepare" function is not possible at all.
  457. * Also consider using "implode_escape" function (@see BxDolDb::implode_escape).
  458. *
  459. * @param string $s string to escape
  460. * @return escaped string whcich is ready to pass to SQL query.
  461. */
  462. public function escape($s)
  463. {
  464. try {
  465. $s = self::$_rLink->quote($s);
  466. }
  467. catch (PDOException $oException) {
  468. $oException->errorInfo[self::$_sErrorKey] = array(
  469. 'code' => BX_UPGRADE_DB_ERR_ESCAPE,
  470. 'message' => $oException->getMessage(),
  471. 'trace' => $oException->getTrace()
  472. );
  473. throw $oException;
  474. }
  475. return $s;
  476. }
  477. /**
  478. * This function is usefull when you need to form array of parameters to pass to IN(...) SQL construction.
  479. * Example:
  480. * @code
  481. * $a = array(2, 4.5, 'apple', 'car');
  482. * $s = "SELECT * FROM `t` WHERE `a` IN (" . $oDb->implode_escape($a) . ")";
  483. * echo $s; // outputs: SELECT * FROM `t` WHERE `a` IN (2, 4.5, 'apple', 'car')
  484. * @endcode
  485. *
  486. * @param $mixed array or parameters or just one paramter
  487. * @return string which is ready to pass to IN(...) SQL construction
  488. */
  489. public function implode_escape ($mixed)
  490. {
  491. if (is_array($mixed)) {
  492. $s = '';
  493. foreach ($mixed as $v)
  494. $s .= (is_numeric($v) ? $v : $this->escape($v)) . ',';
  495. if ($s)
  496. return substr($s, 0, -1);
  497. else
  498. return 'NULL';
  499. }
  500. return is_numeric($mixed) ? $mixed : ($mixed ? $this->escape($mixed) : 'NULL');
  501. }
  502. /**
  503. * @deprecated
  504. */
  505. public function unescape ($mixed)
  506. {
  507. if(is_array($mixed)) {
  508. foreach($mixed as $k => $v)
  509. $mixed[$k] = $this->getOne("SELECT '$v'");
  510. return $mixed;
  511. }
  512. else
  513. return $this->getOne("SELECT '$mixed'");
  514. }
  515. /**
  516. * Prepare SQL query before execution if some arguments are need to be passed to it.
  517. * All parameters marked with question (?) symbol in SQL query are replaced with parameters passed after SQL query parameter.
  518. * Parameters are properly excaped and surrounded by qutes if needed.
  519. * Example:
  520. * @code
  521. * $sSql = $oDb->prepare("SELECT `a`, `b` from `t` WHERE `c` = ? and `d` = ?", 12, 'aa');
  522. * echo $sSql;// outputs: SELECT `a`, `b` from `t` WHERE `c` = 12 and `d` = 'aa'
  523. * $a = $oDb->getAll($sSql);
  524. * @endcode
  525. *
  526. * @param string $sQuery SQL query, parameters for replacing are marked with ? symbol
  527. * @param mixed $mixed any number if parameters to replace, number of parameters whould match number of ? symbols in SQL query
  528. * @return PDOStatement object with SQL query ready for execution
  529. */
  530. public function prepare($sQuery)
  531. {
  532. if(!self::$_rLink)
  533. return false;
  534. $aArgs = func_get_args();
  535. $sQuery = array_shift($aArgs);
  536. $oStatement = self::$_rLink->prepare($sQuery);
  537. $iIndex = 1;
  538. foreach($aArgs as $mixedArg) {
  539. if(is_null($mixedArg))
  540. $iValueType = PDO::PARAM_NULL;
  541. else if(is_numeric($mixedArg))
  542. $iValueType = PDO::PARAM_INT;
  543. else
  544. $iValueType = PDO::PARAM_STR;
  545. $oStatement->bindValue($iIndex++, $mixedArg, $iValueType);
  546. }
  547. return $oStatement;
  548. }
  549. /**
  550. * Prepare SQL query before execution if some arguments are need to be passed to it.
  551. * All parameters marked with question (?) symbol in SQL query are replaced with parameters passed after SQL query parameter.
  552. * Parameters are properly excaped and surrounded by qutes if needed.
  553. * Example:
  554. * @code
  555. * $sSql = $oDb->prepare("SELECT `a`, `b` from `t` WHERE `c` = ? and `d` = ?", 12, 'aa');
  556. * echo $sSql;// outputs: SELECT `a`, `b` from `t` WHERE `c` = 12 and `d` = 'aa'
  557. * $a = $oDb->getAll($sSql);
  558. * @endcode
  559. *
  560. * @param string $sQuery SQL query, parameters for replacing are marked with ? symbol
  561. * @param mixed $mixed any number if parameters to replace, number of parameters whould match number of ? symbols in SQL query
  562. * @return string with SQL query.
  563. */
  564. function prepareAsString($sQuery)
  565. {
  566. $aArgs = func_get_args();
  567. $sQuery = array_shift($aArgs);
  568. $iPos = 0;
  569. foreach ($aArgs as $mixedArg) {
  570. if (is_null($mixedArg))
  571. $s = 'NULL';
  572. elseif (is_numeric($mixedArg))
  573. $s = $mixedArg;
  574. else
  575. $s = $this->escape($mixedArg);
  576. $i = bx_mb_strpos($sQuery, '?', $iPos);
  577. $sQuery = bx_mb_substr_replace($sQuery, $s, $i, 1);
  578. $iPos = $i + get_mb_len($s);
  579. }
  580. return $sQuery;
  581. }
  582. /**
  583. * Convert array of key => values to SQL query.
  584. * Array keys are field names and array values are field values.
  585. * @param $a array
  586. * @param $sDiv fields separator, by default it is ',', another useful value is ' AND '
  587. * @return part of SQL query string
  588. */
  589. public function arrayToSQL($a, $sDiv = ',')
  590. {
  591. $s = '';
  592. foreach($a as $k => $v)
  593. $s .= "`{$k}` = " . $this->escape($v) . $sDiv;
  594. return trim($s, $sDiv);
  595. }
  596. public function getCache ($sName, $sFunc)
  597. {
  598. return false;
  599. }
  600. protected function log($s)
  601. {
  602. if (defined('BX_DIRECTORY_PATH_LOGS')) {
  603. $sPath = BX_DIRECTORY_PATH_LOGS;
  604. }
  605. else {
  606. $sDirName = pathinfo(__FILE__, PATHINFO_DIRNAME);
  607. $sPath = $sDirName . '/../../logs/';
  608. }
  609. return file_put_contents($sPath . 'db.err.log', date('Y-m-d H:i:s') . "\t" . $s . "\n", FILE_APPEND);
  610. }
  611. public function executeSQL($sPath, $aReplace = array (), $isBreakOnError = true)
  612. {
  613. if(!file_exists($sPath) || !($rHandler = fopen($sPath, "r")))
  614. return array(array ('query' => "fopen($sPath, 'r')", 'error' => 'file not found or permission denied'));
  615. self::$_rLink->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
  616. $sQuery = "";
  617. $sDelimiter = ';';
  618. $aResult = array();
  619. while(!feof($rHandler)) {
  620. $sStr = trim(fgets($rHandler));
  621. if(empty($sStr) || $sStr[0] == "" || $sStr[0] == "#" || ($sStr[0] == "-" && $sStr[1] == "-"))
  622. continue;
  623. //--- Change delimiter ---//
  624. if(strpos($sStr, "DELIMITER //") !== false || strpos($sStr, "DELIMITER ;") !== false) {
  625. $sDelimiter = trim(str_replace('DELIMITER', '', $sStr));
  626. continue;
  627. }
  628. $sQuery .= $sStr;
  629. //--- Check for multiline query ---//
  630. if(substr($sStr, -strlen($sDelimiter)) != $sDelimiter)
  631. continue;
  632. //--- Execute query ---//
  633. if ($aReplace)
  634. $sQuery = str_replace($aReplace['from'], $aReplace['to'], $sQuery);
  635. if($sDelimiter != ';')
  636. $sQuery = str_replace($sDelimiter, "", $sQuery);
  637. if($this->query(trim($sQuery), array(), false) === false) {
  638. $aResult[] = array('query' => $sQuery, 'error' => $this->_aError['message']);
  639. if ($isBreakOnError)
  640. break;
  641. }
  642. $sQuery = "";
  643. }
  644. fclose($rHandler);
  645. self::$_rLink->setAttribute(PDO::ATTR_ERRMODE, $this->_iPdoErrorMode);
  646. return empty($aResult) ? true : $aResult;
  647. }
  648. protected function executeStatement($oStatement, $aBindings = array(), $bVerbose = null)
  649. {
  650. $bResult = false;
  651. switch (self::$_rLink->getAttribute(PDO::ATTR_ERRMODE)) {
  652. case PDO::ERRMODE_SILENT:
  653. $bResult = $this->executeStatementSilent($oStatement, $aBindings, $bVerbose);
  654. break;
  655. case PDO::ERRMODE_EXCEPTION:
  656. $bResult = $this->executeStatementException($oStatement, $aBindings, $bVerbose);
  657. break;
  658. }
  659. return $bResult;
  660. }
  661. protected function executeStatementException($oStatement, $aBindings = array(), $bVerbose = null)
  662. {
  663. $bResult = false;
  664. try {
  665. $bResult = $oStatement->execute(!empty($aBindings) && is_array($aBindings) ? $aBindings : null);
  666. }
  667. catch (PDOException $oException) {
  668. $aError = $oStatement->errorInfo();
  669. $oException->errorInfo[self::$_sErrorKey] = array(
  670. 'code' => BX_UPGRADE_DB_ERR_QUERY_ERROR,
  671. 'message' => !empty($aError[2]) ? $aError[2] : $oException->getMessage(),
  672. 'query' => $oStatement->queryString,
  673. 'trace' => $oException->getTrace(),
  674. 'verbose' => $bVerbose
  675. );
  676. throw $oException;
  677. }
  678. return $bResult;
  679. }
  680. protected function executeStatementSilent($oStatement, $aBindings = array(), $bVerbose = null)
  681. {
  682. $bResult = $oStatement->execute(!empty($aBindings) && is_array($aBindings) ? $aBindings : null);
  683. if($bResult)
  684. return true;
  685. $aError = $oStatement->errorInfo();
  686. $aTrace = debug_backtrace();
  687. unset($aTrace[0]);
  688. $this->_aError = array(
  689. 'code' => BX_UPGRADE_DB_ERR_QUERY_ERROR,
  690. 'message' => !empty($aError[2]) ? $aError[2] : '',
  691. 'query' => $oStatement->queryString,
  692. 'trace' => $aTrace,
  693. 'verbose' => $bVerbose
  694. );
  695. return false;
  696. }
  697. protected function errorOutput($aError)
  698. {
  699. $aErrorLocation = array();
  700. if(!empty($aError['query']) && !empty($aError['trace']))
  701. foreach($aError['trace'] as $aCall )
  702. if(isset($aCall['args']) && is_array($aCall['args']))
  703. foreach($aCall['args'] as $argNum => $argVal)
  704. if((is_string($argVal) && strcmp($argVal, $aError['query']) == 0) || ($argVal instanceof PDOStatement && strcmp($argVal->queryString, $aError['query']) == 0)) {
  705. $aErrorLocation['file'] = isset($aCall['file']) ? $aCall['file'] : (isset($aCall['class']) ? 'class: ' . $aCall['class'] : 'undefined');
  706. $aErrorLocation['line'] = isset($aCall['line']) ? $aCall['line'] : 'undefined';
  707. $aErrorLocation['function'] = $aCall['function'];
  708. $aErrorLocation['arg'] = $argNum;
  709. }
  710. $sOutput = '';
  711. if(!empty($aError['query']))
  712. $sOutput .= '<p><b>Query:</b><br />' . $aError['query'] . '</p>';
  713. if(!empty($aError['message']))
  714. $sOutput .= '<p><b>Mysql error:</b><br />' . $aError['message'] . '</p>';
  715. if(!empty($aErrorLocation))
  716. $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>';
  717. if(!empty($aError['trace'])) {
  718. $sBackTrace = print_r($aError['trace'], true);
  719. $sBackTrace = str_replace('[_sUser:protected] => ' . BX_DATABASE_USER, '[_sUser:protected] => *****', $sBackTrace);
  720. $sBackTrace = str_replace('[_sPassword:protected] => ' . BX_DATABASE_PASS, '[_sPassword:protected] => *****', $sBackTrace);
  721. $sOutput .= '<div><b>Debug backtrace:</b></div><div style="overflow:scroll;height:300px;border:1px solid gray;"><pre>' . htmlspecialchars_adv($sBackTrace) . '</pre></div>';
  722. }
  723. if(!empty(self::$_aParams)) {
  724. $sSettings = var_export(self::$_aParams, true);
  725. $sOutput .= '<div><b>Settings:</b></div><div style="overflow:scroll;height:300px;border:1px solid gray;"><pre>' . htmlspecialchars_adv($sSettings) . '</pre></div>';
  726. }
  727. $sOutput .= '<p><b>Called script:</b><br />' . $_SERVER['PHP_SELF'] . '</p>';
  728. if(!empty($_REQUEST)) {
  729. $sRequest = var_export($_REQUEST, true);
  730. $sOutput .= '<p><b>Request parameters:</b><br /><pre>' . htmlspecialchars_adv($sRequest) . '</pre></p>';
  731. }
  732. return $sOutput;
  733. }
  734. }
  735. /** @} */