BxDolUpgradeDb.php 27 KB

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