BxDolUpgradeDb.php 27 KB

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