PageRenderTime 69ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/typo3/sysext/dbal/class.ux_t3lib_db.php

https://bitbucket.org/linxpinx/mercurial
PHP | 3373 lines | 2068 code | 383 blank | 922 comment | 472 complexity | 5d57942da2ed45977e109034af05d4eb MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Unlicense, LGPL-2.1, Apache-2.0
  1. <?php
  2. /***************************************************************
  3. * Copyright notice
  4. *
  5. * (c) 2004-2010 Kasper Skaarhoj (kasperYYYY@typo3.com)
  6. * (c) 2004-2010 Karsten Dambekalns <karsten@typo3.org>
  7. * (c) 2009-2010 Xavier Perseguers <typo3@perseguers.ch>
  8. * All rights reserved
  9. *
  10. * This script is part of the TYPO3 project. The TYPO3 project is
  11. * free software; you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License as published by
  13. * the Free Software Foundation; either version 2 of the License, or
  14. * (at your option) any later version.
  15. *
  16. * The GNU General Public License can be found at
  17. * http://www.gnu.org/copyleft/gpl.html.
  18. * A copy is found in the textfile GPL.txt and important notices to the license
  19. * from the author is found in LICENSE.txt distributed with these scripts.
  20. *
  21. *
  22. * This script is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. *
  27. * This copyright notice MUST APPEAR in all copies of the script!
  28. ***************************************************************/
  29. /**
  30. * Contains a database abstraction layer class for TYPO3
  31. *
  32. * $Id: class.ux_t3lib_db.php 29977 2010-02-13 13:18:32Z xperseguers $
  33. *
  34. * @author Kasper Skaarhoj <kasper@typo3.com>
  35. * @author Karsten Dambekalns <k.dambekalns@fishfarm.de>
  36. * @author Xavier Perseguers <typo3@perseguers.ch>
  37. */
  38. /**
  39. * [CLASS/FUNCTION INDEX of SCRIPT]
  40. *
  41. *
  42. *
  43. * 123: class ux_t3lib_DB extends t3lib_DB
  44. * 169: function ux_t3lib_DB()
  45. * 184: function initInternalVariables()
  46. *
  47. * SECTION: Query Building (Overriding parent methods)
  48. * 217: function exec_INSERTquery($table,$fields_values)
  49. * 275: function exec_UPDATEquery($table,$where,$fields_values)
  50. * 334: function exec_DELETEquery($table,$where)
  51. * 387: function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy = '',$orderBy = '',$limit = '')
  52. *
  53. * SECTION: Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
  54. * 533: function SELECTquery($select_fields,$from_table,$where_clause,$groupBy = '',$orderBy = '',$limit = '')
  55. * 556: function quoteSelectFields(&$select_fields)
  56. * 573: function quoteFromTables(&$from_table)
  57. * 595: function quoteWhereClause(&$where_clause)
  58. * 620: function quoteGroupBy(&$groupBy)
  59. * 637: function quoteOrderBy(&$orderBy)
  60. *
  61. * SECTION: Various helper functions
  62. * 663: function quoteStr($str, $table)
  63. *
  64. * SECTION: SQL wrapper functions (Overriding parent methods)
  65. * 707: function sql_error()
  66. * 734: function sql_num_rows(&$res)
  67. * 760: function sql_fetch_assoc(&$res)
  68. * 808: function sql_fetch_row(&$res)
  69. * 842: function sql_free_result(&$res)
  70. * 868: function sql_insert_id()
  71. * 893: function sql_affected_rows()
  72. * 919: function sql_data_seek(&$res,$seek)
  73. * 946: function sql_field_type(&$res,$pointer)
  74. *
  75. * SECTION: Legacy functions, bound to _DEFAULT handler. (Overriding parent methods)
  76. * 987: function sql($db,$query)
  77. * 999: function sql_query($query)
  78. * 1035: function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password)
  79. * 1055: function sql_select_db($TYPO3_db)
  80. *
  81. * SECTION: SQL admin functions
  82. * 1086: function admin_get_tables()
  83. * 1149: function admin_get_fields($tableName)
  84. * 1210: function admin_get_keys($tableName)
  85. * 1270: function admin_query($query)
  86. *
  87. * SECTION: Handler management
  88. * 1333: function handler_getFromTableList($tableList)
  89. * 1379: function handler_init($handlerKey)
  90. *
  91. * SECTION: Table/Field mapping
  92. * 1488: function map_needMapping($tableList,$fieldMappingOnly = FALSE)
  93. * 1524: function map_assocArray($input,$tables,$rev = FALSE)
  94. * 1573: function map_remapSELECTQueryParts(&$select_fields,&$from_table,&$where_clause,&$groupBy,&$orderBy)
  95. * 1615: function map_sqlParts(&$sqlPartArray, $defaultTable)
  96. * 1650: function map_genericQueryParsed(&$parsedQuery)
  97. * 1717: function map_fieldNamesInArray($table,&$fieldArray)
  98. *
  99. * SECTION: Debugging
  100. * 1758: function debugHandler($function,$execTime,$inData)
  101. * 1823: function debug_log($query,$ms,$data,$join,$errorFlag)
  102. * 1849: function debug_explain($query)
  103. *
  104. * TOTAL FUNCTIONS: 41
  105. * (This index is automatically created/updated by the extension "extdeveval")
  106. *
  107. */
  108. /**
  109. * TYPO3 database abstraction layer
  110. *
  111. * @author Kasper Skaarhoj <kasper@typo3.com>
  112. * @author Karsten Dambekalns <k.dambekalns@fishfarm.de>
  113. * @package TYPO3
  114. * @subpackage tx_dbal
  115. */
  116. class ux_t3lib_DB extends t3lib_DB {
  117. // Internal, static:
  118. var $printErrors = FALSE; // Enable output of SQL errors after query executions. Set through TYPO3_CONF_VARS, see init()
  119. var $debug = FALSE; // Enable debug mode. Set through TYPO3_CONF_VARS, see init()
  120. var $conf = array(); // Configuration array, copied from TYPO3_CONF_VARS in constructor.
  121. var $mapping = array(); // See manual.
  122. var $table2handlerKeys = array(); // See manual.
  123. var $handlerCfg = array( // See manual.
  124. '_DEFAULT' => array(
  125. 'type' => 'native',
  126. 'config' => array(
  127. 'username' => '', // Set by default (overridden)
  128. 'password' => '', // Set by default (overridden)
  129. 'host' => '', // Set by default (overridden)
  130. 'database' => '', // Set by default (overridden)
  131. 'driver' => '', // ONLY "adodb" type; eg. "mysql"
  132. 'sequenceStart' => 1, // ONLY "adodb", first number in sequences/serials/...
  133. 'useNameQuote' => 0 // ONLY "adodb", whether to use NameQuote() method from ADOdb to quote names
  134. )
  135. ),
  136. );
  137. // Internal, dynamic:
  138. var $handlerInstance = array(); // Contains instance of the handler objects as they are created. Exception is the native mySQL calls which are registered as an array with keys "handlerType" = "native" and "link" pointing to the link resource for the connection.
  139. var $lastHandlerKey = ''; // Storage of the handler key of last ( SELECT) query - used for subsequent fetch-row calls etc.
  140. var $lastQuery = ''; // Storage of last SELECT query
  141. var $lastParsedAndMappedQueryArray = array(); // Query array, the last one parsed
  142. var $resourceIdToTableNameMap = array(); // Mapping of resource ids to table names.
  143. // Internal, caching:
  144. var $cache_handlerKeyFromTableList = array(); // Caching handlerKeys for table lists
  145. var $cache_mappingFromTableList = array(); // Caching mapping information for table lists
  146. var $cache_autoIncFields = array(); // parsed SQL from standard DB dump file
  147. var $cache_fieldType = array(); // field types for tables/fields
  148. var $cache_primaryKeys = array(); // primary keys
  149. /**
  150. * SQL parser
  151. *
  152. * @var tx_dbal_sqlengine
  153. */
  154. var $SQLparser;
  155. /**
  156. * Installer
  157. *
  158. * @var t3lib_install
  159. */
  160. var $Installer;
  161. /**
  162. * Constructor.
  163. * Creates SQL parser object and imports configuration from $TYPO3_CONF_VARS['EXTCONF']['dbal']
  164. */
  165. public function __construct() {
  166. // Set SQL parser object for internal use:
  167. $this->SQLparser = t3lib_div::makeInstance('tx_dbal_sqlengine');
  168. $this->Installer = t3lib_div::makeInstance('t3lib_install');
  169. // Set internal variables with configuration:
  170. $this->conf = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal'];
  171. $this->initInternalVariables();
  172. }
  173. /**
  174. * Setting internal variables from $this->conf.
  175. *
  176. * @return void
  177. */
  178. protected function initInternalVariables() {
  179. // Set outside configuration:
  180. if (isset($this->conf['mapping'])) {
  181. $this->mapping = $this->conf['mapping'];
  182. }
  183. if (isset($this->conf['table2handlerKeys'])) {
  184. $this->table2handlerKeys = $this->conf['table2handlerKeys'];
  185. }
  186. if (isset($this->conf['handlerCfg'])) {
  187. $this->handlerCfg = $this->conf['handlerCfg'];
  188. }
  189. $this->cacheFieldInfo();
  190. // Debugging settings:
  191. $this->printErrors = $this->conf['debugOptions']['printErrors'] ? TRUE : FALSE;
  192. $this->debug = $this->conf['debugOptions']['enabled'] ? TRUE : FALSE;
  193. }
  194. /**
  195. * Clears the cached field information file.
  196. *
  197. * @return void
  198. */
  199. public function clearCachedFieldInfo() {
  200. if (file_exists(PATH_typo3conf . 'temp_fieldInfo.php')) {
  201. unlink(PATH_typo3conf . 'temp_fieldInfo.php');
  202. }
  203. }
  204. /**
  205. * Caches the field information.
  206. *
  207. * @return void
  208. */
  209. public function cacheFieldInfo() {
  210. $extSQL = '';
  211. $parsedExtSQL = array();
  212. // try to fetch cached file first
  213. // file is removed when admin_query() is called
  214. if (file_exists(PATH_typo3conf . 'temp_fieldInfo.php')) {
  215. $fdata = unserialize(t3lib_div::getUrl(PATH_typo3conf . 'temp_fieldInfo.php'));
  216. $this->cache_autoIncFields = $fdata['incFields'];
  217. $this->cache_fieldType = $fdata['fieldTypes'];
  218. $this->cache_primaryKeys = $fdata['primaryKeys'];
  219. } else {
  220. // handle stddb.sql, parse and analyze
  221. $extSQL = t3lib_div::getUrl(PATH_site . 't3lib/stddb/tables.sql');
  222. $parsedExtSQL = $this->Installer->getFieldDefinitions_fileContent($extSQL);
  223. $this->analyzeFields($parsedExtSQL);
  224. // loop over all installed extensions
  225. foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $ext => $v) {
  226. if (!is_array($v) || !isset($v['ext_tables.sql'])) {
  227. continue;
  228. }
  229. // fetch db dump (if any) and parse it, then analyze
  230. $extSQL = t3lib_div::getUrl($v['ext_tables.sql']);
  231. $parsedExtSQL = $this->Installer->getFieldDefinitions_fileContent($extSQL);
  232. $this->analyzeFields($parsedExtSQL);
  233. }
  234. $cachedFieldInfo = array('incFields' => $this->cache_autoIncFields, 'fieldTypes' => $this->cache_fieldType, 'primaryKeys' => $this->cache_primaryKeys);
  235. $cachedFieldInfo = serialize($this->mapCachedFieldInfo($cachedFieldInfo));
  236. // write serialized content to file
  237. t3lib_div::writeFile(PATH_typo3conf . 'temp_fieldInfo.php', $cachedFieldInfo);
  238. if (strcmp(t3lib_div::getUrl(PATH_typo3conf . 'temp_fieldInfo.php'), $cachedFieldInfo)) {
  239. die('typo3temp/temp_incfields.php was NOT updated properly (written content didn\'t match file content) - maybe write access problem?');
  240. }
  241. }
  242. }
  243. /**
  244. * Analyzes fields and adds the extracted information to the field type, auto increment and primary key info caches.
  245. *
  246. * @param array $parsedExtSQL The output produced by t3lib_install::getFieldDefinitions_fileContent()
  247. * @return void
  248. * @see t3lib_install::getFieldDefinitions_fileContent()
  249. */
  250. protected function analyzeFields($parsedExtSQL) {
  251. foreach ($parsedExtSQL as $table => $tdef) {
  252. if (is_array($tdef['fields'])) {
  253. foreach ($tdef['fields'] as $field => $fdef) {
  254. $fdef = $this->SQLparser->parseFieldDef($fdef);
  255. $this->cache_fieldType[$table][$field]['type'] = $fdef['fieldType'];
  256. $this->cache_fieldType[$table][$field]['metaType'] = $this->MySQLMetaType($fdef['fieldType']);
  257. $this->cache_fieldType[$table][$field]['notnull'] = (isset($fdef['featureIndex']['NOTNULL']) && !$this->SQLparser->checkEmptyDefaultValue($fdef['featureIndex'])) ? 1 : 0;
  258. if (isset($fdef['featureIndex']['DEFAULT'])) {
  259. $default = $fdef['featureIndex']['DEFAULT']['value'][0];
  260. if (isset($fdef['featureIndex']['DEFAULT']['value'][1])) {
  261. $default = $fdef['featureIndex']['DEFAULT']['value'][1] . $default . $fdef['featureIndex']['DEFAULT']['value'][1];
  262. }
  263. $this->cache_fieldType[$table][$field]['default'] = $default;
  264. }
  265. if (isset($fdef['featureIndex']['AUTO_INCREMENT'])) {
  266. $this->cache_autoIncFields[$table] = $field;
  267. }
  268. if (isset($tdef['keys']['PRIMARY'])) {
  269. $this->cache_primaryKeys[$table] = substr($tdef['keys']['PRIMARY'], 13, -1);
  270. }
  271. }
  272. }
  273. }
  274. }
  275. /**
  276. * This function builds all definitions for mapped tables and fields
  277. * @see cacheFieldInfo()
  278. */
  279. protected function mapCachedFieldInfo($fieldInfo) {
  280. if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['mapping'])) {
  281. foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['mapping'] as $mappedTable => $mappedConf) {
  282. if (array_key_exists($mappedTable, $fieldInfo['incFields'])) {
  283. $mappedTableAlias = $mappedConf['mapTableName'];
  284. if (isset($mappedConf['mapFieldNames'][$fieldInfo['incFields'][$mappedTable]])) {
  285. $fieldInfo['incFields'][$mappedTableAlias] = $mappedConf['mapFieldNames'][$fieldInfo['incFields'][$mappedTable]];
  286. } else {
  287. $fieldInfo['incFields'][$mappedTableAlias] = $fieldInfo['incFields'][$mappedTable];
  288. }
  289. }
  290. if (array_key_exists($mappedTable, $fieldInfo['fieldTypes'])) {
  291. foreach ($fieldInfo['fieldTypes'][$mappedTable] as $field => $fieldConf) {
  292. $tempMappedFieldConf[$mappedConf['mapFieldNames'][$field]] = $fieldConf;
  293. }
  294. $fieldInfo['fieldTypes'][$mappedConf['mapTableName']] = $tempMappedFieldConf;
  295. }
  296. if (array_key_exists($mappedTable, $fieldInfo['primaryKeys'])) {
  297. $mappedTableAlias = $mappedConf['mapTableName'];
  298. if (isset($mappedConf['mapFieldNames'][$fieldInfo['primaryKeys'][$mappedTable]])) {
  299. $fieldInfo['primaryKeys'][$mappedTableAlias] = $mappedConf['mapFieldNames'][$fieldInfo['primaryKeys'][$mappedTable]];
  300. } else {
  301. $fieldInfo['primaryKeys'][$mappedTableAlias] = $fieldInfo['primaryKeys'][$mappedTable];
  302. }
  303. }
  304. }
  305. }
  306. return $fieldInfo;
  307. }
  308. /************************************
  309. *
  310. * Query Building (Overriding parent methods)
  311. * These functions are extending counterparts in the parent class.
  312. *
  313. **************************************/
  314. /* From the ADOdb documentation, this is what we do (_Execute for SELECT, _query for the other actions)
  315. Execute() is the default way to run queries. You can use the low-level functions _Execute() and _query() to reduce query overhead.
  316. Both these functions share the same parameters as Execute().
  317. If you do not have any bind parameters or your database supports binding (without emulation), then you can call _Execute() directly.
  318. Calling this function bypasses bind emulation. Debugging is still supported in _Execute().
  319. If you do not require debugging facilities nor emulated binding, and do not require a recordset to be returned, then you can call _query.
  320. This is great for inserts, updates and deletes. Calling this function bypasses emulated binding, debugging, and recordset handling. Either
  321. the resultid, TRUE or FALSE are returned by _query().
  322. */
  323. /**
  324. * Inserts a record for $table from the array with field/value pairs $fields_values.
  325. *
  326. * @param string Table name
  327. * @param array Field values as key=>value pairs. Values will be escaped internally. Typically you would fill an array like "$insertFields" with 'fieldname'=>'value' and pass it to this function as argument.
  328. * @param mixed List/array of keys NOT to quote (eg. SQL functions)
  329. * @return mixed Result from handler, usually TRUE when success and FALSE on failure
  330. */
  331. public function exec_INSERTquery($table, $fields_values, $no_quote_fields = '') {
  332. if ($this->debug) {
  333. $pt = t3lib_div::milliseconds();
  334. }
  335. // Do field mapping if needed:
  336. $ORIG_tableName = $table;
  337. if ($tableArray = $this->map_needMapping($table)) {
  338. // Field mapping of array:
  339. $fields_values = $this->map_assocArray($fields_values, $tableArray);
  340. // Table name:
  341. if ($this->mapping[$table]['mapTableName']) {
  342. $table = $this->mapping[$table]['mapTableName'];
  343. }
  344. }
  345. // Select API:
  346. $this->lastHandlerKey = $this->handler_getFromTableList($ORIG_tableName);
  347. switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
  348. case 'native':
  349. $this->lastQuery = $this->INSERTquery($table,$fields_values,$no_quote_fields);
  350. if (is_string($this->lastQuery)) {
  351. $sqlResult = mysql_query($this->lastQuery, $this->handlerInstance[$this->lastHandlerKey]['link']);
  352. } else {
  353. $sqlResult = mysql_query($this->lastQuery[0], $this->handlerInstance[$this->lastHandlerKey]['link']);
  354. foreach ($this->lastQuery[1] as $field => $content) {
  355. mysql_query('UPDATE ' . $this->quoteFromTables($table) . ' SET ' . $this->quoteFromTables($field) . '=' . $this->fullQuoteStr($content, $table) . ' WHERE ' . $this->quoteWhereClause($where), $this->handlerInstance[$this->lastHandlerKey]['link']);
  356. }
  357. }
  358. break;
  359. case 'adodb':
  360. // auto generate ID for auto_increment fields if not present (static import needs this!)
  361. // should we check the table name here (static_*)?
  362. if (isset($this->cache_autoIncFields[$table])) {
  363. if (isset($fields_values[$this->cache_autoIncFields[$table]])) {
  364. $new_id = $fields_values[$this->cache_autoIncFields[$table]];
  365. if ($table != 'tx_dbal_debuglog') {
  366. $this->handlerInstance[$this->lastHandlerKey]->last_insert_id = $new_id;
  367. }
  368. } else {
  369. $new_id = $this->handlerInstance[$this->lastHandlerKey]->GenID($table.'_'.$this->cache_autoIncFields[$table], $this->handlerInstance[$this->lastHandlerKey]->sequenceStart);
  370. $fields_values[$this->cache_autoIncFields[$table]] = $new_id;
  371. if ($table != 'tx_dbal_debuglog') {
  372. $this->handlerInstance[$this->lastHandlerKey]->last_insert_id = $new_id;
  373. }
  374. }
  375. }
  376. $this->lastQuery = $this->INSERTquery($table,$fields_values,$no_quote_fields);
  377. if (is_string($this->lastQuery)) {
  378. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery,FALSE);
  379. } else {
  380. $this->handlerInstance[$this->lastHandlerKey]->StartTrans();
  381. if (strlen($this->lastQuery[0])) {
  382. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery[0],FALSE);
  383. }
  384. if (is_array($this->lastQuery[1])) {
  385. foreach ($this->lastQuery[1] as $field => $content) {
  386. if (empty($content)) continue;
  387. if (isset($this->cache_autoIncFields[$table]) && isset($new_id)) {
  388. $this->handlerInstance[$this->lastHandlerKey]->UpdateBlob($this->quoteFromTables($table),$field,$content,$this->quoteWhereClause($this->cache_autoIncFields[$table].'='.$new_id));
  389. } elseif (isset($this->cache_primaryKeys[$table])) {
  390. $where = '';
  391. $pks = explode(',', $this->cache_primaryKeys[$table]);
  392. foreach ($pks as $pk) {
  393. if (isset($fields_values[$pk]))
  394. $where .= $pk.'='.$this->fullQuoteStr($fields_values[$pk], $table).' AND ';
  395. }
  396. $where = $this->quoteWhereClause($where.'1=1');
  397. $this->handlerInstance[$this->lastHandlerKey]->UpdateBlob($this->quoteFromTables($table),$field,$content,$where);
  398. } else {
  399. $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans(FALSE);
  400. die('Could not update BLOB >>>> no WHERE clause found!'); // should never ever happen
  401. }
  402. }
  403. }
  404. if (is_array($this->lastQuery[2])) {
  405. foreach ($this->lastQuery[2] as $field => $content) {
  406. if (empty($content)) continue;
  407. if (isset($this->cache_autoIncFields[$table]) && isset($new_id)) {
  408. $this->handlerInstance[$this->lastHandlerKey]->UpdateClob($this->quoteFromTables($table),$field,$content,$this->quoteWhereClause($this->cache_autoIncFields[$table].'='.$new_id));
  409. } elseif (isset($this->cache_primaryKeys[$table])) {
  410. $where = '';
  411. $pks = explode(',', $this->cache_primaryKeys[$table]);
  412. foreach ($pks as $pk) {
  413. if (isset($fields_values[$pk]))
  414. $where .= $pk.'='.$this->fullQuoteStr($fields_values[$pk], $table).' AND ';
  415. }
  416. $where = $this->quoteWhereClause($where.'1=1');
  417. $this->handlerInstance[$this->lastHandlerKey]->UpdateClob($this->quoteFromTables($table),$field,$content,$where);
  418. } else {
  419. $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans(FALSE);
  420. die('Could not update CLOB >>>> no WHERE clause found!'); // should never ever happen
  421. }
  422. }
  423. }
  424. $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans();
  425. }
  426. break;
  427. case 'userdefined':
  428. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_INSERTquery($table,$fields_values,$no_quote_fields);
  429. break;
  430. }
  431. if ($this->printErrors && $this->sql_error()) {
  432. debug(array($this->lastQuery, $this->sql_error()));
  433. }
  434. if ($this->debug) {
  435. $this->debugHandler(
  436. 'exec_INSERTquery',
  437. t3lib_div::milliseconds()-$pt,
  438. array(
  439. 'handlerType' => $hType,
  440. 'args' => array($table,$fields_values),
  441. 'ORIG_tablename' => $ORIG_tableName
  442. )
  443. );
  444. }
  445. // Return output:
  446. return $sqlResult;
  447. }
  448. /**
  449. * Creates and executes an INSERT SQL-statement for $table with multiple rows.
  450. * This method uses exec_INSERTquery() and is just a syntax wrapper to it.
  451. *
  452. * @param string Table name
  453. * @param array Field names
  454. * @param array Table rows. Each row should be an array with field values mapping to $fields
  455. * @param string/array See fullQuoteArray()
  456. * @return mixed Result from last handler, usually TRUE when success and FALSE on failure
  457. */
  458. public function exec_INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
  459. if ((string)$this->handlerCfg[$this->lastHandlerKey]['type'] === 'native') {
  460. return parent::exec_INSERTmultipleRows($table, $fields, $rows, $no_quote_fields);
  461. }
  462. foreach ($rows as $row) {
  463. $fields_values = array();
  464. foreach ($fields as $key => $value) {
  465. $fields_values[$value] = $row[$key];
  466. }
  467. $res = $this->exec_INSERTquery($table, $fields_values, $no_quote_fields);
  468. }
  469. return $res;
  470. }
  471. /**
  472. * Updates a record from $table
  473. *
  474. * @param string Database tablename
  475. * @param string WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
  476. * @param array Field values as key=>value pairs. Values will be escaped internally. Typically you would fill an array like "$updateFields" with 'fieldname'=>'value' and pass it to this function as argument.
  477. * @param mixed List/array of keys NOT to quote (eg. SQL functions)
  478. * @return mixed Result from handler, usually TRUE when success and FALSE on failure
  479. */
  480. public function exec_UPDATEquery($table,$where,$fields_values,$no_quote_fields = '') {
  481. if ($this->debug) {
  482. $pt = t3lib_div::milliseconds();
  483. }
  484. // Do table/field mapping:
  485. $ORIG_tableName = $table;
  486. if ($tableArray = $this->map_needMapping($table)) {
  487. // Field mapping of array:
  488. $fields_values = $this->map_assocArray($fields_values,$tableArray);
  489. // Where clause table and field mapping:
  490. $whereParts = $this->SQLparser->parseWhereClause($where);
  491. $this->map_sqlParts($whereParts,$tableArray[0]['table']);
  492. $where = $this->SQLparser->compileWhereClause($whereParts, FALSE);
  493. // Table name:
  494. if ($this->mapping[$table]['mapTableName']) {
  495. $table = $this->mapping[$table]['mapTableName'];
  496. }
  497. }
  498. // Select API
  499. $this->lastHandlerKey = $this->handler_getFromTableList($ORIG_tableName);
  500. switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
  501. case 'native':
  502. $this->lastQuery = $this->UPDATEquery($table,$where,$fields_values,$no_quote_fields);
  503. if (is_string($this->lastQuery)) {
  504. $sqlResult = mysql_query($this->lastQuery, $this->handlerInstance[$this->lastHandlerKey]['link']);
  505. }
  506. else {
  507. $sqlResult = mysql_query($this->lastQuery[0], $this->handlerInstance[$this->lastHandlerKey]['link']);
  508. foreach ($this->lastQuery[1] as $field => $content) {
  509. mysql_query('UPDATE '.$this->quoteFromTables($table).' SET '.$this->quoteFromTables($field).'='.$this->fullQuoteStr($content,$table).' WHERE '.$this->quoteWhereClause($where), $this->handlerInstance[$this->lastHandlerKey]['link']);
  510. }
  511. }
  512. break;
  513. case 'adodb':
  514. $this->lastQuery = $this->UPDATEquery($table,$where,$fields_values,$no_quote_fields);
  515. if (is_string($this->lastQuery)) {
  516. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery,FALSE);
  517. } else {
  518. $this->handlerInstance[$this->lastHandlerKey]->StartTrans();
  519. if (strlen($this->lastQuery[0])) {
  520. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery[0],FALSE);
  521. }
  522. if (is_array($this->lastQuery[1])) {
  523. foreach ($this->lastQuery[1] as $field => $content) {
  524. $this->handlerInstance[$this->lastHandlerKey]->UpdateBlob($this->quoteFromTables($table),$field,$content,$this->quoteWhereClause($where));
  525. }
  526. }
  527. if (is_array($this->lastQuery[2])) {
  528. foreach ($this->lastQuery[2] as $field => $content) {
  529. $this->handlerInstance[$this->lastHandlerKey]->UpdateClob($this->quoteFromTables($table),$field,$content,$this->quoteWhereClause($where));
  530. }
  531. }
  532. $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans();
  533. }
  534. break;
  535. case 'userdefined':
  536. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_UPDATEquery($table,$where,$fields_values,$no_quote_fields);
  537. break;
  538. }
  539. if ($this->printErrors && $this->sql_error()) {
  540. debug(array($this->lastQuery, $this->sql_error()));
  541. }
  542. if ($this->debug) {
  543. $this->debugHandler(
  544. 'exec_UPDATEquery',
  545. t3lib_div::milliseconds()-$pt,
  546. array(
  547. 'handlerType' => $hType,
  548. 'args' => array($table,$where, $fields_values),
  549. 'ORIG_from_table' => $ORIG_tableName
  550. )
  551. );
  552. }
  553. // Return result:
  554. return $sqlResult;
  555. }
  556. /**
  557. * Deletes records from table
  558. *
  559. * @param string Database tablename
  560. * @param string WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
  561. * @return mixed Result from handler
  562. */
  563. public function exec_DELETEquery($table, $where) {
  564. if ($this->debug) {
  565. $pt = t3lib_div::milliseconds();
  566. }
  567. // Do table/field mapping:
  568. $ORIG_tableName = $table;
  569. if ($tableArray = $this->map_needMapping($table)) {
  570. // Where clause:
  571. $whereParts = $this->SQLparser->parseWhereClause($where);
  572. $this->map_sqlParts($whereParts,$tableArray[0]['table']);
  573. $where = $this->SQLparser->compileWhereClause($whereParts, FALSE);
  574. // Table name:
  575. if ($this->mapping[$table]['mapTableName']) {
  576. $table = $this->mapping[$table]['mapTableName'];
  577. }
  578. }
  579. // Select API
  580. $this->lastHandlerKey = $this->handler_getFromTableList($ORIG_tableName);
  581. switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
  582. case 'native':
  583. $this->lastQuery = $this->DELETEquery($table,$where);
  584. $sqlResult = mysql_query($this->lastQuery, $this->handlerInstance[$this->lastHandlerKey]['link']);
  585. break;
  586. case 'adodb':
  587. $this->lastQuery = $this->DELETEquery($table,$where);
  588. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery,FALSE);
  589. break;
  590. case 'userdefined':
  591. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_DELETEquery($table,$where);
  592. break;
  593. }
  594. if ($this->printErrors && $this->sql_error()) {
  595. debug(array($this->lastQuery, $this->sql_error()));
  596. }
  597. if ($this->debug) {
  598. $this->debugHandler(
  599. 'exec_DELETEquery',
  600. t3lib_div::milliseconds()-$pt,
  601. array(
  602. 'handlerType' => $hType,
  603. 'args' => array($table,$where),
  604. 'ORIG_from_table' => $ORIG_tableName
  605. )
  606. );
  607. }
  608. // Return result:
  609. return $sqlResult;
  610. }
  611. /**
  612. * Selects records from Data Source
  613. *
  614. * @param string $select_fields List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
  615. * @param string $from_table Table(s) from which to select. This is what comes right after "FROM ...". Required value.
  616. * @param string $where_clause Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQquoteStr() yourself! DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
  617. * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
  618. * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
  619. * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
  620. * @return mixed Result from handler. Typically object from DBAL layers.
  621. */
  622. public function exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
  623. if ($this->debug) {
  624. $pt = t3lib_div::milliseconds();
  625. }
  626. // Map table / field names if needed:
  627. $ORIG_tableName = $from_table; // Saving table names in $ORIG_from_table since $from_table is transformed beneath:
  628. if ($tableArray = $this->map_needMapping($ORIG_tableName)) {
  629. $this->map_remapSELECTQueryParts($select_fields,$from_table,$where_clause,$groupBy,$orderBy); // Variables passed by reference!
  630. }
  631. // Get handler key and select API:
  632. $this->lastHandlerKey = $this->handler_getFromTableList($ORIG_tableName);
  633. $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
  634. switch ($hType) {
  635. case 'native':
  636. $this->lastQuery = $this->SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit);
  637. $sqlResult = mysql_query($this->lastQuery, $this->handlerInstance[$this->lastHandlerKey]['link']);
  638. $this->resourceIdToTableNameMap[(string)$sqlResult] = $ORIG_tableName;
  639. break;
  640. case 'adodb':
  641. if ($limit != '') {
  642. $splitLimit = t3lib_div::intExplode(',', $limit); // Splitting the limit values:
  643. if ($splitLimit[1]) { // If there are two parameters, do mapping differently than otherwise:
  644. $numrows = $splitLimit[1];
  645. $offset = $splitLimit[0];
  646. } else {
  647. $numrows = $splitLimit[0];
  648. $offset = 0;
  649. }
  650. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->SelectLimit($this->SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy), $numrows, $offset);
  651. $this->lastQuery = $sqlResult->sql;
  652. } else {
  653. $this->lastQuery = $this->SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy);
  654. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_Execute($this->lastQuery);
  655. }
  656. $sqlResult->TYPO3_DBAL_handlerType = 'adodb'; // Setting handler type in result object (for later recognition!)
  657. $sqlResult->TYPO3_DBAL_tableList = $ORIG_tableName;
  658. break;
  659. case 'userdefined':
  660. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit);
  661. if (is_object($sqlResult)) {
  662. $sqlResult->TYPO3_DBAL_handlerType = 'userdefined'; // Setting handler type in result object (for later recognition!)
  663. $sqlResult->TYPO3_DBAL_tableList = $ORIG_tableName;
  664. }
  665. break;
  666. }
  667. if ($this->printErrors && $this->sql_error()) {
  668. debug(array($this->lastQuery, $this->sql_error()));
  669. }
  670. if ($this->debug) {
  671. $this->debugHandler(
  672. 'exec_SELECTquery',
  673. t3lib_div::milliseconds()-$pt,
  674. array(
  675. 'handlerType' => $hType,
  676. 'args' => array($from_table,$select_fields,$where_clause,$groupBy,$orderBy,$limit),
  677. 'ORIG_from_table' => $ORIG_tableName
  678. )
  679. );
  680. }
  681. // Return result handler.
  682. return $sqlResult;
  683. }
  684. /**
  685. * Truncates a table.
  686. *
  687. * @param string Database tablename
  688. * @return mixed Result from handler
  689. */
  690. public function exec_TRUNCATEquery($table) {
  691. if ($this->debug) {
  692. $pt = t3lib_div::milliseconds();
  693. }
  694. // Do table/field mapping:
  695. $ORIG_tableName = $table;
  696. if ($tableArray = $this->map_needMapping($table)) {
  697. // Table name:
  698. if ($this->mapping[$table]['mapTableName']) {
  699. $table = $this->mapping[$table]['mapTableName'];
  700. }
  701. }
  702. // Select API
  703. $this->lastHandlerKey = $this->handler_getFromTableList($ORIG_tableName);
  704. switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
  705. case 'native':
  706. $this->lastQuery = $this->TRUNCATEquery($table);
  707. $sqlResult = mysql_query($this->lastQuery, $this->handlerInstance[$this->lastHandlerKey]['link']);
  708. break;
  709. case 'adodb':
  710. $this->lastQuery = $this->TRUNCATEquery($table);
  711. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery, FALSE);
  712. break;
  713. case 'userdefined':
  714. $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_TRUNCATEquery($table,$where);
  715. break;
  716. }
  717. if ($this->printErrors && $this->sql_error()) {
  718. debug(array($this->lastQuery, $this->sql_error()));
  719. }
  720. if ($this->debug) {
  721. $this->debugHandler(
  722. 'exec_TRUNCATEquery',
  723. t3lib_div::milliseconds() - $pt,
  724. array(
  725. 'handlerType' => $hType,
  726. 'args' => array($table),
  727. 'ORIG_from_table' => $ORIG_tableName
  728. )
  729. );
  730. }
  731. // Return result:
  732. return $sqlResult;
  733. }
  734. /**
  735. * Executes a query.
  736. * EXPERIMENTAL since TYPO3 4.4.
  737. *
  738. * @param array $queryParts SQL parsed by method parseSQL() of t3lib_sqlparser
  739. * @return pointer Result pointer / DBAL object
  740. * @see ux_t3lib_db::sql_query()
  741. */
  742. protected function exec_query(array $queryParts) {
  743. switch ($queryParts['type']) {
  744. case 'SELECT':
  745. $selectFields = $this->SQLparser->compileFieldList($queryParts['SELECT']);
  746. $fromTables = $this->SQLparser->compileFromTables($queryParts['FROM']);
  747. $whereClause = isset($queryParts['WHERE']) ? $this->SQLparser->compileWhereClause($queryParts['WHERE']) : '1=1';
  748. $groupBy = isset($queryParts['GROUPBY']) ? $this->SQLparser->compileWhereClause($queryParts['GROUPBY']) : '';
  749. $orderBy = isset($queryParts['GROUPBY']) ? $this->SQLparser->compileWhereClause($queryParts['ORDERBY']) : '';
  750. $limit = isset($queryParts['LIMIT']) ? $this->SQLparser->compileWhereClause($queryParts['LIMIT']) : '';
  751. return $this->exec_SELECTquery($selectFields, $fromTables, $whereClause, $groupBy, $orderBy, $limit);
  752. case 'UPDATE':
  753. $table = $queryParts['TABLE'];
  754. $fields = array();
  755. foreach ($components['FIELDS'] as $fN => $fV) {
  756. $fields[$fN] = $fV[0];
  757. }
  758. $whereClause = isset($queryParts['WHERE']) ? $this->SQLparser->compileWhereClause($queryParts['WHERE']) : '1=1';
  759. return $this->exec_UPDATEquery($table, $whereClause, $fields);
  760. case 'INSERT':
  761. $table = $queryParts['TABLE'];
  762. $values = array();
  763. if (isset($queryParts['VALUES_ONLY']) && is_array($queryParts['VALUES_ONLY'])) {
  764. $fields = $GLOBALS['TYPO3_DB']->cache_fieldType[$table];
  765. $fc = 0;
  766. foreach ($fields as $fn => $fd) {
  767. $values[$fn] = $queryParts['VALUES_ONLY'][$fc++][0];
  768. }
  769. } else {
  770. foreach ($queryParts['FIELDS'] as $fN => $fV) {
  771. $values[$fN] = $fV[0];
  772. }
  773. }
  774. return $this->exec_INSERTquery($table, $values);
  775. case 'DELETE':
  776. $table = $queryParts['TABLE'];
  777. $whereClause = isset($queryParts['WHERE']) ? $this->SQLparser->compileWhereClause($queryParts['WHERE']) : '1=1';
  778. return $this->exec_DELETEquery($table, $whereClause);
  779. case 'TRUNCATETABLE':
  780. $table = $queryParts['TABLE'];
  781. return $this->exec_TRUNCATEquery($table);
  782. }
  783. }
  784. /**************************************
  785. *
  786. * Query building
  787. *
  788. **************************************/
  789. /**
  790. * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
  791. * Usage count/core: 4
  792. *
  793. * @param string See exec_INSERTquery()
  794. * @param array See exec_INSERTquery()
  795. * @param mixed See exec_INSERTquery()
  796. * @return mixed Full SQL query for INSERT as string or array (unless $fields_values does not contain any elements in which case it will be FALSE). If BLOB fields will be affected and one is not running the native type, an array will be returned, where 0 => plain SQL, 1 => fieldname/value pairs of BLOB fields
  797. */
  798. public function INSERTquery($table, $fields_values, $no_quote_fields = '') {
  799. // Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
  800. if (is_array($fields_values) && count($fields_values)) {
  801. if (is_string($no_quote_fields)) {
  802. $no_quote_fields = explode(',', $no_quote_fields);
  803. } elseif (!is_array($no_quote_fields)) {
  804. $no_quote_fields = array();
  805. }
  806. $blobfields = array();
  807. $nArr = array();
  808. foreach ($fields_values as $k => $v) {
  809. if (!$this->runningNative() && $this->sql_field_metatype($table, $k) == 'B') {
  810. // we skip the field in the regular INSERT statement, it is only in blobfields
  811. $blobfields[$this->quoteFieldNames($k)] = $v;
  812. } elseif (!$this->runningNative() && $this->sql_field_metatype($table, $k) == 'XL') {
  813. // we skip the field in the regular INSERT statement, it is only in clobfields
  814. $clobfields[$this->quoteFieldNames($k)] = $v;
  815. } else {
  816. // Add slashes old-school:
  817. // cast numerical values
  818. $mt = $this->sql_field_metatype($table, $k);
  819. if ($mt{0} == 'I') {
  820. $v = (int)$v;
  821. } else if ($mt{0} == 'F') {
  822. $v = (double)$v;
  823. }
  824. $nArr[$this->quoteFieldNames($k)] = (!in_array($k,$no_quote_fields)) ? $this->fullQuoteStr($v, $table) : $v;
  825. }
  826. }
  827. if (count($blobfields) || count($clobfields)) {
  828. if (count($nArr)) {
  829. $query[0] = 'INSERT INTO ' . $this->quoteFromTables($table) . '
  830. (
  831. ' . implode(',
  832. ', array_keys($nArr)) . '
  833. ) VALUES (
  834. ' . implode(',
  835. ', $nArr) . '
  836. )';
  837. }
  838. if (count($blobfields)) $query[1] = $blobfields;
  839. if (count($clobfields)) $query[2] = $clobfields;
  840. if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query[0];
  841. } else {
  842. $query = 'INSERT INTO '.$this->quoteFromTables($table).'
  843. (
  844. ' . implode(',
  845. ', array_keys($nArr)) . '
  846. ) VALUES (
  847. ' . implode(',
  848. ', $nArr) . '
  849. )';
  850. if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
  851. }
  852. return $query;
  853. }
  854. }
  855. /**
  856. * Creates an INSERT SQL-statement for $table with multiple rows.
  857. * This method will create multiple INSERT queries concatenated with ';'
  858. *
  859. * @param string Table name
  860. * @param array Field names
  861. * @param array Table rows. Each row should be an array with field values mapping to $fields
  862. * @param string/array See fullQuoteArray()
  863. * @return array Full SQL query for INSERT as array of strings (unless $fields_values does not contain any elements in which case it will be FALSE). If BLOB fields will be affected and one is not running the native type, an array will be returned for each row, where 0 => plain SQL, 1 => fieldname/value pairs of BLOB fields.
  864. */
  865. public function INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
  866. if ((string)$this->handlerCfg[$this->lastHandlerKey]['type'] === 'native') {
  867. return parent::INSERTmultipleRows($table, $fields, $rows, $no_quote_fields);
  868. }
  869. $result = array();
  870. foreach ($rows as $row) {
  871. $fields_values = array();
  872. foreach ($fields as $key => $value) {
  873. $fields_values[$value] = $row[$key];
  874. }
  875. $rowQuery = $this->INSERTquery($table, $fields_values, $no_quote_fields);
  876. if (is_array($rowQuery)) {
  877. $result[] = $rowQuery;
  878. } else {
  879. $result[][0] = $rowQuery;
  880. }
  881. }
  882. return $result;
  883. }
  884. /**
  885. * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
  886. * Usage count/core: 6
  887. *
  888. * @param string See exec_UPDATEquery()
  889. * @param string See exec_UPDATEquery()
  890. * @param array See exec_UPDATEquery()
  891. * @param mixed See exec_UPDATEquery()
  892. * @return mixed Full SQL query for UPDATE as string or array (unless $fields_values does not contain any elements in which case it will be FALSE). If BLOB fields will be affected and one is not running the native type, an array will be returned, where 0 => plain SQL, 1 => fieldname/value pairs of BLOB fields
  893. */
  894. public function UPDATEquery($table, $where, $fields_values, $no_quote_fields = '') {
  895. // Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
  896. if (is_string($where)) {
  897. $fields = array();
  898. $blobfields = array();
  899. $clobfields = array();
  900. if (is_array($fields_values) && count($fields_values)) {
  901. if (is_string($no_quote_fields)) {
  902. $no_quote_fields = explode(',', $no_quote_fields);
  903. } elseif (!is_array($no_quote_fields)) {
  904. $no_quote_fields = array();
  905. }
  906. $nArr = array();
  907. foreach ($fields_values as $k => $v) {
  908. if (!$this->runningNative() && $this->sql_field_metatype($table, $k) == 'B') {
  909. // we skip the field in the regular UPDATE statement, it is only in blobfields
  910. $blobfields[$this->quoteFieldNames($k)] = $v;
  911. } elseif (!$this->runningNative() && $this->sql_field_metatype($table, $k) == 'XL') {
  912. // we skip the field in the regular UPDATE statement, it is only in clobfields
  913. $clobfields[$this->quoteFieldNames($k)] = $v;
  914. } else {
  915. // Add slashes old-school:
  916. // cast numeric values
  917. $mt = $this->sql_field_metatype($table, $k);
  918. if ($mt{0} == 'I') {
  919. $v = (int)$v;
  920. } else if ($mt{0} == 'F') {
  921. $v = (double)$v;
  922. }
  923. $nArr[] = $this->quoteFieldNames($k) . '=' . ((!in_array($k, $no_quote_fields)) ? $this->fullQuoteStr($v, $table) : $v);
  924. }
  925. }
  926. }
  927. if (count($blobfields) || count($clobfields)) {
  928. if (count($nArr)) {
  929. $query[0] = 'UPDATE ' . $this->quoteFromTables($table) . '
  930. SET
  931. ' . implode(',
  932. ', $nArr) .
  933. (strlen($where) > 0 ? '
  934. WHERE
  935. ' . $this->quoteWhereClause($where) : '');
  936. }
  937. if (count($blobfields)) {
  938. $query[1] = $blobfields;
  939. }
  940. if (count($clobfields)) {
  941. $query[2] = $clobfields;
  942. }
  943. if ($this->debugOutput || $this->store_lastBuiltQuery) {
  944. $this->debug_lastBuiltQuery = $query[0];
  945. }
  946. } else {
  947. $query = 'UPDATE ' . $this->quoteFromTables($table) . '
  948. SET
  949. ' . implode(',
  950. ', $nArr) .
  951. (strlen($where) > 0 ? '
  952. WHERE
  953. ' . $this->quoteWhereClause($where) : '');
  954. if ($this->debugOutput || $this->store_lastBuiltQuery) {
  955. $this->debug_lastBuiltQuery = $query;
  956. }
  957. }
  958. return $query;
  959. } else {
  960. throw new InvalidArgumentException(
  961. 'TYPO3 Fatal Error: "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !',
  962. 1270853880
  963. );
  964. }
  965. }
  966. /**
  967. * Creates a DELETE SQL-statement for $table where $where-clause
  968. * Usage count/core: 3
  969. *
  970. * @param string See exec_DELETEquery()
  971. * @param string See exec_DELETEquery()
  972. * @return string Full SQL query for DELETE
  973. */
  974. public function DELETEquery($table, $where) {
  975. if (is_string($where)) {
  976. $table = $this->quoteFromTables($table);
  977. $where = $this->quoteWhereClause($where);
  978. $query = parent::DELETEquery($table, $where);
  979. if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
  980. return $query;
  981. } else {
  982. die('<strong>TYPO3 Fatal Error:</strong> "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !');
  983. }
  984. }
  985. /**
  986. * Creates a SELECT SQL-statement
  987. * Usage count/core: 11
  988. *
  989. * @param string See exec_SELECTquery()
  990. * @param string See exec_SELECTquery()
  991. * @param string See exec_SELECTquery()
  992. * @param string See exec_SELECTquery()
  993. * @param string See exec_SELECTquery()
  994. * @param string See exec_SELECTquery()
  995. * @return string Full SQL query for SELECT
  996. */
  997. public function SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
  998. $this->lastHandlerKey = $this->handler_getFromTableList($from_table);
  999. $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
  1000. if ($hType === 'adodb' && $this->runningADOdbDriver('postgres')) {
  1001. // Possibly rewrite the LIMIT to be PostgreSQL-compatible
  1002. $splitLimit = t3lib_div::intExplode(',', $limit); // Splitting the limit values:
  1003. if ($splitLimit[1]) { // If there are two parameters, do mapping differently than otherwise:
  1004. $numrows = $splitLimit[1];
  1005. $offset = $splitLimit[0];
  1006. $limit = $numrows . ' OFFSET ' . $offset;
  1007. }
  1008. }
  1009. $select_fields = $this->quoteFieldNames($select_fields);
  1010. $from_table = $this->quoteFromTables($from_table);
  1011. $where_clause = $this->quoteWhereClause($where_clause);
  1012. $groupBy = $this->quoteGroupBy($groupBy);
  1013. $orderBy = $this->quoteOrderBy($orderBy);
  1014. // Call parent method to build actual query
  1015. $query = parent::SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit);
  1016. if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
  1017. return $query;
  1018. }
  1019. /**
  1020. * Creates a TRUNCATE TABLE SQL-statement
  1021. *
  1022. * @param string See exec_TRUNCATEquery()
  1023. * @return string Full SQL query for TRUNCATE TABLE
  1024. */
  1025. public function TRUNCATEquery($table) {
  1026. $table = $this->quoteFromTables($table);
  1027. // Call parent method to build actual query
  1028. $query = parent::TRUNCATEquery($table);
  1029. if ($this->debugOutput || $this->store_lastBuiltQuery) {
  1030. $this->debug_lastBuiltQuery = $query;
  1031. }
  1032. return $query;
  1033. }
  1034. /**************************************
  1035. *
  1036. * Functions for quoting table/field names
  1037. *
  1038. **************************************/
  1039. /**
  1040. * Quotes components of a SELECT subquery.
  1041. *
  1042. * @param array $components Array of SQL query components
  1043. * @return array
  1044. */
  1045. protected function quoteSELECTsubquery(array $components) {
  1046. $components['SELECT'] = $this->_quoteFieldNames($components['SELECT']);
  1047. $components['FROM'] = $this->_quoteFromTables($components['FROM']);
  1048. $components['WHERE'] = $this->_quoteWhereClause($components['WHERE']);
  1049. return $components;
  1050. }
  1051. /**
  1052. * Quotes field (and table) names with the quote character suitable for the DB being used
  1053. * Use quoteFieldNames instead!
  1054. *
  1055. * @param string List of fields to be selected from DB
  1056. * @return string Quoted list of fields to be selected from DB
  1057. * @deprecated since TYPO3 4.0
  1058. */
  1059. public function quoteSelectFields($select_fields) {
  1060. $this->quoteFieldNames($select_fields);
  1061. }
  1062. /**
  1063. * Quotes field (and table) names with the quote character suitable for the DB being used
  1064. *
  1065. * @param string List of fields to be used in query to DB
  1066. * @return string Quoted list of fields to be in query to DB
  1067. */
  1068. public function quoteFieldNames($select_fields) {
  1069. if ($select_fields == '') return '';
  1070. if ($this->runningNative()) return $select_fields;
  1071. $select_fields = $this->SQLparser->parseFieldList($select_fields);
  1072. if ($this->SQLparser->parse_error) {
  1073. die($this->SQLparser->parse_error . ' in ' . __FILE__ . ' : ' . __LINE__);
  1074. }
  1075. $select_fields = $this->_quoteFieldNames($select_fields);
  1076. return $this->SQLparser->compileFieldList($select_fields);
  1077. }
  1078. /**
  1079. * Quotes field (and table) names in a SQL SELECT clause acccording to DB rules
  1080. *
  1081. * @param array $select_fields The parsed fields to quote
  1082. * @return array
  1083. * @see quoteFieldNames()
  1084. */
  1085. protected function _quoteFieldNames(array $select_fields) {
  1086. foreach ($select_fields as $k => $v) {
  1087. if ($select_fields[$k]['field'] != '' && $select_fields[$k]['field'] != '*' && !is_numeric($select_fields[$k]['field'])) {
  1088. $select_fields[$k]['field'] = $this->quoteName($select_fields[$k]['field']);
  1089. }
  1090. if ($select_fields[$k]['table'] != '' && !is_numeric($select_fields[$k]['table'])) {
  1091. $select_fields[$k]['table'] = $this->quoteName($select_fields[$k]['table']);
  1092. }
  1093. if ($select_fields[$k]['as'] != '') {
  1094. $select_fields[$k]['as'] = $this->quoteName($select_fields[$k]['as']);
  1095. }
  1096. if (isset($select_fields[$k]['func_content.']) && $select_fields[$k]['func_content.'][0]['func_content'] != '*'){
  1097. $select_fields[$k]['func_content.'][0]['func_content'] = $this->quoteFieldNames($select_fields[$k]['func_content.'][0]['func_content']);
  1098. $select_fields[$k]['func_content'] = $this->quoteFieldNames($select_fields[$k]['func_content']);
  1099. }
  1100. if (isset($select_fields[$k]['flow-control'])) {
  1101. // Quoting flow-control statements
  1102. if ($select_fields[$k]['flow-control']['type'] === 'CASE') {
  1103. if (isset($select_fields[$k]['flow-control']['case_field'])) {
  1104. $select_fields[$k]['flow-control']['case_field'] = $this->quoteFieldNames($select_fields[$k]['flow-control']['case_field']);
  1105. }
  1106. foreach ($select_fields[$k]['flow-control']['when'] as $key => $when) {
  1107. $select_fields[$k]['flow-control']['when'][$key]['when_value'] = $this->_quoteWhereClause($when['when_value']);
  1108. }
  1109. }
  1110. }
  1111. }
  1112. return $select_fields;
  1113. }
  1114. /**
  1115. * Quotes table names with the quote character suitable for the DB being used
  1116. *
  1117. * @param string List of tables to be selected from DB
  1118. * @return string Quoted list of tables to be selected from DB
  1119. */
  1120. public function quoteFromTables($from_table) {
  1121. if ($from_table == '') return '';
  1122. if ($this->runningNative()) return $from_table;
  1123. $from_table = $this->SQLparser->parseFromTables($from_table);
  1124. $from_table = $this->_quoteFromTables($from_table);
  1125. return $this->SQLparser->compileFromTables($from_table);
  1126. }
  1127. /**
  1128. * Quotes table names in a SQL FROM clause acccording to DB rules
  1129. *
  1130. * @param array $from_table The parsed FROM clause to quote
  1131. * @return array
  1132. * @see quoteFromTables()
  1133. */
  1134. protected function _quoteFromTables(array $from_table) {
  1135. foreach ($from_table as $k => $v) {
  1136. $from_table[$k]['table'] = $this->quoteName($from_table[$k]['table']);
  1137. if ($from_table[$k]['as'] != '') {
  1138. $from_table[$k]['as'] = $this->quoteName($from_table[$k]['as']);
  1139. }
  1140. if (is_array($v['JOIN'])) {
  1141. foreach ($v['JOIN'] as $joinCnt => $join) {
  1142. $from_table[$k]['JOIN'][$joinCnt]['withTable'] = $this->quoteName($join['withTable']);
  1143. $from_table[$k]['JOIN'][$joinCnt]['as'] = ($join['as']) ? $this->quoteName($join['as']) : '';
  1144. foreach ($from_table[$k]['JOIN'][$joinCnt]['ON'] as &$condition) {
  1145. $condition['left']['table'] = ($condition['left']['table']) ? $this->quoteName($condition['left']['table']) : '';
  1146. $condition['left']['field'] = $this->quoteName($condition['left']['field']);
  1147. $condition['right']['table'] = ($condition['right']['table']) ? $this->quoteName($condition['right']['table']) : '';
  1148. $condition['right']['field'] = $this->quoteName($condition['right']['field']);
  1149. }
  1150. }
  1151. }
  1152. }
  1153. return $from_table;
  1154. }
  1155. /**
  1156. * Quotes the field (and table) names within a where clause with the quote character suitable for the DB being used
  1157. *
  1158. * @param string A where clause that can e parsed by parseWhereClause
  1159. * @return string Usable where clause with quoted field/table names
  1160. */
  1161. public function quoteWhereClause($where_clause) {
  1162. if ($where_clause === '' || $this->runningNative()) return $where_clause;
  1163. $where_clause = $this->SQLparser->parseWhereClause($where_clause);
  1164. if (is_array($where_clause)) {
  1165. $where_clause = $this->_quoteWhereClause($where_clause);
  1166. $where_clause = $this->SQLparser->compileWhereClause($where_clause);
  1167. } else {
  1168. die('Could not parse where clause in ' . __FILE__ . ' : ' . __LINE__);
  1169. }
  1170. return $where_clause;
  1171. }
  1172. /**
  1173. * Quotes field names in a SQL WHERE clause acccording to DB rules
  1174. *
  1175. * @param array $where_clause The parsed WHERE clause to quote
  1176. * @return array
  1177. * @see quoteWhereClause()
  1178. */
  1179. protected function _quoteWhereClause(array $where_clause) {
  1180. foreach ($where_clause as $k => $v) {
  1181. // Look for sublevel:
  1182. if (is_array($where_clause[$k]['sub'])) {
  1183. $where_clause[$k]['sub'] = $this->_quoteWhereClause($where_clause[$k]['sub']);
  1184. } elseif (isset($v['func'])) {
  1185. switch ($where_clause[$k]['func']['type']) {
  1186. case 'EXISTS':
  1187. $where_clause[$k]['func']['subquery'] = $this->quoteSELECTsubquery($v['func']['subquery']);
  1188. break;
  1189. case 'IFNULL':
  1190. case 'LOCATE':
  1191. if ($where_clause[$k]['func']['table'] != '') {
  1192. $where_clause[$k]['func']['table'] = $this->quoteName($v['func']['table']);
  1193. }
  1194. if ($where_clause[$k]['func']['field'] != '') {
  1195. $where_clause[$k]['func']['field'] = $this->quoteName($v['func']['field']);
  1196. }
  1197. break;
  1198. }
  1199. } else {
  1200. if ($where_clause[$k]['table'] != '') {
  1201. $where_clause[$k]['table'] = $this->quoteName($where_clause[$k]['table']);
  1202. }
  1203. if (!is_numeric($where_clause[$k]['field'])) {
  1204. $where_clause[$k]['field'] = $this->quoteName($where_clause[$k]['field']);
  1205. }
  1206. if (isset($where_clause[$k]['calc_table'])) {
  1207. if ($where_clause[$k]['calc_table'] != '') {
  1208. $where_clause[$k]['calc_table'] = $this->quoteName($where_clause[$k]['calc_table']);
  1209. }
  1210. if ($where_clause[$k]['calc_field'] != '') {
  1211. $where_clause[$k]['calc_field'] = $this->quoteName($where_clause[$k]['calc_field']);
  1212. }
  1213. }
  1214. }
  1215. if ($where_clause[$k]['comparator']) {
  1216. if (isset($v['value']['operator'])) {
  1217. foreach ($where_clause[$k]['value']['args'] as $argK => $fieldDef) {
  1218. $where_clause[$k]['value']['args'][$argK]['table'] = $this->quoteName($fieldDef['table']);
  1219. $where_clause[$k]['value']['args'][$argK]['field'] = $this->quoteName($fieldDef['field']);
  1220. }
  1221. } else {
  1222. // Detecting value type; list or plain:
  1223. if (t3lib_div::inList('NOTIN,IN', strtoupper(str_replace(array(' ',"\n", "\r", "\t"), '', $where_clause[$k]['comparator'])))) {
  1224. if (isset($v['subquery'])) {
  1225. $where_clause[$k]['subquery'] = $this->quoteSELECTsubquery($v['subquery']);
  1226. }
  1227. } else {
  1228. if ((!isset($where_clause[$k]['value'][1]) || $where_clause[$k]['value'][1] == '') && is_string($where_clause[$k]['value'][0]) && strstr($where_clause[$k]['value'][0], '.')) {
  1229. $where_clause[$k]['value'][0] = $this->quoteFieldNames($where_clause[$k]['value'][0]);
  1230. }
  1231. }
  1232. }
  1233. }
  1234. }
  1235. return $where_clause;
  1236. }
  1237. /**
  1238. * [Describe function...]
  1239. *
  1240. * @param [type] $$groupBy: ...
  1241. * @return [type] ...
  1242. */
  1243. protected function quoteGroupBy($groupBy) {
  1244. if ($groupBy === '') return '';
  1245. if ($this->runningNative()) return $groupBy;
  1246. $groupBy = $this->SQLparser->parseFieldList($groupBy);
  1247. foreach ($groupBy as $k => $v) {
  1248. $groupBy[$k]['field'] = $this->quoteName($groupBy[$k]['field']);
  1249. if ($groupBy[$k]['table'] != '') {
  1250. $groupBy[$k]['table'] = $this->quoteName($groupBy[$k]['table']);
  1251. }
  1252. }
  1253. return $this->SQLparser->compileFieldList($groupBy);
  1254. }
  1255. /**
  1256. * [Describe function...]
  1257. *
  1258. * @param [type] $$orderBy: ...
  1259. * @return [type] ...
  1260. */
  1261. protected function quoteOrderBy($orderBy) {
  1262. if ($orderBy === '') return '';
  1263. if ($this->runningNative()) return $orderBy;
  1264. $orderBy = $this->SQLparser->parseFieldList($orderBy);
  1265. foreach ($orderBy as $k => $v) {
  1266. $orderBy[$k]['field'] = $this->quoteName($orderBy[$k]['field']);
  1267. if ($orderBy[$k]['table'] != '') {
  1268. $orderBy[$k]['table'] = $this->quoteName($orderBy[$k]['table']);
  1269. }
  1270. }
  1271. return $this->SQLparser->compileFieldList($orderBy);
  1272. }
  1273. /**************************************
  1274. *
  1275. * Various helper functions
  1276. *
  1277. **************************************/
  1278. /**
  1279. * Escaping and quoting values for SQL statements.
  1280. *
  1281. * @param string Input string
  1282. * @param string Table name for which to quote string. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how to quote the string!).
  1283. * @return string Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
  1284. * @see quoteStr()
  1285. */
  1286. public function fullQuoteStr($str, $table) {
  1287. return '\'' . $this->quoteStr($str, $table) . '\'';
  1288. }
  1289. /**
  1290. * Substitution for PHP function "addslashes()"
  1291. * NOTICE: You must wrap the output of this function in SINGLE QUOTES to be DBAL compatible. Unless you have to apply the single quotes yourself you should rather use ->fullQuoteStr()!
  1292. *
  1293. * @param string Input string
  1294. * @param string Table name for which to quote string. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how to quote the string!).
  1295. * @return string Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
  1296. * @see quoteStr()
  1297. */
  1298. public function quoteStr($str, $table) {
  1299. $this->lastHandlerKey = $this->handler_getFromTableList($table);
  1300. switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
  1301. case 'native':
  1302. if ($this->handlerInstance[$this->lastHandlerKey]['link']) {
  1303. $str = mysql_real_escape_string($str, $this->handlerInstance[$this->lastHandlerKey]['link']);
  1304. } else {
  1305. // link may be null when unit testing DBAL
  1306. $str = str_replace('\'', '\\\'', $str);
  1307. }
  1308. break;
  1309. case 'adodb':
  1310. $str = substr($this->handlerInstance[$this->lastHandlerKey]->qstr($str), 1, -1);
  1311. break;
  1312. case 'userdefined':
  1313. $str = $this->handlerInstance[$this->lastHandlerKey]->quoteStr($str);
  1314. break;
  1315. default:
  1316. die('No handler found!!!');
  1317. break;
  1318. }
  1319. return $str;
  1320. }
  1321. /**
  1322. * Quotes an object name (table name, field, ...)
  1323. *
  1324. * @param string Object's name
  1325. * @param string Handler key
  1326. * @param boolean If method NameQuote() is not used, whether to use backticks instead of driver-specific quotes
  1327. * @return string Properly-quoted object's name
  1328. */
  1329. public function quoteName($name, $handlerKey = NULL, $useBackticks = FALSE) {
  1330. $handlerKey = $handlerKey ? $handlerKey : $this->lastHandlerKey;
  1331. $useNameQuote = isset($this->handlerCfg[$handlerKey]['config']['useNameQuote']) ? $this->handlerCfg[$handlerKey]['config']['useNameQuote'] : FALSE;
  1332. if ($useNameQuote) {
  1333. return $this->handlerInstance[$handlerKey]->DataDictionary->NameQuote($name);
  1334. } else {
  1335. $quote = $useBackticks ? '`' : $this->handlerInstance[$handlerKey]->nameQuote;
  1336. return $quote . $name . $quote;
  1337. }
  1338. }
  1339. /**
  1340. * Return MetaType for native field type (ADOdb only!)
  1341. *
  1342. * @param string native type as reported by admin_get_fields()
  1343. * @param string Table name for which query type string. Important for detection of DBMS handler of the query!
  1344. * @return string Meta type (currenly ADOdb syntax only, http://phplens.com/lens/adodb/docs-adodb.htm#metatype)
  1345. */
  1346. public function MetaType($type, $table, $max_length = -1) {
  1347. $this->lastHandlerKey = $this->handler_getFromTableList($table);
  1348. $str = '';
  1349. switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
  1350. case 'native':
  1351. $str = $type;
  1352. break;
  1353. case 'adodb':
  1354. if (in_array($table, $this->cache_fieldType)) {
  1355. $rs = $this->handlerInstance[$this->lastHandlerKey]->SelectLimit('SELECT * FROM ' . $this->quoteFromTables($table), 1);
  1356. $str = $rs->MetaType($type, $max_length);
  1357. }
  1358. break;
  1359. case 'userdefined':
  1360. $str = $this->handlerInstance[$this->lastHandlerKey]->MetaType($str,$table,$max_length);
  1361. break;
  1362. default:
  1363. die('No handler found!!!');
  1364. break;
  1365. }
  1366. return $str;
  1367. }
  1368. /**
  1369. * Return MetaType for native MySQL field type
  1370. *
  1371. * @param string native type as reported as in mysqldump files
  1372. * @return string Meta type (currenly ADOdb syntax only, http://phplens.com/lens/adodb/docs-adodb.htm#metatype)
  1373. */
  1374. public function MySQLMetaType($t) {
  1375. switch (strtoupper($t)) {
  1376. case 'STRING':
  1377. case 'CHAR':
  1378. case 'VARCHAR':
  1379. case 'TINYBLOB':
  1380. case 'TINYTEXT':
  1381. case 'ENUM':
  1382. case 'SET': return 'C';
  1383. case 'TEXT':
  1384. case 'LONGTEXT':
  1385. case 'MEDIUMTEXT': return 'XL';
  1386. case 'IMAGE':
  1387. case 'LONGBLOB':
  1388. case 'BLOB':
  1389. case 'MEDIUMBLOB': return 'B';
  1390. case 'YEAR':
  1391. case 'DATE': return 'D';
  1392. case 'TIME':
  1393. case 'DATETIME':
  1394. case 'TIMESTAMP': return 'T';
  1395. case 'FLOAT':
  1396. case 'DOUBLE': return 'F';
  1397. case 'INT':
  1398. case 'INTEGER':
  1399. case 'TINYINT':
  1400. case 'SMALLINT':
  1401. case 'MEDIUMINT':
  1402. case 'BIGINT': return 'I8'; // we always return I8 to be on the safe side. Under some circumstances the fields are to small otherwise...
  1403. default: return 'N';
  1404. }
  1405. }
  1406. /**
  1407. * Return actual MySQL type for meta field type
  1408. *
  1409. * @param string Meta type (currenly ADOdb syntax only, http://phplens.com/lens/adodb/docs-adodb.htm#metatype)
  1410. * @return string native type as reported as in mysqldump files, uppercase
  1411. */
  1412. public function MySQLActualType($meta) {
  1413. switch (strtoupper($meta)) {
  1414. case 'C': return 'VARCHAR';
  1415. case 'XL':
  1416. case 'X': return 'LONGTEXT';
  1417. case 'C2': return 'VARCHAR';
  1418. case 'X2': return 'LONGTEXT';
  1419. case 'B': return 'LONGBLOB';
  1420. case 'D': return 'DATE';
  1421. case 'T': return 'DATETIME';
  1422. case 'L': return 'TINYINT';
  1423. case 'I':
  1424. case 'I1':
  1425. case 'I2':
  1426. case 'I4':
  1427. case 'I8': return 'BIGINT'; // we only have I8 in DBAL, see MySQLMetaType()
  1428. case 'F': return 'DOUBLE';
  1429. case 'N': return 'NUMERIC';
  1430. default: return $meta;
  1431. }
  1432. }
  1433. /**************************************
  1434. *
  1435. * SQL wrapper functions (Overriding parent methods)
  1436. * (For use in your applications)
  1437. *
  1438. **************************************/
  1439. /**
  1440. * Returns the error status on the most recent sql() execution (based on $this->lastHandlerKey)
  1441. *
  1442. * @return string Handler error strings
  1443. */
  1444. public function sql_error() {
  1445. switch ($this->handlerCfg[$this->lastHandlerKey]['type']) {
  1446. case 'native':
  1447. $output = mysql_error($this->handlerInstance[$this->lastHandlerKey]['link']);
  1448. break;
  1449. case 'adodb':
  1450. $output = $this->handlerInstance[$this->lastHandlerKey]->ErrorMsg();
  1451. break;
  1452. case 'userdefined':
  1453. $output = $this->handlerInstance[$this->lastHandlerKey]->sql_error();
  1454. break;
  1455. }
  1456. return $output;
  1457. }
  1458. /**
  1459. * Returns the error number on the most recent sql() execution (based on $this->lastHandlerKey)
  1460. *
  1461. * @return int Handler error number
  1462. */
  1463. public function sql_errno() {
  1464. switch ($this->handlerCfg[$this->lastHandlerKey]['type']) {
  1465. case 'native':
  1466. $output = mysql_errno($this->handlerInstance[$this->lastHandlerKey]['link']);
  1467. break;
  1468. case 'adodb':
  1469. $output = $this->handlerInstance[$this->lastHandlerKey]->ErrorNo();
  1470. break;
  1471. case 'userdefined':
  1472. $output = $this->handlerInstance[$this->lastHandlerKey]->sql_errno();
  1473. break;
  1474. }
  1475. return $output;
  1476. }
  1477. /**
  1478. * Returns the number of selected rows.
  1479. *
  1480. * @param pointer Result pointer / DBAL object
  1481. * @return integer Number of resulting rows.
  1482. */
  1483. public function sql_num_rows(&$res) {
  1484. if ($res === FALSE) return 0;
  1485. $handlerType = is_object($res) ? $res->TYPO3_DBAL_handlerType : 'native';
  1486. switch ($handlerType) {
  1487. case 'native':
  1488. $output = mysql_num_rows($res);
  1489. break;
  1490. case 'adodb':
  1491. $output = method_exists($res, 'RecordCount') ? $res->RecordCount() : 0;
  1492. break;
  1493. case 'userdefined':
  1494. $output = $res->sql_num_rows();
  1495. break;
  1496. }
  1497. return $output;
  1498. }
  1499. /**
  1500. * Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
  1501. *
  1502. * @param pointer MySQL result pointer (of SELECT query) / DBAL object
  1503. * @return array Associative array of result row.
  1504. */
  1505. public function sql_fetch_assoc(&$res) {
  1506. $output = array();
  1507. $handlerType = is_object($res) ? $res->TYPO3_DBAL_handlerType : (is_resource($res) ? 'native' : FALSE);
  1508. switch ($handlerType) {
  1509. case 'native':
  1510. $output = mysql_fetch_assoc($res);
  1511. $tableList = $this->resourceIdToTableNameMap[(string)$res]; // Reading list of tables from SELECT query:
  1512. break;
  1513. case 'adodb':
  1514. // Check if method exists for the current $res object.
  1515. // If a table exists in TCA but not in the db, a error
  1516. // occured because $res is not a valid object.
  1517. if (method_exists($res, 'FetchRow')) {
  1518. $output = $res->FetchRow();
  1519. $tableList = $res->TYPO3_DBAL_tableList; // Reading list of tables from SELECT query:
  1520. // Removing all numeric/integer keys.
  1521. // A workaround because in ADOdb we would need to know what we want before executing the query...
  1522. // MSSQL does not support ADODB_FETCH_BOTH and always returns an assoc. array instead. So
  1523. // we don't need to remove anything.
  1524. if (is_array($output)) {
  1525. if ($this->runningADOdbDriver('mssql')) {
  1526. // MSSQL does not know such thing as an empty string. So it returns one space instead, which we must fix.
  1527. foreach ($output as $key => $value) {
  1528. if ($value === ' ') {
  1529. $output[$key] = '';
  1530. }
  1531. }
  1532. } else {
  1533. foreach ($output as $key => $value) {
  1534. if (is_integer($key)) {
  1535. unset($output[$key]);
  1536. }
  1537. }
  1538. }
  1539. }
  1540. }
  1541. break;
  1542. case 'userdefined':
  1543. $output = $res->sql_fetch_assoc();
  1544. $tableList = $res->TYPO3_DBAL_tableList; // Reading list of tables from SELECT query:
  1545. break;
  1546. }
  1547. // Table/Fieldname mapping:
  1548. if (is_array($output)) {
  1549. if ($tables = $this->map_needMapping($tableList,TRUE)) {
  1550. $output = $this->map_assocArray($output,$tables,1);
  1551. }
  1552. }
  1553. // Return result:
  1554. return $output;
  1555. }
  1556. /**
  1557. * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
  1558. * The array contains the values in numerical indices.
  1559. *
  1560. * @param pointer MySQL result pointer (of SELECT query) / DBAL object
  1561. * @return array Array with result rows.
  1562. */
  1563. public function sql_fetch_row(&$res) {
  1564. $handlerType = is_object($res) ? $res->TYPO3_DBAL_handlerType : 'native';
  1565. switch ($handlerType) {
  1566. case 'native':
  1567. $output = mysql_fetch_row($res);
  1568. break;
  1569. case 'adodb':
  1570. // Check if method exists for the current $res object.
  1571. // If a table exists in TCA but not in the db, a error
  1572. // occured because $res is not a valid object.
  1573. if (method_exists($res, 'FetchRow')) {
  1574. $output = $res->FetchRow();
  1575. // Removing all assoc. keys.
  1576. // A workaround because in ADOdb we would need to know what we want before executing the query...
  1577. // MSSQL does not support ADODB_FETCH_BOTH and always returns an assoc. array instead. So
  1578. // we need to convert resultset.
  1579. if (is_array($output)) {
  1580. $keyIndex = 0;
  1581. foreach ($output as $key => $value) {
  1582. unset($output[$key]);
  1583. if (is_integer($key) || $this->runningADOdbDriver('mssql')) {
  1584. $output[$keyIndex] = $value;
  1585. if ($value === ' ') {
  1586. // MSSQL does not know such thing as an empty string. So it returns one space instead, which we must fix.
  1587. $output[$keyIndex] = '';
  1588. }
  1589. $keyIndex++;
  1590. }
  1591. }
  1592. }
  1593. }
  1594. break;
  1595. case 'userdefined':
  1596. $output = $res->sql_fetch_row();
  1597. break;
  1598. }
  1599. return $output;
  1600. }
  1601. /**
  1602. * Free result memory / unset result object
  1603. *
  1604. * @param pointer MySQL result pointer to free / DBAL object
  1605. * @return boolean Returns TRUE on success or FALSE on failure.
  1606. */
  1607. public function sql_free_result(&$res) {
  1608. if ($res === FALSE) return FALSE;
  1609. $handlerType = is_object($res) ? $res->TYPO3_DBAL_handlerType : 'native';
  1610. switch ($handlerType) {
  1611. case 'native':
  1612. $output = mysql_free_result($res);
  1613. break;
  1614. case 'adodb':
  1615. if (method_exists($res, 'Close')) {
  1616. $res->Close();
  1617. unset($res);
  1618. $output = TRUE;
  1619. } else {
  1620. $output = FALSE;
  1621. }
  1622. break;
  1623. case 'userdefined':
  1624. unset($res);
  1625. break;
  1626. }
  1627. return $output;
  1628. }
  1629. /**
  1630. * Get the ID generated from the previous INSERT operation
  1631. *
  1632. * @return integer The uid of the last inserted record.
  1633. */
  1634. public function sql_insert_id() {
  1635. switch ($this->handlerCfg[$this->lastHandlerKey]['type']) {
  1636. case 'native':
  1637. $output = mysql_insert_id($this->handlerInstance[$this->lastHandlerKey]['link']);
  1638. break;
  1639. case 'adodb':
  1640. $output = $this->handlerInstance[$this->lastHandlerKey]->last_insert_id;
  1641. break;
  1642. case 'userdefined':
  1643. $output = $this->handlerInstance[$this->lastHandlerKey]->sql_insert_id();
  1644. break;
  1645. }
  1646. return $output;
  1647. }
  1648. /**
  1649. * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
  1650. *
  1651. * @return integer Number of rows affected by last query
  1652. */
  1653. public function sql_affected_rows() {
  1654. switch ($this->handlerCfg[$this->lastHandlerKey]['type']) {
  1655. case 'native':
  1656. $output = mysql_affected_rows();
  1657. break;
  1658. case 'adodb':
  1659. $output = $this->handlerInstance[$this->lastHandlerKey]->Affected_Rows();
  1660. break;
  1661. case 'userdefined':
  1662. $output = $this->handlerInstance[$this->lastHandlerKey]->sql_affected_rows();
  1663. break;
  1664. }
  1665. return $output;
  1666. }
  1667. /**
  1668. * Move internal result pointer
  1669. *
  1670. * @param pointer MySQL result pointer (of SELECT query) / DBAL object
  1671. * @param integer Seek result number.
  1672. * @return boolean Returns TRUE on success or FALSE on failure.
  1673. */
  1674. public function sql_data_seek(&$res, $seek) {
  1675. $handlerType = is_object($res) ? $res->TYPO3_DBAL_handlerType : 'native';
  1676. switch ($handlerType) {
  1677. case 'native':
  1678. $output = mysql_data_seek($res,$seek);
  1679. break;
  1680. case 'adodb':
  1681. $output = $res->Move($seek);
  1682. break;
  1683. case 'userdefined':
  1684. $output = $res->sql_data_seek($seek);
  1685. break;
  1686. }
  1687. return $output;
  1688. }
  1689. /**
  1690. * Get the type of the specified field in a result
  1691. *
  1692. * If the first parameter is a string, it is used as table name for the lookup.
  1693. *
  1694. * @param pointer MySQL result pointer (of SELECT query) / DBAL object / table name
  1695. * @param integer Field index. In case of ADOdb a string (field name!) FIXME
  1696. * @return string Returns the type of the specified field index
  1697. */
  1698. public function sql_field_metatype($table, $field) {
  1699. // If $table and/or $field are mapped, use the original names instead
  1700. foreach ($this->mapping as $tableName => $tableMapInfo) {
  1701. if (isset($tableMapInfo['mapTableName']) && $tableMapInfo['mapTableName'] === $table) {
  1702. // Table name is mapped => use original name
  1703. $table = $tableName;
  1704. }
  1705. if (isset($tableMapInfo['mapFieldNames'])) {
  1706. foreach ($tableMapInfo['mapFieldNames'] as $fieldName => $fieldMapInfo) {
  1707. if ($fieldMapInfo === $field) {
  1708. // Field name is mapped => use original name
  1709. $field = $fieldName;
  1710. }
  1711. }
  1712. }
  1713. }
  1714. return $this->cache_fieldType[$table][$field]['metaType'];
  1715. }
  1716. /**
  1717. * Get the type of the specified field in a result
  1718. *
  1719. * If the first parameter is a string, it is used as table name for the lookup.
  1720. *
  1721. * @param pointer MySQL result pointer (of SELECT query) / DBAL object / table name
  1722. * @param integer Field index. In case of ADOdb a string (field name!) FIXME
  1723. * @return string Returns the type of the specified field index
  1724. */
  1725. public function sql_field_type(&$res,$pointer) {
  1726. if ($res === null) {
  1727. debug(array('no res in sql_field_type!'));
  1728. return 'text';
  1729. }
  1730. elseif (is_string($res)){
  1731. if ($res === 'tx_dbal_debuglog') return 'text';
  1732. $handlerType = 'adodb';
  1733. }
  1734. else {
  1735. $handlerType = is_object($res) ? $res->TYPO3_DBAL_handlerType : 'native';
  1736. }
  1737. switch ($handlerType) {
  1738. case 'native':
  1739. $output = mysql_field_type($res,$pointer);
  1740. break;
  1741. case 'adodb':
  1742. if (is_string($pointer)){
  1743. $output = $this->cache_fieldType[$res][$pointer]['type'];
  1744. }
  1745. break;
  1746. case 'userdefined':
  1747. $output = $res->sql_field_type($pointer);
  1748. break;
  1749. }
  1750. return $output;
  1751. }
  1752. /**********
  1753. *
  1754. * Legacy functions, bound to _DEFAULT handler. (Overriding parent methods)
  1755. * Deprecated or still experimental.
  1756. *
  1757. **********/
  1758. /**
  1759. * Executes query (on DEFAULT handler!)
  1760. * DEPRECATED - use exec_* functions from this class instead!
  1761. *
  1762. * @param string Database name
  1763. * @param string Query to execute
  1764. * @return pointer Result pointer
  1765. * @deprecated since TYPO3 4.1
  1766. */
  1767. public function sql($db,$query) {
  1768. return $this->sql_query($query);
  1769. }
  1770. /**
  1771. * Executes a query
  1772. * EXPERIMENTAL - This method will make its best to handle the query correctly
  1773. * but if it cannot, it will simply pass the query to DEFAULT handler.
  1774. *
  1775. * You should use exec_* function from this class instead!
  1776. * If you don't, anything that does not use the _DEFAULT handler will probably break!
  1777. *
  1778. * This method was deprecated in TYPO3 4.1 but is considered experimental since TYPO3 4.4
  1779. * as it tries to handle the query correctly anyway.
  1780. *
  1781. * @param string Query to execute
  1782. * @return pointer Result pointer / DBAL object
  1783. */
  1784. public function sql_query($query) {
  1785. // This method is heavily used by Extbase, try to handle it with DBAL-native methods
  1786. $queryParts = $this->SQLparser->parseSQL($query);
  1787. if (is_array($queryParts) && t3lib_div::inList('SELECT,UPDATE,INSERT,DELETE', $queryParts['type'])) {
  1788. return $this->exec_query($queryParts);
  1789. }
  1790. switch ($this->handlerCfg['_DEFAULT']['type']) {
  1791. case 'native':
  1792. $sqlResult = mysql_query($query, $this->handlerInstance['_DEFAULT']['link']);
  1793. break;
  1794. case 'adodb':
  1795. $sqlResult = $this->handlerInstance['_DEFAULT']->Execute($query);
  1796. $sqlResult->TYPO3_DBAL_handlerType = 'adodb';
  1797. break;
  1798. case 'userdefined':
  1799. $sqlResult = $this->handlerInstance['_DEFAULT']->sql_query($query);
  1800. $sqlResult->TYPO3_DBAL_handlerType = 'userdefined';
  1801. break;
  1802. }
  1803. if ($this->printErrors && $this->sql_error()) {
  1804. debug(array($this->lastQuery, $this->sql_error()));
  1805. }
  1806. return $sqlResult;
  1807. }
  1808. /**
  1809. * Opening the _DEFAULT connection handler to the database.
  1810. * This is typically done by the scripts "init.php" in the backend or "index_ts.php" in the frontend (tslib_fe->connectToMySQL())
  1811. * You wouldn't need to use this at any time - let TYPO3 core handle this.
  1812. *
  1813. * @param string Database host IP/domain
  1814. * @param string Username to connect with.
  1815. * @param string Password to connect with.
  1816. * @return mixed Returns handler connection value
  1817. * @deprecated since TYPO3 4.1
  1818. * @see handler_init()
  1819. */
  1820. public function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password) {
  1821. // Overriding the _DEFAULT handler configuration of username, password, localhost and database name:
  1822. $this->handlerCfg['_DEFAULT']['config']['username'] = $TYPO3_db_username;
  1823. $this->handlerCfg['_DEFAULT']['config']['password'] = $TYPO3_db_password;
  1824. $this->handlerCfg['_DEFAULT']['config']['host'] = $TYPO3_db_host;
  1825. $this->handlerCfg['_DEFAULT']['config']['database'] = TYPO3_db;
  1826. // Initializing and output value:
  1827. $sqlResult = $this->handler_init('_DEFAULT');
  1828. return $sqlResult;
  1829. }
  1830. /**
  1831. * Select database for _DEFAULT handler.
  1832. *
  1833. * @param string Database to connect to.
  1834. * @return boolean Always returns TRUE; function is obsolete, database selection is made in handler_init() function!
  1835. * @deprecated since TYPO3 4.1
  1836. */
  1837. public function sql_select_db($TYPO3_db) {
  1838. return TRUE;
  1839. }
  1840. /**************************************
  1841. *
  1842. * SQL admin functions
  1843. * (For use in the Install Tool and Extension Manager)
  1844. *
  1845. **************************************/
  1846. /**
  1847. * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
  1848. * Use in Install Tool only!
  1849. * Usage count/core: 1
  1850. *
  1851. * @return array Each entry represents a database name
  1852. */
  1853. public function admin_get_dbs() {
  1854. $dbArr = array();
  1855. switch ($this->handlerCfg['_DEFAULT']['type']) {
  1856. case 'native':
  1857. $db_list = mysql_list_dbs($this->link);
  1858. while ($row = mysql_fetch_object($db_list)) {
  1859. if ($this->sql_select_db($row->Database)) {
  1860. $dbArr[] = $row->Database;
  1861. }
  1862. }
  1863. break;
  1864. case 'adodb':
  1865. // check needed for install tool - otherwise it will just die because the call to
  1866. // MetaDatabases is done on a stdClass instance
  1867. if (method_exists($this->handlerInstance['_DEFAULT'],'MetaDatabases')) {
  1868. $sqlDBs = $this->handlerInstance['_DEFAULT']->MetaDatabases();
  1869. if (is_array($sqlDBs)) {
  1870. foreach ($sqlDBs as $k => $theDB) {
  1871. $dbArr[] = $theDB;
  1872. }
  1873. }
  1874. }
  1875. break;
  1876. case 'userdefined':
  1877. $dbArr = $this->handlerInstance['_DEFAULT']->admin_get_tables();
  1878. break;
  1879. }
  1880. return $dbArr;
  1881. }
  1882. /**
  1883. * Returns the list of tables from the system (quering the DBMSs)
  1884. * It looks up all tables from the DBMS of the _DEFAULT handler and then add all tables *configured* to be managed by other handlers
  1885. *
  1886. * When fetching the tables, it skips tables whose names begin with BIN$, as this is taken as a table coming from the "Recycle Bin" on Oracle.
  1887. *
  1888. * @return array Tables in an array (tablename is in both key and value)
  1889. * @todo Should the check for Oracle Recycle Bin stuff be moved elsewhere?
  1890. * @todo Should return table details in value! see t3lib_db::admin_get_tables()
  1891. */
  1892. public function admin_get_tables() {
  1893. $whichTables = array();
  1894. // Getting real list of tables:
  1895. switch ($this->handlerCfg['_DEFAULT']['type']) {
  1896. case 'native':
  1897. $tables_result = mysql_query('SHOW TABLE STATUS FROM `' . TYPO3_db . '`', $this->handlerInstance['_DEFAULT']['link']);
  1898. if (!$this->sql_error()) {
  1899. while ($theTable = $this->sql_fetch_assoc($tables_result)) {
  1900. $whichTables[current($theTable)] = current($theTable);
  1901. }
  1902. }
  1903. break;
  1904. case 'adodb':
  1905. // check needed for install tool - otherwise it will just die because the call to
  1906. // MetaTables is done on a stdClass instance
  1907. if (method_exists($this->handlerInstance['_DEFAULT'], 'MetaTables')) {
  1908. $sqlTables = $this->handlerInstance['_DEFAULT']->MetaTables('TABLES');
  1909. while (list($k, $theTable) = each($sqlTables)) {
  1910. if (preg_match('/BIN\$/', $theTable)) continue; // skip tables from the Oracle 10 Recycle Bin
  1911. $whichTables[$theTable] = $theTable;
  1912. }
  1913. }
  1914. break;
  1915. case 'userdefined':
  1916. $whichTables = $this->handlerInstance['_DEFAULT']->admin_get_tables();
  1917. break;
  1918. }
  1919. // Check mapping:
  1920. if (is_array($this->mapping) && count($this->mapping)) {
  1921. // Mapping table names in reverse, first getting list of real table names:
  1922. $tMap = array();
  1923. foreach ($this->mapping as $tN => $tMapInfo) {
  1924. if (isset($tMapInfo['mapTableName'])) $tMap[$tMapInfo['mapTableName']]=$tN;
  1925. }
  1926. // Do mapping:
  1927. $newList=array();
  1928. foreach ($whichTables as $tN) {
  1929. if (isset($tMap[$tN])) $tN = $tMap[$tN];
  1930. $newList[$tN] = $tN;
  1931. }
  1932. $whichTables = $newList;
  1933. }
  1934. // Adding tables configured to reside in other DBMS (handler by other handlers than the default):
  1935. if (is_array($this->table2handlerKeys)) {
  1936. foreach ($this->table2handlerKeys as $key => $handlerKey) {
  1937. $whichTables[$key] = $key;
  1938. }
  1939. }
  1940. return $whichTables;
  1941. }
  1942. /**
  1943. * Returns information about each field in the $table (quering the DBMS)
  1944. * In a DBAL this should look up the right handler for the table and return compatible information
  1945. * This function is important not only for the Install Tool but probably for DBALs as well since they might need to look up table specific information in order to construct correct queries. In such cases this information should probably be cached for quick delivery
  1946. *
  1947. * @param string Table name
  1948. * @return array Field information in an associative array with fieldname => field row
  1949. */
  1950. public function admin_get_fields($tableName) {
  1951. $output = array();
  1952. // Do field mapping if needed:
  1953. $ORIG_tableName = $tableName;
  1954. if ($tableArray = $this->map_needMapping($tableName)) {
  1955. // Table name:
  1956. if ($this->mapping[$tableName]['mapTableName']) {
  1957. $tableName = $this->mapping[$tableName]['mapTableName'];
  1958. }
  1959. }
  1960. // Find columns
  1961. $this->lastHandlerKey = $this->handler_getFromTableList($ORIG_tableName);
  1962. switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
  1963. case 'native':
  1964. $columns_res = mysql_query('SHOW columns FROM '.$tableName, $this->handlerInstance[$this->lastHandlerKey]['link']);
  1965. while($fieldRow = mysql_fetch_assoc($columns_res)) {
  1966. $output[$fieldRow['Field']] = $fieldRow;
  1967. }
  1968. break;
  1969. case 'adodb':
  1970. $fieldRows = $this->handlerInstance[$this->lastHandlerKey]->MetaColumns($tableName, FALSE);
  1971. if (is_array($fieldRows)) {
  1972. foreach ($fieldRows as $k => $fieldRow) {
  1973. settype($fieldRow, 'array');
  1974. $fieldRow['Field'] = $fieldRow['name'];
  1975. $ntype = $this->MySQLActualType($this->MetaType($fieldRow['type'],$tableName));
  1976. $ntype .= (($fieldRow['max_length'] != -1) ? (($ntype == 'INT') ? '(11)' :'('.$fieldRow['max_length'].')') : '');
  1977. $fieldRow['Type'] = strtolower($ntype);
  1978. $fieldRow['Null'] = '';
  1979. $fieldRow['Key'] = '';
  1980. $fieldRow['Default'] = $fieldRow['default_value'];
  1981. $fieldRow['Extra'] = '';
  1982. $output[$fieldRow['name']] = $fieldRow;
  1983. }
  1984. }
  1985. break;
  1986. case 'userdefined':
  1987. $output = $this->handlerInstance[$this->lastHandlerKey]->admin_get_fields($tableName);
  1988. break;
  1989. }
  1990. // mapping should be done:
  1991. if (is_array($tableArray) && is_array($this->mapping[$ORIG_tableName]['mapFieldNames'])) {
  1992. $revFields = array_flip($this->mapping[$ORIG_tableName]['mapFieldNames']);
  1993. $newOutput = array();
  1994. foreach ($output as $fN => $fInfo) {
  1995. if (isset($revFields[$fN])) {
  1996. $fN = $revFields[$fN];
  1997. $fInfo['Field'] = $fN;
  1998. }
  1999. $newOutput[$fN] = $fInfo;
  2000. }
  2001. $output = $newOutput;
  2002. }
  2003. return $output;
  2004. }
  2005. /**
  2006. * Returns information about each index key in the $table (quering the DBMS)
  2007. * In a DBAL this should look up the right handler for the table and return compatible information
  2008. *
  2009. * @param string Table name
  2010. * @return array Key information in a numeric array
  2011. */
  2012. public function admin_get_keys($tableName) {
  2013. $output = array();
  2014. // Do field mapping if needed:
  2015. $ORIG_tableName = $tableName;
  2016. if ($tableArray = $this->map_needMapping($tableName)) {
  2017. // Table name:
  2018. if ($this->mapping[$tableName]['mapTableName']) {
  2019. $tableName = $this->mapping[$tableName]['mapTableName'];
  2020. }
  2021. }
  2022. // Find columns
  2023. $this->lastHandlerKey = $this->handler_getFromTableList($ORIG_tableName);
  2024. switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
  2025. case 'native':
  2026. $keyRes = mysql_query('SHOW keys FROM '.$tableName, $this->handlerInstance[$this->lastHandlerKey]['link']);
  2027. while($keyRow = mysql_fetch_assoc($keyRes)) {
  2028. $output[] = $keyRow;
  2029. }
  2030. break;
  2031. case 'adodb':
  2032. $keyRows = $this->handlerInstance[$this->lastHandlerKey]->MetaIndexes($tableName);
  2033. if ($keyRows !== FALSE) {
  2034. while (list($k, $theKey) = each($keyRows)) {
  2035. $theKey['Table'] = $tableName;
  2036. $theKey['Non_unique'] = (int) !$theKey['unique'];
  2037. $theKey['Key_name'] = str_replace($tableName.'_','',$k);
  2038. // the following are probably not needed anyway...
  2039. $theKey['Collation'] = '';
  2040. $theKey['Cardinality'] = '';
  2041. $theKey['Sub_part'] = '';
  2042. $theKey['Packed'] = '';
  2043. $theKey['Null'] = '';
  2044. $theKey['Index_type'] = '';
  2045. $theKey['Comment'] = '';
  2046. // now map multiple fields into multiple rows (we mimic MySQL, remember...)
  2047. $keycols = $theKey['columns'];
  2048. while (list($c, $theCol) = each($keycols)) {
  2049. $theKey['Seq_in_index'] = $c+1;
  2050. $theKey['Column_name'] = $theCol;
  2051. $output[] = $theKey;
  2052. }
  2053. }
  2054. }
  2055. $priKeyRow = $this->handlerInstance[$this->lastHandlerKey]->MetaPrimaryKeys($tableName);
  2056. $theKey = array();
  2057. $theKey['Table'] = $tableName;
  2058. $theKey['Non_unique'] = 0;
  2059. $theKey['Key_name'] = 'PRIMARY';
  2060. // the following are probably not needed anyway...
  2061. $theKey['Collation'] = '';
  2062. $theKey['Cardinality'] = '';
  2063. $theKey['Sub_part'] = '';
  2064. $theKey['Packed'] = '';
  2065. $theKey['Null'] = '';
  2066. $theKey['Index_type'] = '';
  2067. $theKey['Comment'] = '';
  2068. // now map multiple fields into multiple rows (we mimic MySQL, remember...)
  2069. if ($priKeyRow !== FALSE) {
  2070. while (list($c, $theCol) = each($priKeyRow)) {
  2071. $theKey['Seq_in_index'] = $c+1;
  2072. $theKey['Column_name'] = $theCol;
  2073. $output[] = $theKey;
  2074. }
  2075. }
  2076. break;
  2077. case 'userdefined':
  2078. $output = $this->handlerInstance[$this->lastHandlerKey]->admin_get_keys($tableName);
  2079. break;
  2080. }
  2081. // mapping should be done:
  2082. if (is_array($tableArray) && is_array($this->mapping[$ORIG_tableName]['mapFieldNames'])) {
  2083. $revFields = array_flip($this->mapping[$ORIG_tableName]['mapFieldNames']);
  2084. $newOutput = array();
  2085. foreach ($output as $kN => $kInfo) {
  2086. // Table:
  2087. $kInfo['Table'] = $ORIG_tableName;
  2088. // Column
  2089. if (isset($revFields[$kInfo['Column_name']])) {
  2090. $kInfo['Column_name'] = $revFields[$kInfo['Column_name']];
  2091. }
  2092. // Write it back:
  2093. $newOutput[$kN] = $kInfo;
  2094. }
  2095. $output = $newOutput;
  2096. }
  2097. return $output;
  2098. }
  2099. /**
  2100. * mysql() wrapper function, used by the Install Tool.
  2101. *
  2102. * @return array
  2103. */
  2104. public function admin_get_charsets() {
  2105. return array();
  2106. }
  2107. /**
  2108. * mysql() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
  2109. *
  2110. * @param string Query to execute
  2111. * @return pointer Result pointer
  2112. */
  2113. public function admin_query($query) {
  2114. $parsedQuery = $this->SQLparser->parseSQL($query);
  2115. $ORIG_table = $parsedQuery['TABLE'];
  2116. if (is_array($parsedQuery)) {
  2117. // Process query based on type:
  2118. switch ($parsedQuery['type']) {
  2119. case 'CREATETABLE':
  2120. case 'ALTERTABLE':
  2121. case 'DROPTABLE':
  2122. if (file_exists(PATH_typo3conf.'temp_fieldInfo.php')) unlink(PATH_typo3conf.'temp_fieldInfo.php');
  2123. $this->map_genericQueryParsed($parsedQuery);
  2124. break;
  2125. case 'INSERT':
  2126. case 'TRUNCATETABLE':
  2127. $this->map_genericQueryParsed($parsedQuery);
  2128. break;
  2129. case 'CREATEDATABASE':
  2130. die('Creating a database with DBAL is not supported. Did you really read the manual?');
  2131. break;
  2132. default:
  2133. die('ERROR: Invalid Query type ('.$parsedQuery['type'].') for ->admin_query() function!: "'.htmlspecialchars($query).'"');
  2134. break;
  2135. }
  2136. // Setting query array (for other applications to access if needed)
  2137. $this->lastParsedAndMappedQueryArray = $parsedQuery;
  2138. // Execute query (based on handler derived from the TABLE name which we actually know for once!)
  2139. $this->lastHandlerKey = $this->handler_getFromTableList($ORIG_table);
  2140. switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
  2141. case 'native':
  2142. // Compiling query:
  2143. $compiledQuery = $this->SQLparser->compileSQL($this->lastParsedAndMappedQueryArray);
  2144. if ($this->lastParsedAndMappedQueryArray['type']=='INSERT') {
  2145. return mysql_query($compiledQuery, $this->link);
  2146. }
  2147. return mysql_query($compiledQuery[0], $this->link);
  2148. break;
  2149. case 'adodb':
  2150. // Compiling query:
  2151. $compiledQuery = $this->SQLparser->compileSQL($this->lastParsedAndMappedQueryArray);
  2152. switch ($this->lastParsedAndMappedQueryArray['type']) {
  2153. case 'INSERT':
  2154. return $this->exec_INSERTquery($this->lastParsedAndMappedQueryArray['TABLE'], $compiledQuery);
  2155. case 'TRUNCATETABLE':
  2156. return $this->exec_TRUNCATEquery($this->lastParsedAndMappedQueryArray['TABLE']);
  2157. }
  2158. return $this->handlerInstance[$this->lastHandlerKey]->DataDictionary->ExecuteSQLArray($compiledQuery);
  2159. break;
  2160. case 'userdefined':
  2161. // Compiling query:
  2162. $compiledQuery = $this->SQLparser->compileSQL($this->lastParsedAndMappedQueryArray);
  2163. return $this->handlerInstance[$this->lastHandlerKey]->admin_query($compiledQuery);
  2164. break;
  2165. }
  2166. } else die('ERROR: Query could not be parsed: "'.htmlspecialchars($parsedQuery).'". Query: "'.htmlspecialchars($query).'"');
  2167. }
  2168. /************************************
  2169. *
  2170. * Handler management
  2171. *
  2172. **************************************/
  2173. /**
  2174. * Return the handler key pointing to an appropriate database handler as found in $this->handlerCfg array
  2175. * Notice: TWO or more tables in the table list MUST use the SAME handler key - otherwise a fatal error is thrown! (Logically, no database can possibly join two tables from separate sources!)
  2176. *
  2177. * @param string Table list, eg. "pages" or "pages, tt_content" or "pages AS A, tt_content AS B"
  2178. * @return string Handler key (see $this->handlerCfg array) for table
  2179. */
  2180. public function handler_getFromTableList($tableList) {
  2181. $key = $tableList;
  2182. if (!isset($this->cache_handlerKeyFromTableList[$key])) {
  2183. // Get tables separated:
  2184. $_tableList = $tableList;
  2185. $tableArray = $this->SQLparser->parseFromTables($_tableList);
  2186. // If success, traverse the tables:
  2187. if (is_array($tableArray) && count($tableArray)) {
  2188. $outputHandlerKey = '';
  2189. foreach ($tableArray as $vArray) {
  2190. // Find handler key, select "_DEFAULT" if none is specifically configured:
  2191. $handlerKey = $this->table2handlerKeys[$vArray['table']] ? $this->table2handlerKeys[$vArray['table']] : '_DEFAULT';
  2192. // In case of separate handler keys for joined tables:
  2193. if ($outputHandlerKey && $handlerKey != $outputHandlerKey) {
  2194. die('DBAL fatal error: Tables in this list "'.$tableList.'" didn\'t use the same DB handler!');
  2195. }
  2196. $outputHandlerKey = $handlerKey;
  2197. }
  2198. // Check initialized state; if handler is NOT initialized (connected) then we will connect it!
  2199. if (!isset($this->handlerInstance[$outputHandlerKey])) {
  2200. $this->handler_init($outputHandlerKey);
  2201. }
  2202. // Return handler key:
  2203. $this->cache_handlerKeyFromTableList[$key] = $outputHandlerKey;
  2204. } else {
  2205. die('DBAL fatal error: No handler found in handler_getFromTableList() for: "'.$tableList.'" ('.$tableArray.')');
  2206. }
  2207. }
  2208. return $this->cache_handlerKeyFromTableList[$key];
  2209. }
  2210. /**
  2211. * Initialize handler (connecting to database)
  2212. *
  2213. * @param string Handler key
  2214. * @return boolean If connection went well, return TRUE
  2215. * @see handler_getFromTableList()
  2216. */
  2217. public function handler_init($handlerKey) {
  2218. // Find handler configuration:
  2219. $cfgArray = $this->handlerCfg[$handlerKey];
  2220. $handlerType = (string)$cfgArray['type'];
  2221. $output = FALSE;
  2222. if (is_array($cfgArray)) {
  2223. if (!$cfgArray['config']['database']) {
  2224. // Configuration is incomplete
  2225. return;
  2226. }
  2227. switch ($handlerType) {
  2228. case 'native':
  2229. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']) {
  2230. $link = mysql_connect($cfgArray['config']['host'].(isset($cfgArray['config']['port']) ? ':'.$cfgArray['config']['port'] : ''), $cfgArray['config']['username'], $cfgArray['config']['password'], TRUE);
  2231. } else {
  2232. $link = mysql_pconnect($cfgArray['config']['host'].(isset($cfgArray['config']['port']) ? ':'.$cfgArray['config']['port'] : ''), $cfgArray['config']['username'], $cfgArray['config']['password']);
  2233. }
  2234. // Set handler instance:
  2235. $this->handlerInstance[$handlerKey] = array('handlerType' => 'native', 'link' => $link);
  2236. // If link succeeded:
  2237. if ($link) {
  2238. // For default, set ->link (see t3lib_DB)
  2239. if ($handlerKey == '_DEFAULT') {
  2240. $this->link = $link;
  2241. }
  2242. // Select database as well:
  2243. if (mysql_select_db($cfgArray['config']['database'], $link)) {
  2244. $output = TRUE;
  2245. }
  2246. $setDBinit = t3lib_div::trimExplode(chr(10), $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'], 1);
  2247. foreach ($setDBinit as $v) {
  2248. if (mysql_query($v, $link) === FALSE) {
  2249. t3lib_div::sysLog('Could not initialize DB connection with query "'.$v.'".','Core',3);
  2250. }
  2251. }
  2252. } else {
  2253. t3lib_div::sysLog('Could not connect to MySQL server '.$cfgArray['config']['host'].' with user '.$cfgArray['config']['username'].'.','Core',4);
  2254. }
  2255. break;
  2256. case 'adodb':
  2257. $output = TRUE;
  2258. require_once(t3lib_extMgm::extPath('adodb').'adodb/adodb.inc.php');
  2259. if (!defined('ADODB_FORCE_NULLS')) define('ADODB_FORCE_NULLS', 1);
  2260. $GLOBALS['ADODB_FORCE_TYPE'] = ADODB_FORCE_VALUE;
  2261. $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_BOTH;
  2262. $this->handlerInstance[$handlerKey] = &ADONewConnection($cfgArray['config']['driver']);
  2263. // Set driver-specific options
  2264. if (isset($cfgArray['config']['driverOptions'])) {
  2265. foreach ($cfgArray['config']['driverOptions'] as $optionName => $optionValue) {
  2266. $optionSetterName = 'set' . ucfirst($optionName);
  2267. if (method_exists($this->handlerInstance[$handlerKey], $optionSetterName)) {
  2268. $this->handlerInstance[$handlerKey]->$optionSetterName($optionValue);
  2269. } else {
  2270. $this->handlerInstance[$handlerKey]->$optionName = $optionValue;
  2271. }
  2272. }
  2273. }
  2274. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']) {
  2275. $this->handlerInstance[$handlerKey]->Connect($cfgArray['config']['host'].(isset($cfgArray['config']['port']) ? ':'.$cfgArray['config']['port'] : ''),$cfgArray['config']['username'],$cfgArray['config']['password'],$cfgArray['config']['database']);
  2276. } else {
  2277. $this->handlerInstance[$handlerKey]->PConnect($cfgArray['config']['host'].(isset($cfgArray['config']['port']) ? ':'.$cfgArray['config']['port'] : ''),$cfgArray['config']['username'],$cfgArray['config']['password'],$cfgArray['config']['database']);
  2278. }
  2279. if (!$this->handlerInstance[$handlerKey]->isConnected()) {
  2280. $dsn = $cfgArray['config']['driver'].'://'.$cfgArray['config']['username'].
  2281. (strlen($cfgArray['config']['password']) ? ':XXXX@' : '').
  2282. $cfgArray['config']['host'].(isset($cfgArray['config']['port']) ? ':'.$cfgArray['config']['port'] : '').'/'.$cfgArray['config']['database'].
  2283. ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect'] ? '' : '?persistent=1');
  2284. t3lib_div::sysLog('Could not connect to DB server using ADOdb on '.$cfgArray['config']['host'].' with user '.$cfgArray['config']['username'].'.','Core',4);
  2285. error_log('DBAL error: Connection to '.$dsn.' failed. Maybe PHP doesn\'t support the database?');
  2286. $output = FALSE;
  2287. } else {
  2288. $this->handlerInstance[$handlerKey]->DataDictionary = NewDataDictionary($this->handlerInstance[$handlerKey]);
  2289. $this->handlerInstance[$handlerKey]->last_insert_id = 0;
  2290. if (isset($cfgArray['config']['sequenceStart'])) {
  2291. $this->handlerInstance[$handlerKey]->sequenceStart = $cfgArray['config']['sequenceStart'];
  2292. } else {
  2293. $this->handlerInstance[$handlerKey]->sequenceStart = 1;
  2294. }
  2295. }
  2296. break;
  2297. case 'userdefined':
  2298. // Find class file:
  2299. $fileName = t3lib_div::getFileAbsFileName($cfgArray['config']['classFile']);
  2300. if (@is_file($fileName)) {
  2301. require_once($fileName);
  2302. } else die('DBAL error: "'.$fileName.'" was not a file to include.');
  2303. // Initialize:
  2304. $this->handlerInstance[$handlerKey] = t3lib_div::makeInstance($cfgArray['config']['class']);
  2305. $this->handlerInstance[$handlerKey]->init($cfgArray,$this);
  2306. if (is_object($this->handlerInstance[$handlerKey])) {
  2307. $output = TRUE;
  2308. }
  2309. break;
  2310. default:
  2311. die('ERROR: Invalid handler type: "'.$cfgArray['type'].'"');
  2312. break;
  2313. }
  2314. return $output;
  2315. } else die('ERROR: No handler for key "'.$handlerKey.'"');
  2316. }
  2317. /**
  2318. * Checks if database is connected.
  2319. *
  2320. * @return boolean
  2321. */
  2322. public function isConnected() {
  2323. $result = FALSE;
  2324. switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
  2325. case 'native':
  2326. $result = is_resource($this->link);
  2327. break;
  2328. case 'adodb':
  2329. case 'userdefined':
  2330. $result = is_object($this->handlerInstance[$this->lastHandlerKey]) && $this->handlerInstance[$this->lastHandlerKey]->isConnected();
  2331. break;
  2332. }
  2333. return $result;
  2334. }
  2335. /**
  2336. * Checks whether the DBAL is currently inside an operation running on the "native" DB handler (i.e. MySQL)
  2337. *
  2338. * @return boolean True if running on "native" DB handler (i.e. MySQL)
  2339. */
  2340. public function runningNative() {
  2341. return ((string)$this->handlerCfg[$this->lastHandlerKey]['type']==='native');
  2342. }
  2343. /**
  2344. * Checks whether the ADOdb handler is running with a driver that contains the argument
  2345. *
  2346. * @param string $driver Driver name, matched with strstr().
  2347. * @return boolean True if running with the given driver
  2348. */
  2349. public function runningADOdbDriver($driver) {
  2350. return strstr($this->handlerCfg[$this->lastHandlerKey]['config']['driver'], $driver);
  2351. }
  2352. /************************************
  2353. *
  2354. * Table/Field mapping
  2355. *
  2356. **************************************/
  2357. /**
  2358. * Checks if mapping is needed for a table(list)
  2359. *
  2360. * @param string List of tables in query
  2361. * @param boolean If TRUE, it will check only if FIELDs are configured and ignore the mapped table name if any.
  2362. * @return mixed Returns an array of table names (parsed version of input table) if mapping is needed, otherwise just FALSE.
  2363. */
  2364. protected function map_needMapping($tableList, $fieldMappingOnly = FALSE) {
  2365. $key = $tableList.'|'.$fieldMappingOnly;
  2366. if (!isset($this->cache_mappingFromTableList[$key])) {
  2367. $this->cache_mappingFromTableList[$key] = FALSE; // Default:
  2368. $tables = $this->SQLparser->parseFromTables($tableList);
  2369. if (is_array($tables)) {
  2370. foreach ($tables as $tableCfg) {
  2371. if ($fieldMappingOnly) {
  2372. if (is_array($this->mapping[$tableCfg['table']]['mapFieldNames'])) {
  2373. $this->cache_mappingFromTableList[$key] = $tables;
  2374. } elseif (is_array($tableCfg['JOIN'])) {
  2375. foreach ($tableCfg['JOIN'] as $join) {
  2376. if (is_array($this->mapping[$join['withTable']]['mapFieldNames'])) {
  2377. $this->cache_mappingFromTableList[$key] = $tables;
  2378. break;
  2379. }
  2380. }
  2381. }
  2382. } else {
  2383. if (is_array($this->mapping[$tableCfg['table']])) {
  2384. $this->cache_mappingFromTableList[$key] = $tables;
  2385. } elseif (is_array($tableCfg['JOIN'])) {
  2386. foreach ($tableCfg['JOIN'] as $join) {
  2387. if (is_array($this->mapping[$join['withTable']])) {
  2388. $this->cache_mappingFromTableList[$key] = $tables;
  2389. break;
  2390. }
  2391. }
  2392. }
  2393. }
  2394. }
  2395. }
  2396. }
  2397. return $this->cache_mappingFromTableList[$key];
  2398. }
  2399. /**
  2400. * Takes an associated array with field => value pairs and remaps the field names if configured for this table in $this->mapping array.
  2401. * Be careful not to map a field name to another existing fields name (although you can use this to swap fieldnames of course...:-)
  2402. * Observe mapping problems with join-results (more than one table): Joined queries should always prefix the table name to avoid problems with this.
  2403. * Observe that alias fields are not mapped of course (should not be a problem though)
  2404. *
  2405. * @param array Input array, associative keys
  2406. * @param array Array of tables from the query. Normally just one table; many tables in case of a join. NOTICE: for multiple tables (with joins) there MIGHT occur trouble with fields of the same name in the two tables: This function traverses the mapping information for BOTH tables and applies mapping without checking from which table the field really came!
  2407. * @param boolean If TRUE, reverse direction. Default direction is to map an array going INTO the database (thus mapping TYPO3 fieldnames to PHYSICAL field names!)
  2408. * @return array Output array, with mapped associative keys.
  2409. */
  2410. protected function map_assocArray($input, $tables, $rev = FALSE) {
  2411. // Traverse tables from query (hopefully only one table):
  2412. foreach ($tables as $tableCfg) {
  2413. $tableKey = $this->getMappingKey($tableCfg['table']);
  2414. if (is_array($this->mapping[$tableKey]['mapFieldNames'])) {
  2415. // Get the map (reversed if needed):
  2416. if ($rev) {
  2417. $theMap = array_flip($this->mapping[$tableKey]['mapFieldNames']);
  2418. } else {
  2419. $theMap = $this->mapping[$tableKey]['mapFieldNames'];
  2420. }
  2421. // Traverse selected record, map fieldnames:
  2422. $output = array();
  2423. foreach ($input as $fN => $value) {
  2424. // Set the field name, change it if found in mapping array:
  2425. if ($theMap[$fN]) {
  2426. $newKey = $theMap[$fN];
  2427. } else {
  2428. $newKey = $fN;
  2429. }
  2430. // Set value to fieldname:
  2431. $output[$newKey] = $value;
  2432. }
  2433. // When done, override the $input array with the result:
  2434. $input = $output;
  2435. }
  2436. }
  2437. // Return input array (which might have been altered in the mean time)
  2438. return $input;
  2439. }
  2440. /**
  2441. * Remaps table/field names in a SELECT query's parts
  2442. * Notice: All arguments are passed by reference!
  2443. *
  2444. * @param string List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
  2445. * @param string Table(s) from which to select. This is what comes right after "FROM ...". Require value.
  2446. * @param string Where clause. This is what comes right after "WHERE ...". Can be blank.
  2447. * @param string Group by field(s)
  2448. * @param string Order by field(s)
  2449. * @return void
  2450. * @see exec_SELECTquery()
  2451. */
  2452. protected function map_remapSELECTQueryParts(&$select_fields, &$from_table, &$where_clause, &$groupBy, &$orderBy) {
  2453. // Backup current mapping as it may be altered if aliases on mapped tables are found
  2454. $backupMapping = $this->mapping;
  2455. // Tables:
  2456. $tables = $this->SQLparser->parseFromTables($from_table);
  2457. $defaultTable = $tables[0]['table'];
  2458. // Prepare mapping for aliased tables. This will copy the definition of the original table name.
  2459. // The alias is prefixed with a database-incompatible character to prevent naming clash with real table name
  2460. // Further access to $this->mapping should be made through $this->getMappingKey() method
  2461. foreach ($tables as $k => $v) {
  2462. if ($v['as'] && is_array($this->mapping[$v['table']]['mapFieldNames'])) {
  2463. $mappingKey = $this->getFreeMappingKey($v['as']);
  2464. $this->mapping[$mappingKey]['mapFieldNames'] =& $this->mapping[$v['table']]['mapFieldNames'];
  2465. }
  2466. if (is_array($v['JOIN'])) {
  2467. foreach ($v['JOIN'] as $joinCnt => $join) {
  2468. if ($join['as'] && is_array($this->mapping[$join['withTable']]['mapFieldNames'])) {
  2469. $mappingKey = $this->getFreeMappingKey($join['as']);
  2470. $this->mapping[$mappingKey]['mapFieldNames'] =& $this->mapping[$join['withTable']]['mapFieldNames'];
  2471. }
  2472. }
  2473. }
  2474. }
  2475. foreach ($tables as $k => $v) {
  2476. $tableKey = $this->getMappingKey($v['table']);
  2477. if ($this->mapping[$tableKey]['mapTableName']) {
  2478. $tables[$k]['table'] = $this->mapping[$tableKey]['mapTableName'];
  2479. }
  2480. // Mapping JOINS
  2481. if (is_array($v['JOIN'])) {
  2482. foreach($v['JOIN'] as $joinCnt => $join) {
  2483. // Mapping withTable of the JOIN
  2484. $withTableKey = $this->getMappingKey($join['withTable']);
  2485. if ($this->mapping[$withTableKey]['mapTableName']) {
  2486. $tables[$k]['JOIN'][$joinCnt]['withTable'] = $this->mapping[$withTableKey]['mapTableName'];
  2487. }
  2488. $onPartsArray = array();
  2489. // Mapping ON parts of the JOIN
  2490. if (is_array($tables[$k]['JOIN'][$joinCnt]['ON'])) {
  2491. foreach ($tables[$k]['JOIN'][$joinCnt]['ON'] as &$condition) {
  2492. // Left side of the comparator
  2493. $leftTableKey = $this->getMappingKey($condition['left']['table']);
  2494. if (isset($this->mapping[$leftTableKey]['mapFieldNames'][$condition['left']['field']])) {
  2495. $condition['left']['field'] = $this->mapping[$leftTableKey]['mapFieldNames'][$condition['left']['field']];
  2496. }
  2497. if (isset($this->mapping[$leftTableKey]['mapTableName'])) {
  2498. $condition['left']['table'] = $this->mapping[$leftTableKey]['mapTableName'];
  2499. }
  2500. // Right side of the comparator
  2501. $rightTableKey = $this->getMappingKey($condition['right']['table']);
  2502. if (isset($this->mapping[$rightTableKey]['mapFieldNames'][$condition['right']['field']])) {
  2503. $condition['right']['field'] = $this->mapping[$rightTableKey]['mapFieldNames'][$condition['right']['field']];
  2504. }
  2505. if (isset($this->mapping[$rightTableKey]['mapTableName'])) {
  2506. $condition['right']['table'] = $this->mapping[$rightTableKey]['mapTableName'];
  2507. }
  2508. }
  2509. }
  2510. }
  2511. }
  2512. }
  2513. $from_table = $this->SQLparser->compileFromTables($tables);
  2514. // Where clause:
  2515. $whereParts = $this->SQLparser->parseWhereClause($where_clause);
  2516. $this->map_sqlParts($whereParts,$defaultTable);
  2517. $where_clause = $this->SQLparser->compileWhereClause($whereParts, FALSE);
  2518. // Select fields:
  2519. $expFields = $this->SQLparser->parseFieldList($select_fields);
  2520. $this->map_sqlParts($expFields,$defaultTable);
  2521. $select_fields = $this->SQLparser->compileFieldList($expFields, FALSE, FALSE);
  2522. // Group By fields
  2523. $expFields = $this->SQLparser->parseFieldList($groupBy);
  2524. $this->map_sqlParts($expFields,$defaultTable);
  2525. $groupBy = $this->SQLparser->compileFieldList($expFields);
  2526. // Order By fields
  2527. $expFields = $this->SQLparser->parseFieldList($orderBy);
  2528. $this->map_sqlParts($expFields,$defaultTable);
  2529. $orderBy = $this->SQLparser->compileFieldList($expFields);
  2530. // Restore the original mapping
  2531. $this->mapping = $backupMapping;
  2532. }
  2533. /**
  2534. * Returns the key to be used when retrieving information from $this->mapping. This ensures
  2535. * that mapping from aliased tables is properly retrieved.
  2536. *
  2537. * @param string $tableName
  2538. * @return string
  2539. */
  2540. protected function getMappingKey($tableName) {
  2541. // Search deepest alias mapping
  2542. while (isset($this->mapping['*' . $tableName])) {
  2543. $tableName = '*' . $tableName;
  2544. }
  2545. return $tableName;
  2546. }
  2547. /**
  2548. * Returns a free key to be used to store mapping information in $this->mapping.
  2549. *
  2550. * @param string $tableName
  2551. * @return string
  2552. */
  2553. protected function getFreeMappingKey($tableName) {
  2554. while (isset($this->mapping[$tableName])) {
  2555. $tableName = '*' . $tableName;
  2556. }
  2557. return $tableName;
  2558. }
  2559. /**
  2560. * Generic mapping of table/field names arrays (as parsed by tx_dbal_sqlengine)
  2561. *
  2562. * @param array Array with parsed SQL parts; Takes both fields, tables, where-parts, group and order-by. Passed by reference.
  2563. * @param string Default table name to assume if no table is found in $sqlPartArray
  2564. * @return void
  2565. * @access private
  2566. * @see map_remapSELECTQueryParts()
  2567. */
  2568. protected function map_sqlParts(&$sqlPartArray, $defaultTable) {
  2569. $defaultTableKey = $this->getMappingKey($defaultTable);
  2570. // Traverse sql Part array:
  2571. if (is_array($sqlPartArray)) {
  2572. foreach ($sqlPartArray as $k => $v) {
  2573. if (isset($sqlPartArray[$k]['type'])) {
  2574. switch ($sqlPartArray[$k]['type']) {
  2575. case 'flow-control':
  2576. $temp = array($sqlPartArray[$k]['flow-control']);
  2577. $this->map_sqlParts($temp, $defaultTable); // Call recursively!
  2578. $sqlPartArray[$k]['flow-control'] = $temp[0];
  2579. break;
  2580. case 'CASE':
  2581. if (isset($sqlPartArray[$k]['case_field'])) {
  2582. $fieldArray = explode('.', $sqlPartArray[$k]['case_field']);
  2583. if (count($fieldArray) == 1 && is_array($this->mapping[$defaultTableKey]['mapFieldNames']) && isset($this->mapping[$defaultTableKey]['mapFieldNames'][$fieldArray[0]])) {
  2584. $sqlPartArray[$k]['case_field'] = $this->mapping[$defaultTableKey]['mapFieldNames'][$fieldArray[0]];
  2585. }
  2586. elseif (count($fieldArray) == 2) {
  2587. // Map the external table
  2588. $table = $fieldArray[0];
  2589. $tableKey = $this->getMappingKey($table);
  2590. if (isset($this->mapping[$tableKey]['mapTableName'])) {
  2591. $table = $this->mapping[$tableKey]['mapTableName'];
  2592. }
  2593. // Map the field itself
  2594. $field = $fieldArray[1];
  2595. if (is_array($this->mapping[$tableKey]['mapFieldNames']) && isset($this->mapping[$tableKey]['mapFieldNames'][$fieldArray[1]])) {
  2596. $field = $this->mapping[$tableKey]['mapFieldNames'][$fieldArray[1]];
  2597. }
  2598. $sqlPartArray[$k]['case_field'] = $table . '.' . $field;
  2599. }
  2600. }
  2601. foreach ($sqlPartArray[$k]['when'] as $key => $when) {
  2602. $this->map_sqlParts($sqlPartArray[$k]['when'][$key]['when_value'], $defaultTable);
  2603. }
  2604. break;
  2605. }
  2606. }
  2607. // Look for sublevel (WHERE parts only)
  2608. if (is_array($sqlPartArray[$k]['sub'])) {
  2609. $this->map_sqlParts($sqlPartArray[$k]['sub'], $defaultTable); // Call recursively!
  2610. } elseif (isset($sqlPartArray[$k]['func'])) {
  2611. switch ($sqlPartArray[$k]['func']['type']) {
  2612. case 'EXISTS':
  2613. $this->map_subquery($sqlPartArray[$k]['func']['subquery']);
  2614. break;
  2615. case 'IFNULL':
  2616. case 'LOCATE':
  2617. // For the field, look for table mapping (generic):
  2618. $t = $sqlPartArray[$k]['func']['table'] ? $sqlPartArray[$k]['func']['table'] : $defaultTable;
  2619. $t = $this->getMappingKey($t);
  2620. if (is_array($this->mapping[$t]['mapFieldNames']) && $this->mapping[$t]['mapFieldNames'][$sqlPartArray[$k]['func']['field']]) {
  2621. $sqlPartArray[$k]['func']['field'] = $this->mapping[$t]['mapFieldNames'][$sqlPartArray[$k]['func']['field']];
  2622. }
  2623. if ($this->mapping[$t]['mapTableName']) {
  2624. $sqlPartArray[$k]['func']['table'] = $this->mapping[$t]['mapTableName'];
  2625. }
  2626. break;
  2627. }
  2628. } else {
  2629. // For the field, look for table mapping (generic):
  2630. $t = $sqlPartArray[$k]['table'] ? $sqlPartArray[$k]['table'] : $defaultTable;
  2631. $t = $this->getMappingKey($t);
  2632. // Mapping field name, if set:
  2633. if (is_array($this->mapping[$t]['mapFieldNames']) && isset($this->mapping[$t]['mapFieldNames'][$sqlPartArray[$k]['field']])) {
  2634. $sqlPartArray[$k]['field'] = $this->mapping[$t]['mapFieldNames'][$sqlPartArray[$k]['field']];
  2635. }
  2636. // Mapping field name in SQL-functions like MIN(), MAX() or SUM()
  2637. if ($this->mapping[$t]['mapFieldNames']) {
  2638. $fieldArray = explode('.', $sqlPartArray[$k]['func_content']);
  2639. if (count($fieldArray) == 1 && is_array($this->mapping[$t]['mapFieldNames']) && isset($this->mapping[$t]['mapFieldNames'][$fieldArray[0]])) {
  2640. $sqlPartArray[$k]['func_content.'][0]['func_content'] = $this->mapping[$t]['mapFieldNames'][$fieldArray[0]];
  2641. $sqlPartArray[$k]['func_content'] = $this->mapping[$t]['mapFieldNames'][$fieldArray[0]];
  2642. }
  2643. elseif (count($fieldArray) == 2) {
  2644. // Map the external table
  2645. $table = $fieldArray[0];
  2646. $tableKey = $this->getMappingKey($table);
  2647. if (isset($this->mapping[$tableKey]['mapTableName'])) {
  2648. $table = $this->mapping[$tableKey]['mapTableName'];
  2649. }
  2650. // Map the field itself
  2651. $field = $fieldArray[1];
  2652. if (is_array($this->mapping[$tableKey]['mapFieldNames']) && isset($this->mapping[$tableKey]['mapFieldNames'][$fieldArray[1]])) {
  2653. $field = $this->mapping[$tableKey]['mapFieldNames'][$fieldArray[1]];
  2654. }
  2655. $sqlPartArray[$k]['func_content.'][0]['func_content'] = $table . '.' . $field;
  2656. $sqlPartArray[$k]['func_content'] = $table . '.' . $field;
  2657. }
  2658. // Mapping flow-control statements
  2659. if (isset($sqlPartArray[$k]['flow-control'])) {
  2660. if (isset($sqlPartArray[$k]['flow-control']['type'])) {
  2661. $temp = array($sqlPartArray[$k]['flow-control']);
  2662. $this->map_sqlParts($temp, $t); // Call recursively!
  2663. $sqlPartArray[$k]['flow-control'] = $temp[0];
  2664. }
  2665. }
  2666. }
  2667. // Do we have a function (e.g., CONCAT)
  2668. if (isset($v['value']['operator'])) {
  2669. foreach ($sqlPartArray[$k]['value']['args'] as $argK => $fieldDef) {
  2670. $tableKey = $this->getMappingKey($fieldDef['table']);
  2671. if (isset($this->mapping[$tableKey]['mapTableName'])) {
  2672. $sqlPartArray[$k]['value']['args'][$argK]['table'] = $this->mapping[$tableKey]['mapTableName'];
  2673. }
  2674. if (is_array($this->mapping[$tableKey]['mapFieldNames']) && isset($this->mapping[$tableKey]['mapFieldNames'][$fieldDef['field']])) {
  2675. $sqlPartArray[$k]['value']['args'][$argK]['field'] = $this->mapping[$tableKey]['mapFieldNames'][$fieldDef['field']];
  2676. }
  2677. }
  2678. }
  2679. // Do we have a subquery (WHERE parts only)?
  2680. if (isset($sqlPartArray[$k]['subquery'])) {
  2681. $this->map_subquery($sqlPartArray[$k]['subquery']);
  2682. }
  2683. // do we have a field name in the value?
  2684. // this is a very simplistic check, beware
  2685. if (!is_numeric($sqlPartArray[$k]['value'][0]) && !isset($sqlPartArray[$k]['value'][1])) {
  2686. $fieldArray = explode('.', $sqlPartArray[$k]['value'][0]);
  2687. if (count($fieldArray) == 1 && is_array($this->mapping[$t]['mapFieldNames']) && isset($this->mapping[$t]['mapFieldNames'][$fieldArray[0]])) {
  2688. $sqlPartArray[$k]['value'][0] = $this->mapping[$t]['mapFieldNames'][$fieldArray[0]];
  2689. } elseif (count($fieldArray) == 2) {
  2690. // Map the external table
  2691. $table = $fieldArray[0];
  2692. $tableKey = $this->getMappingKey($table);
  2693. if (isset($this->mapping[$tableKey]['mapTableName'])) {
  2694. $table = $this->mapping[$tableKey]['mapTableName'];
  2695. }
  2696. // Map the field itself
  2697. $field = $fieldArray[1];
  2698. if (is_array($this->mapping[$tableKey]['mapFieldNames']) && isset($this->mapping[$tableKey]['mapFieldNames'][$fieldArray[1]])) {
  2699. $field = $this->mapping[$tableKey]['mapFieldNames'][$fieldArray[1]];
  2700. }
  2701. $sqlPartArray[$k]['value'][0] = $table . '.' . $field;
  2702. }
  2703. }
  2704. // Map table?
  2705. $tableKey = $this->getMappingKey($sqlPartArray[$k]['table']);
  2706. if ($sqlPartArray[$k]['table'] && $this->mapping[$tableKey]['mapTableName']) {
  2707. $sqlPartArray[$k]['table'] = $this->mapping[$tableKey]['mapTableName'];
  2708. }
  2709. }
  2710. }
  2711. }
  2712. }
  2713. /**
  2714. * Maps table and field names in a subquery.
  2715. *
  2716. * @param array $parsedQuery
  2717. * @return void
  2718. */
  2719. protected function map_subquery(&$parsedQuery) {
  2720. // Backup current mapping as it may be altered
  2721. $backupMapping = $this->mapping;
  2722. foreach ($parsedQuery['FROM'] as $k => $v) {
  2723. $mappingKey = $v['table'];
  2724. if ($v['as'] && is_array($this->mapping[$v['table']]['mapFieldNames'])) {
  2725. $mappingKey = $this->getFreeMappingKey($v['as']);
  2726. } else {
  2727. // Should ensure that no alias is defined in the external query
  2728. // which would correspond to a real table name in the subquery
  2729. if ($this->getMappingKey($v['table']) !== $v['table']) {
  2730. $mappingKey = $this->getFreeMappingKey($v['table']);
  2731. // This is the only case when 'mapTableName' should be copied
  2732. $this->mapping[$mappingKey]['mapTableName'] =& $this->mapping[$v['table']]['mapTableName'];
  2733. }
  2734. }
  2735. if ($mapping !== $v['table']) {
  2736. $this->mapping[$mappingKey]['mapFieldNames'] =& $this->mapping[$v['table']]['mapFieldNames'];
  2737. }
  2738. }
  2739. // Perform subquery's remapping
  2740. $defaultTable = $parsedQuery['FROM'][0]['table'];
  2741. $this->map_sqlParts($parsedQuery['SELECT'], $defaultTable);
  2742. $this->map_sqlParts($parsedQuery['FROM'], $defaultTable);
  2743. $this->map_sqlParts($parsedQuery['WHERE'], $defaultTable);
  2744. // Restore the mapping
  2745. $this->mapping = $backupMapping;
  2746. }
  2747. /**
  2748. * Will do table/field mapping on a general tx_dbal_sqlengine-compliant SQL query
  2749. * (May still not support all query types...)
  2750. *
  2751. * @param array Parsed QUERY as from tx_dbal_sqlengine::parseSQL(). NOTICE: Passed by reference!
  2752. * @return void
  2753. * @see tx_dbal_sqlengine::parseSQL()
  2754. */
  2755. protected function map_genericQueryParsed(&$parsedQuery) {
  2756. // Getting table - same for all:
  2757. $table = $parsedQuery['TABLE'];
  2758. if ($table) {
  2759. // Do field mapping if needed:
  2760. if ($tableArray = $this->map_needMapping($table)) {
  2761. // Table name:
  2762. if ($this->mapping[$table]['mapTableName']) {
  2763. $parsedQuery['TABLE'] = $this->mapping[$table]['mapTableName'];
  2764. }
  2765. // Based on type, do additional changes:
  2766. switch ($parsedQuery['type']) {
  2767. case 'ALTERTABLE':
  2768. // Changing field name:
  2769. $newFieldName = $this->mapping[$table]['mapFieldNames'][$parsedQuery['FIELD']];
  2770. if ($newFieldName) {
  2771. if ($parsedQuery['FIELD'] == $parsedQuery['newField']) {
  2772. $parsedQuery['FIELD'] = $parsedQuery['newField'] = $newFieldName;
  2773. } else $parsedQuery['FIELD'] = $newFieldName;
  2774. }
  2775. // Changing key field names:
  2776. if (is_array($parsedQuery['fields'])) {
  2777. $this->map_fieldNamesInArray($table,$parsedQuery['fields']);
  2778. }
  2779. break;
  2780. case 'CREATETABLE':
  2781. // Remapping fields:
  2782. if (is_array($parsedQuery['FIELDS'])) {
  2783. $newFieldsArray = array();
  2784. foreach ($parsedQuery['FIELDS'] as $fN => $fInfo) {
  2785. if ($this->mapping[$table]['mapFieldNames'][$fN]) {
  2786. $fN = $this->mapping[$table]['mapFieldNames'][$fN];
  2787. }
  2788. $newFieldsArray[$fN] = $fInfo;
  2789. }
  2790. $parsedQuery['FIELDS'] = $newFieldsArray;
  2791. }
  2792. // Remapping keys:
  2793. if (is_array($parsedQuery['KEYS'])) {
  2794. foreach ($parsedQuery['KEYS'] as $kN => $kInfo) {
  2795. $this->map_fieldNamesInArray($table,$parsedQuery['KEYS'][$kN]);
  2796. }
  2797. }
  2798. break;
  2799. /// ... and here support for all other query types should be!
  2800. }
  2801. }
  2802. } else die('ERROR, mapping: No table found in parsed Query array...');
  2803. }
  2804. /**
  2805. * Re-mapping field names in array
  2806. *
  2807. * @param string (TYPO3) Table name for fields.
  2808. * @param array Array of fieldnames to remap. Notice: Passed by reference!
  2809. * @return void
  2810. */
  2811. protected function map_fieldNamesInArray($table,&$fieldArray) {
  2812. if (is_array($this->mapping[$table]['mapFieldNames'])) {
  2813. foreach ($fieldArray as $k => $v) {
  2814. if ($this->mapping[$table]['mapFieldNames'][$v]) {
  2815. $fieldArray[$k] = $this->mapping[$table]['mapFieldNames'][$v];
  2816. }
  2817. }
  2818. }
  2819. }
  2820. /**************************************
  2821. *
  2822. * Debugging
  2823. *
  2824. **************************************/
  2825. /**
  2826. * Debug handler for query execution
  2827. *
  2828. * @param string Function name from which this function is called.
  2829. * @param string Execution time in ms of the query
  2830. * @param array In-data of various kinds.
  2831. * @return void
  2832. * @access private
  2833. */
  2834. public function debugHandler($function,$execTime,$inData) {
  2835. // we don't want to log our own log/debug SQL
  2836. $script = substr(PATH_thisScript,strlen(PATH_site));
  2837. if (substr($script,-strlen('dbal/mod1/index.php'))!='dbal/mod1/index.php' && !strstr($inData['args'][0], 'tx_dbal_debuglog')) {
  2838. $data = array();
  2839. $errorFlag = 0;
  2840. $joinTable = '';
  2841. if ($this->sql_error()) {
  2842. $data['sqlError'] = $this->sql_error();
  2843. $errorFlag|=1;
  2844. }
  2845. // if lastQuery is empty (for whatever reason) at least log inData.args
  2846. if (empty($this->lastQuery))
  2847. $query = implode(' ',$inData['args']);
  2848. else
  2849. $query = $this->lastQuery;
  2850. if ($this->conf['debugOptions']['backtrace']) {
  2851. $backtrace = debug_backtrace();
  2852. unset($backtrace[0]); // skip this very method :)
  2853. $data['backtrace'] = array_slice($backtrace, 0, $this->conf['debugOptions']['backtrace']);
  2854. }
  2855. switch ($function) {
  2856. case 'exec_INSERTquery':
  2857. case 'exec_UPDATEquery':
  2858. case 'exec_DELETEquery':
  2859. $this->debug_log($query,$execTime,$data,$joinTable,$errorFlag, $script);
  2860. break;
  2861. case 'exec_SELECTquery':
  2862. // Get explain data:
  2863. if ($this->conf['debugOptions']['EXPLAIN'] && t3lib_div::inList('adodb,native',$inData['handlerType'])) {
  2864. $data['EXPLAIN'] = $this->debug_explain($this->lastQuery);
  2865. }
  2866. // Check parsing of Query:
  2867. if ($this->conf['debugOptions']['parseQuery']) {
  2868. $parseResults = array();
  2869. $parseResults['SELECT'] = $this->SQLparser->debug_parseSQLpart('SELECT',$inData['args'][1]);
  2870. $parseResults['FROM'] = $this->SQLparser->debug_parseSQLpart('FROM',$inData['args'][0]);
  2871. $parseResults['WHERE'] = $this->SQLparser->debug_parseSQLpart('WHERE',$inData['args'][2]);
  2872. $parseResults['GROUPBY'] = $this->SQLparser->debug_parseSQLpart('SELECT',$inData['args'][3]); // Using select field list syntax
  2873. $parseResults['ORDERBY'] = $this->SQLparser->debug_parseSQLpart('SELECT',$inData['args'][4]); // Using select field list syntax
  2874. foreach ($parseResults as $k => $v) {
  2875. if (!strlen($parseResults[$k])) unset($parseResults[$k]);
  2876. }
  2877. if (count($parseResults)) {
  2878. $data['parseError'] = $parseResults;
  2879. $errorFlag|=2;
  2880. }
  2881. }
  2882. // Checking joinTables:
  2883. if ($this->conf['debugOptions']['joinTables']) {
  2884. if (count(explode(',', $inData['ORIG_from_table']))>1) {
  2885. $joinTable = $inData['args'][0];
  2886. }
  2887. }
  2888. // Logging it:
  2889. $this->debug_log($query,$execTime,$data,$joinTable,$errorFlag, $script);
  2890. if (!empty($inData['args'][2]))
  2891. $this->debug_WHERE($inData['args'][0], $inData['args'][2], $script);
  2892. break;
  2893. }
  2894. }
  2895. }
  2896. /**
  2897. * Logs the where clause for debugging purposes.
  2898. *
  2899. * @param string $table Table name(s) the query was targeted at
  2900. * @param string $where The WHERE clause to be logged
  2901. * @param string $script The script calling the logging
  2902. * @return void
  2903. */
  2904. public function debug_WHERE($table, $where, $script = '') {
  2905. $insertArray = array (
  2906. 'tstamp' => $GLOBALS['EXEC_TIME'],
  2907. 'beuser_id' => intval($GLOBALS['BE_USER']->user['uid']),
  2908. 'script' => $script,
  2909. 'tablename' => $table,
  2910. 'whereclause' => $where
  2911. );
  2912. $this->exec_INSERTquery('tx_dbal_debuglog_where', $insertArray);
  2913. }
  2914. /**
  2915. * Inserts row in the log table
  2916. *
  2917. * @param string The current query
  2918. * @param integer Execution time of query in milliseconds
  2919. * @param array Data to be stored serialized.
  2920. * @param string Join string if there IS a join.
  2921. * @param integer Error status.
  2922. * @param string $script The script calling the logging
  2923. * @return void
  2924. */
  2925. public function debug_log($query,$ms,$data,$join,$errorFlag, $script='') {
  2926. if (is_array($query)) {
  2927. $queryToLog = $query[0].' -- ';
  2928. if (count($query[1])) {
  2929. $queryToLog .= count($query[1]).' BLOB FIELDS: '.implode(', ',array_keys($query[1]));
  2930. }
  2931. if (count($query[2])) {
  2932. $queryToLog .= count($query[2]).' CLOB FIELDS: '.implode(', ',array_keys($query[2]));
  2933. }
  2934. } else {
  2935. $queryToLog = $query;
  2936. }
  2937. $insertArray = array (
  2938. 'tstamp' => $GLOBALS['EXEC_TIME'],
  2939. 'beuser_id' => intval($GLOBALS['BE_USER']->user['uid']),
  2940. 'script' => $script,
  2941. 'exec_time' => $ms,
  2942. 'table_join' => $join,
  2943. 'serdata' => serialize($data),
  2944. 'query' => $queryToLog,
  2945. 'errorFlag' => $errorFlag
  2946. );
  2947. $this->exec_INSERTquery('tx_dbal_debuglog', $insertArray);
  2948. }
  2949. /**
  2950. * Perform EXPLAIN query on DEFAULT handler!
  2951. *
  2952. * @param string SELECT Query
  2953. * @return array The Explain result rows in an array
  2954. * @todo Not supporting other than the default handler? And what about DBMS of other kinds than MySQL - support for EXPLAIN?
  2955. */
  2956. public function debug_explain($query) {
  2957. $output = array();
  2958. $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
  2959. switch ($hType) {
  2960. case 'native':
  2961. $res = $this->sql_query('EXPLAIN '.$query);
  2962. while($row = $this->sql_fetch_assoc($res)) {
  2963. $output[] = $row;
  2964. }
  2965. break;
  2966. case 'adodb':
  2967. switch ($this->handlerCfg['_DEFAULT']['config']['driver']) {
  2968. case 'oci8':
  2969. $res = $this->sql_query('EXPLAIN PLAN '.$query);
  2970. $output[] = 'EXPLAIN PLAN data logged to default PLAN_TABLE';
  2971. break;
  2972. default:
  2973. $res = $this->sql_query('EXPLAIN '.$query);
  2974. while($row = $this->sql_fetch_assoc($res)) {
  2975. $output[] = $row;
  2976. }
  2977. break;
  2978. }
  2979. break;
  2980. }
  2981. return $output;
  2982. }
  2983. }
  2984. if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/dbal/class.ux_t3lib_db.php']) {
  2985. include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/dbal/class.ux_t3lib_db.php']);
  2986. }
  2987. ?>