PageRenderTime 54ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/manager/includes/extenders/dbapi.mysql.class.inc.php

https://github.com/good-web-master/modx.evo.custom
PHP | 504 lines | 332 code | 32 blank | 140 comment | 66 complexity | 71cfb5d81cb8e7901634c36616aac11d MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-1.0, GPL-2.0, MIT, BSD-3-Clause
  1. <?php
  2. /* Datbase API object of MySQL
  3. * Written by Raymond Irving June, 2005
  4. *
  5. */
  6. class DBAPI {
  7. var $conn;
  8. var $config;
  9. var $isConnected;
  10. /**
  11. * @name: DBAPI
  12. *
  13. */
  14. function DBAPI($host='',$dbase='', $uid='',$pwd='',$pre=NULL,$charset='',$connection_method='SET CHARACTER SET') {
  15. $this->config['host'] = $host ? $host : $GLOBALS['database_server'];
  16. $this->config['dbase'] = $dbase ? $dbase : $GLOBALS['dbase'];
  17. $this->config['user'] = $uid ? $uid : $GLOBALS['database_user'];
  18. $this->config['pass'] = $pwd ? $pwd : $GLOBALS['database_password'];
  19. $this->config['charset'] = $charset ? $charset : $GLOBALS['database_connection_charset'];
  20. $this->config['connection_method'] = $this->_dbconnectionmethod = (isset($GLOBALS['database_connection_method']) ? $GLOBALS['database_connection_method'] : $connection_method);
  21. $this->config['table_prefix'] = ($pre !== NULL) ? $pre : $GLOBALS['table_prefix'];
  22. $this->initDataTypes();
  23. }
  24. /**
  25. * @name: initDataTypes
  26. * @desc: called in the constructor to set up arrays containing the types
  27. * of database fields that can be used with specific PHP types
  28. */
  29. function initDataTypes() {
  30. $this->dataTypes['numeric'] = array (
  31. 'INT',
  32. 'INTEGER',
  33. 'TINYINT',
  34. 'BOOLEAN',
  35. 'DECIMAL',
  36. 'DEC',
  37. 'NUMERIC',
  38. 'FLOAT',
  39. 'DOUBLE PRECISION',
  40. 'REAL',
  41. 'SMALLINT',
  42. 'MEDIUMINT',
  43. 'BIGINT',
  44. 'BIT'
  45. );
  46. $this->dataTypes['string'] = array (
  47. 'CHAR',
  48. 'VARCHAR',
  49. 'BINARY',
  50. 'VARBINARY',
  51. 'TINYBLOB',
  52. 'BLOB',
  53. 'MEDIUMBLOB',
  54. 'LONGBLOB',
  55. 'TINYTEXT',
  56. 'TEXT',
  57. 'MEDIUMTEXT',
  58. 'LONGTEXT',
  59. 'ENUM',
  60. 'SET'
  61. );
  62. $this->dataTypes['date'] = array (
  63. 'DATE',
  64. 'DATETIME',
  65. 'TIMESTAMP',
  66. 'TIME',
  67. 'YEAR'
  68. );
  69. }
  70. /**
  71. * @name: connect
  72. *
  73. */
  74. function connect($host = '', $dbase = '', $uid = '', $pwd = '', $persist = 0) {
  75. global $modx;
  76. $uid = $uid ? $uid : $this->config['user'];
  77. $pwd = $pwd ? $pwd : $this->config['pass'];
  78. $host = $host ? $host : $this->config['host'];
  79. $dbase = $dbase ? $dbase : $this->config['dbase'];
  80. $charset = $this->config['charset'];
  81. $connection_method = $this->config['connection_method'];
  82. $tstart = $modx->getMicroTime();
  83. if (!$this->conn = ($persist ? mysql_pconnect($host, $uid, $pwd) : mysql_connect($host, $uid, $pwd, true))) {
  84. $modx->messageQuit("Failed to create the database connection!");
  85. exit;
  86. } else {
  87. $dbase = str_replace('`', '', $dbase); // remove the `` chars
  88. if (!@ mysql_select_db($dbase, $this->conn)) {
  89. $modx->messageQuit("Failed to select the database '" . $dbase . "'!");
  90. exit;
  91. }
  92. @mysql_query("{$connection_method} {$charset}", $this->conn);
  93. $tend = $modx->getMicroTime();
  94. $totaltime = $tend - $tstart;
  95. if ($modx->dumpSQL) {
  96. $modx->queryCode .= "<fieldset style='text-align:left'><legend>Database connection</legend>" . sprintf("Database connection was created in %2.4f s", $totaltime) . "</fieldset><br />";
  97. }
  98. $this->isConnected = true;
  99. // FIXME (Fixed by line below):
  100. // this->queryTime = this->queryTime + $totaltime;
  101. $modx->queryTime += $totaltime;
  102. }
  103. }
  104. /**
  105. * @name: disconnect
  106. *
  107. */
  108. function disconnect() {
  109. @ mysql_close($this->conn);
  110. }
  111. function escape($s) {
  112. if (function_exists('mysql_real_escape_string') && $this->conn) {
  113. $s = mysql_real_escape_string($s, $this->conn);
  114. } else {
  115. $s = mysql_escape_string($s);
  116. }
  117. return $s;
  118. }
  119. /**
  120. * @name: query
  121. * @desc: Mainly for internal use.
  122. * Developers should use select, update, insert, delete where possible
  123. */
  124. function query($sql) {
  125. global $modx;
  126. if (empty ($this->conn) || !is_resource($this->conn)) {
  127. $this->connect();
  128. }
  129. $tstart = $modx->getMicroTime();
  130. if (!$result = @ mysql_query($sql, $this->conn)) {
  131. $modx->messageQuit("Execution of a query to the database failed - " . $this->getLastError(), $sql);
  132. } else {
  133. $tend = $modx->getMicroTime();
  134. $totaltime = $tend - $tstart;
  135. $modx->queryTime = $modx->queryTime + $totaltime;
  136. if ($modx->dumpSQL) {
  137. $modx->queryCode .= "<fieldset style='text-align:left'><legend>Query " . ($this->executedQueries + 1) . " - " . sprintf("%2.4f s", $totaltime) . "</legend>" . $sql . "</fieldset><br />";
  138. }
  139. $modx->executedQueries = $modx->executedQueries + 1;
  140. return $result;
  141. }
  142. }
  143. /**
  144. * @name: delete
  145. *
  146. */
  147. function delete($from,$where='',$fields='') {
  148. if (!$from)
  149. return false;
  150. else {
  151. $table = $from;
  152. $where = ($where != "") ? "WHERE $where" : "";
  153. return $this->query("DELETE $fields FROM $table $where");
  154. }
  155. }
  156. /**
  157. * @name: select
  158. *
  159. */
  160. function select($fields = "*", $from = "", $where = "", $orderby = "", $limit = "") {
  161. if (!$from)
  162. return false;
  163. else {
  164. $table = $from;
  165. $where = ($where != "") ? "WHERE $where" : "";
  166. $orderby = ($orderby != "") ? "ORDER BY $orderby " : "";
  167. $limit = ($limit != "") ? "LIMIT $limit" : "";
  168. return $this->query("SELECT $fields FROM $table $where $orderby $limit");
  169. }
  170. }
  171. /**
  172. * @name: update
  173. *
  174. */
  175. function update($fields, $table, $where = "") {
  176. if (!$table)
  177. return false;
  178. else {
  179. if (!is_array($fields))
  180. $flds = $fields;
  181. else {
  182. $flds = '';
  183. foreach ($fields as $key => $value) {
  184. if (!empty ($flds))
  185. $flds .= ",";
  186. $flds .= $key . "=";
  187. $flds .= "'" . $value . "'";
  188. }
  189. }
  190. $where = ($where != "") ? "WHERE $where" : "";
  191. return $this->query("UPDATE $table SET $flds $where");
  192. }
  193. }
  194. /**
  195. * @name: insert
  196. * @desc: returns either last id inserted or the result from the query
  197. */
  198. function insert($fields, $intotable, $fromfields = "*", $fromtable = "", $where = "", $limit = "") {
  199. if (!$intotable)
  200. return false;
  201. else {
  202. if (!is_array($fields))
  203. $flds = $fields;
  204. else {
  205. $keys = array_keys($fields);
  206. $values = array_values($fields);
  207. $flds = "(" . implode(",", $keys) . ") " .
  208. (!$fromtable && $values ? "VALUES('" . implode("','", $values) . "')" : "");
  209. if ($fromtable) {
  210. $where = ($where != "") ? "WHERE $where" : "";
  211. $limit = ($limit != "") ? "LIMIT $limit" : "";
  212. $sql = "SELECT $fromfields FROM $fromtable $where $limit";
  213. }
  214. }
  215. $rt = $this->query("INSERT INTO $intotable $flds $sql");
  216. $lid = $this->getInsertId();
  217. return $lid ? $lid : $rt;
  218. }
  219. }
  220. /**
  221. * @name: getInsertId
  222. *
  223. */
  224. function getInsertId($conn=NULL) {
  225. if( !is_resource($conn)) $conn =& $this->conn;
  226. return mysql_insert_id($conn);
  227. }
  228. /**
  229. * @name: getAffectedRows
  230. *
  231. */
  232. function getAffectedRows($conn=NULL) {
  233. if (!is_resource($conn)) $conn =& $this->conn;
  234. return mysql_affected_rows($conn);
  235. }
  236. /**
  237. * @name: getLastError
  238. *
  239. */
  240. function getLastError($conn=NULL) {
  241. if (!is_resource($conn)) $conn =& $this->conn;
  242. return mysql_error($conn);
  243. }
  244. /**
  245. * @name: getRecordCount
  246. *
  247. */
  248. function getRecordCount($ds) {
  249. return (is_resource($ds)) ? mysql_num_rows($ds) : 0;
  250. }
  251. /**
  252. * @name: getRow
  253. * @desc: returns an array of column values
  254. * @param: $dsq - dataset
  255. *
  256. */
  257. function getRow($ds, $mode = 'assoc') {
  258. if ($ds) {
  259. if ($mode == 'assoc') {
  260. return mysql_fetch_assoc($ds);
  261. }
  262. elseif ($mode == 'num') {
  263. return mysql_fetch_row($ds);
  264. }
  265. elseif ($mode == 'both') {
  266. return mysql_fetch_array($ds, MYSQL_BOTH);
  267. } else {
  268. global $modx;
  269. $modx->messageQuit("Unknown get type ($mode) specified for fetchRow - must be empty, 'assoc', 'num' or 'both'.");
  270. }
  271. }
  272. }
  273. /**
  274. * @name: getColumn
  275. * @desc: returns an array of the values found on colun $name
  276. * @param: $dsq - dataset or query string
  277. */
  278. function getColumn($name, $dsq) {
  279. if (!is_resource($dsq))
  280. $dsq = $this->query($dsq);
  281. if ($dsq) {
  282. $col = array ();
  283. while ($row = $this->getRow($dsq)) {
  284. $col[] = $row[$name];
  285. }
  286. return $col;
  287. }
  288. }
  289. /**
  290. * @name: getColumnNames
  291. * @desc: returns an array containing the column $name
  292. * @param: $dsq - dataset or query string
  293. */
  294. function getColumnNames($dsq) {
  295. if (!is_resource($dsq))
  296. $dsq = $this->query($dsq);
  297. if ($dsq) {
  298. $names = array ();
  299. $limit = mysql_num_fields($dsq);
  300. for ($i = 0; $i < $limit; $i++) {
  301. $names[] = mysql_field_name($dsq, $i);
  302. }
  303. return $names;
  304. }
  305. }
  306. /**
  307. * @name: getValue
  308. * @desc: returns the value from the first column in the set
  309. * @param: $dsq - dataset or query string
  310. */
  311. function getValue($dsq) {
  312. if (!is_resource($dsq))
  313. $dsq = $this->query($dsq);
  314. if ($dsq) {
  315. $r = $this->getRow($dsq, "num");
  316. return $r[0];
  317. }
  318. }
  319. /**
  320. * @name: getXML
  321. * @desc: returns an XML formay of the dataset $ds
  322. */
  323. function getXML($dsq) {
  324. if (!is_resource($dsq))
  325. $dsq = $this->query($dsq);
  326. $xmldata = "<xml>\r\n<recordset>\r\n";
  327. while ($row = $this->getRow($dsq, "both")) {
  328. $xmldata .= "<item>\r\n";
  329. for ($j = 0; $line = each($row); $j++) {
  330. if ($j % 2) {
  331. $xmldata .= "<$line[0]>$line[1]</$line[0]>\r\n";
  332. }
  333. }
  334. $xmldata .= "</item>\r\n";
  335. }
  336. $xmldata .= "</recordset>\r\n</xml>";
  337. return $xmldata;
  338. }
  339. /**
  340. * @name: getTableMetaData
  341. * @desc: returns an array of MySQL structure detail for each column of a
  342. * table
  343. * @param: $table: the full name of the database table
  344. */
  345. function getTableMetaData($table) {
  346. $metadata = false;
  347. if (!empty ($table)) {
  348. $sql = "SHOW FIELDS FROM $table";
  349. if ($ds = $this->query($sql)) {
  350. while ($row = $this->getRow($ds)) {
  351. $fieldName = $row['Field'];
  352. $metadata[$fieldName] = $row;
  353. }
  354. }
  355. }
  356. return $metadata;
  357. }
  358. /**
  359. * @name: prepareDate
  360. * @desc: prepares a date in the proper format for specific database types
  361. * given a UNIX timestamp
  362. * @param: $timestamp: a UNIX timestamp
  363. * @param: $fieldType: the type of field to format the date for
  364. * (in MySQL, you have DATE, TIME, YEAR, and DATETIME)
  365. */
  366. function prepareDate($timestamp, $fieldType = 'DATETIME') {
  367. $date = '';
  368. if (!$timestamp === false && $timestamp > 0) {
  369. switch ($fieldType) {
  370. case 'DATE' :
  371. $date = date('Y-m-d', $timestamp);
  372. break;
  373. case 'TIME' :
  374. $date = date('H:i:s', $timestamp);
  375. break;
  376. case 'YEAR' :
  377. $date = date('Y', $timestamp);
  378. break;
  379. default :
  380. $date = date('Y-m-d H:i:s', $timestamp);
  381. break;
  382. }
  383. }
  384. return $date;
  385. }
  386. /**
  387. * @name: getHTMLGrid
  388. * @param: $params: Data grid parameters
  389. * columnHeaderClass
  390. * tableClass
  391. * itemClass
  392. * altItemClass
  393. * columnHeaderStyle
  394. * tableStyle
  395. * itemStyle
  396. * altItemStyle
  397. * columns
  398. * fields
  399. * colWidths
  400. * colAligns
  401. * colColors
  402. * colTypes
  403. * cellPadding
  404. * cellSpacing
  405. * header
  406. * footer
  407. * pageSize
  408. * pagerLocation
  409. * pagerClass
  410. * pagerStyle
  411. *
  412. */
  413. function getHTMLGrid($dsq, $params) {
  414. global $base_path;
  415. if (!is_resource($dsq))
  416. $dsq = $this->query($dsq);
  417. if ($dsq) {
  418. include_once MODX_BASE_PATH . '/manager/includes/controls/datagrid.class.php';
  419. $grd = new DataGrid('', $dsq);
  420. $grd->noRecordMsg = $params['noRecordMsg'];
  421. $grd->columnHeaderClass = $params['columnHeaderClass'];
  422. $grd->cssClass = $params['cssClass'];
  423. $grd->itemClass = $params['itemClass'];
  424. $grd->altItemClass = $params['altItemClass'];
  425. $grd->columnHeaderStyle = $params['columnHeaderStyle'];
  426. $grd->cssStyle = $params['cssStyle'];
  427. $grd->itemStyle = $params['itemStyle'];
  428. $grd->altItemStyle = $params['altItemStyle'];
  429. $grd->columns = $params['columns'];
  430. $grd->fields = $params['fields'];
  431. $grd->colWidths = $params['colWidths'];
  432. $grd->colAligns = $params['colAligns'];
  433. $grd->colColors = $params['colColors'];
  434. $grd->colTypes = $params['colTypes'];
  435. $grd->colWraps = $params['colWraps'];
  436. $grd->cellPadding = $params['cellPadding'];
  437. $grd->cellSpacing = $params['cellSpacing'];
  438. $grd->header = $params['header'];
  439. $grd->footer = $params['footer'];
  440. $grd->pageSize = $params['pageSize'];
  441. $grd->pagerLocation = $params['pagerLocation'];
  442. $grd->pagerClass = $params['pagerClass'];
  443. $grd->pagerStyle = $params['pagerStyle'];
  444. return $grd->render();
  445. }
  446. }
  447. /**
  448. * @name: makeArray
  449. * @desc: turns a recordset into a multidimensional array
  450. * @return: an array of row arrays from recordset, or empty array
  451. * if the recordset was empty, returns false if no recordset
  452. * was passed
  453. * @param: $rs Recordset to be packaged into an array
  454. */
  455. function makeArray($rs=''){
  456. if(!$rs) return false;
  457. $rsArray = array();
  458. $qty = $this->getRecordCount($rs);
  459. for ($i = 0; $i < $qty; $i++) $rsArray[] = $this->getRow($rs);
  460. return $rsArray;
  461. }
  462. /**
  463. * @name getVersion
  464. * @desc returns a string containing the database server version
  465. *
  466. * @return string
  467. */
  468. function getVersion() {
  469. return mysql_get_server_info();
  470. }
  471. }
  472. ?>