1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
|
<?php
/***************************************************************
* Copyright notice
*
* (c) 2004-2006 Kasper Skaarhoj (kasperYYYY@typo3.com)
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
* A copy is found in the textfile GPL.txt and important notices to the license
* from the author is found in LICENSE.txt distributed with these scripts.
*
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* Contains the class "t3lib_db" containing functions for building SQL queries and mysql wrappers, thus providing a foundational API to all database interaction.
* This class is instantiated globally as $TYPO3_DB in TYPO3 scripts.
*
* $Id: class.t3lib_db.php 1443 2006-04-20 09:00:43Z masi $
*
* @author Kasper Skaarhoj <kasperYYYY@typo3.com>
*/
/**
* [CLASS/FUNCTION INDEX of SCRIPT]
*
*
*
* 138: class t3lib_DB
*
* SECTION: Query execution
* 175: function exec_INSERTquery($table,$fields_values,$no_quote_fields=FALSE)
* 192: function exec_UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE)
* 206: function exec_DELETEquery($table,$where)
* 225: function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')
* 250: function exec_SELECT_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')
* 278: function exec_SELECT_queryArray($queryParts)
* 301: function exec_SELECTgetRows($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='',$uidIndexField='')
*
* SECTION: Query building
* 346: function INSERTquery($table,$fields_values,$no_quote_fields=FALSE)
* 381: function UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE)
* 422: function DELETEquery($table,$where)
* 451: function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')
* 492: function listQuery($field, $value, $table)
* 506: function searchQuery($searchWords,$fields,$table)
*
* SECTION: Various helper functions
* 552: function fullQuoteStr($str, $table)
* 569: function fullQuoteArray($arr, $table, $noQuote=FALSE)
* 596: function quoteStr($str, $table)
* 612: function escapeStrForLike($str, $table)
* 625: function cleanIntArray($arr)
* 641: function cleanIntList($list)
* 655: function stripOrderBy($str)
* 669: function stripGroupBy($str)
* 681: function splitGroupOrderLimit($str)
*
* SECTION: MySQL wrapper functions
* 749: function sql($db,$query)
* 763: function sql_query($query)
* 776: function sql_error()
* 788: function sql_num_rows($res)
* 800: function sql_fetch_assoc($res)
* 813: function sql_fetch_row($res)
* 825: function sql_free_result($res)
* 836: function sql_insert_id()
* 847: function sql_affected_rows()
* 860: function sql_data_seek($res,$seek)
* 873: function sql_field_type($res,$pointer)
* 887: function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password)
* 915: function sql_select_db($TYPO3_db)
*
* SECTION: SQL admin functions
* 947: function admin_get_dbs()
* 965: function admin_get_tables()
* 984: function admin_get_fields($tableName)
* 1002: function admin_get_keys($tableName)
* 1020: function admin_query($query)
*
* SECTION: Connecting service
* 1048: function connectDB()
*
* SECTION: Debugging
* 1086: function debug($func)
*
* TOTAL FUNCTIONS: 42
* (This index is automatically created/updated by the extension "extdeveval")
*
*/
/**
* TYPO3 "database wrapper" class (new in 3.6.0)
* This class contains
* - abstraction functions for executing INSERT/UPDATE/DELETE/SELECT queries ("Query execution"; These are REQUIRED for all future connectivity to the database, thus ensuring DBAL compliance!)
* - functions for building SQL queries (INSERT/UPDATE/DELETE/SELECT) ("Query building"); These are transitional functions for building SQL queries in a more automated way. Use these to build queries instead of doing it manually in your code!
* - mysql() wrapper functions; These are transitional functions. By a simple search/replace you should be able to substitute all mysql*() calls with $GLOBALS['TYPO3_DB']->sql*() and your application will work out of the box. YOU CANNOT (legally) use any mysql functions not found as wrapper functions in this class!
* See the Project Coding Guidelines (doc_core_cgl) for more instructions on best-practise
*
* This class is not in itself a complete database abstraction layer but can be extended to be a DBAL (by extensions, see "dbal" for example)
* ALL connectivity to the database in TYPO3 must be done through this class!
* The points of this class are:
* - To direct all database calls through this class so it becomes possible to implement DBAL with extensions.
* - To keep it very easy to use for developers used to MySQL in PHP - and preserve as much performance as possible when TYPO3 is used with MySQL directly...
* - To create an interface for DBAL implemented by extensions; (Eg. making possible escaping characters, clob/blob handling, reserved words handling)
* - Benchmarking the DB bottleneck queries will become much easier; Will make it easier to find optimization possibilities.
*
* USE:
* In all TYPO3 scripts the global variable $TYPO3_DB is an instance of this class. Use that.
* Eg. $GLOBALS['TYPO3_DB']->sql_fetch_assoc()
*
* @author Kasper Skaarhoj <kasperYYYY@typo3.com>
* @package TYPO3
* @subpackage t3lib
*/
class t3lib_DB {
// Debug:
var $debugOutput = FALSE; // Set "TRUE" if you want database errors outputted.
var $debug_lastBuiltQuery = ''; // Internally: Set to last built query (not necessarily executed...)
var $store_lastBuiltQuery = FALSE; // Set "TRUE" if you want the last built query to be stored in $debug_lastBuiltQuery independent of $this->debugOutput
// Default link identifier:
var $link = FALSE;
/************************************
*
* Query execution
*
* These functions are the RECOMMENDED DBAL functions for use in your applications
* Using these functions will allow the DBAL to use alternative ways of accessing data (contrary to if a query is returned!)
* They compile a query AND execute it immediately and then return the result
* This principle heightens our ability to create various forms of DBAL of the functions.
* Generally: We want to return a result pointer/object, never queries.
* Also, having the table name together with the actual query execution allows us to direct the request to other databases.
*
**************************************/
/**
* Creates and executes an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
* Using this function specifically allows us to handle BLOB and CLOB fields depending on DB
* Usage count/core: 47
*
* @param string Table name
* @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.
* @param string/array See fullQuoteArray()
* @return pointer MySQL result pointer / DBAL object
*/
function exec_INSERTquery($table,$fields_values,$no_quote_fields=FALSE) {
$res = mysql_query($this->INSERTquery($table,$fields_values,$no_quote_fields), $this->link);
if ($this->debugOutput) $this->debug('exec_INSERTquery');
return $res;
}
/**
* Creates and executes an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
* Using this function specifically allow us to handle BLOB and CLOB fields depending on DB
* Usage count/core: 50
*
* @param string Database tablename
* @param string WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
* @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.
* @param string/array See fullQuoteArray()
* @return pointer MySQL result pointer / DBAL object
*/
function exec_UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE) {
$res = mysql_query($this->UPDATEquery($table,$where,$fields_values,$no_quote_fields), $this->link);
if ($this->debugOutput) $this->debug('exec_UPDATEquery');
return $res;
}
/**
* Creates and executes a DELETE SQL-statement for $table where $where-clause
* Usage count/core: 40
*
* @param string Database tablename
* @param string WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
* @return pointer MySQL result pointer / DBAL object
*/
function exec_DELETEquery($table,$where) {
$res = mysql_query($this->DELETEquery($table,$where), $this->link);
if ($this->debugOutput) $this->debug('exec_DELETEquery');
return $res;
}
/**
* Creates and executes a SELECT SQL-statement
* Using this function specifically allow us to handle the LIMIT feature independently of DB.
* Usage count/core: 340
*
* @param string List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
* @param string Table(s) from which to select. This is what comes right after "FROM ...". Required value.
* @param string Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself! DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
* @param string Optional GROUP BY field(s), if none, supply blank string.
* @param string Optional ORDER BY field(s), if none, supply blank string.
* @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
* @return pointer MySQL result pointer / DBAL object
*/
function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='') {
$res = mysql_query($this->SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit), $this->link);
if ($this->debugOutput) $this->debug('exec_SELECTquery');
return $res;
}
/**
* Creates and executes a SELECT query, selecting fields ($select) from two/three tables joined
* Use $mm_table together with $local_table or $foreign_table to select over two tables. Or use all three tables to select the full MM-relation.
* The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local / [$mm_table].uid_foreign <--> [$foreign_table].uid
* The function is very useful for selecting MM-relations between tables adhering to the MM-format used by TCE (TYPO3 Core Engine). See the section on $TCA in Inside TYPO3 for more details.
*
* Usage: 12 (spec. ext. sys_action, sys_messages, sys_todos)
*
* @param string Field list for SELECT
* @param string Tablename, local table
* @param string Tablename, relation table
* @param string Tablename, foreign table
* @param string Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself! DO NOT PUT IN GROUP BY, ORDER BY or LIMIT! You have to prepend 'AND ' to this parameter yourself!
* @param string Optional GROUP BY field(s), if none, supply blank string.
* @param string Optional ORDER BY field(s), if none, supply blank string.
* @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
* @return pointer MySQL result pointer / DBAL object
* @see exec_SELECTquery()
*/
function exec_SELECT_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='') {
if($foreign_table == $local_table) {
$foreign_table_as = $foreign_table.uniqid('_join');
}
$mmWhere = $local_table ? $local_table.'.uid='.$mm_table.'.uid_local' : '';
$mmWhere.= ($local_table AND $foreign_table) ? ' AND ' : '';
$mmWhere.= $foreign_table ? ($foreign_table_as ? $foreign_table_as : $foreign_table).'.uid='.$mm_table.'.uid_foreign' : '';
return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
$select,
($local_table ? $local_table.',' : '').$mm_table.($foreign_table ? ','. $foreign_table.($foreign_table_as ? ' AS '.$foreign_table_as : '') : ''),
$mmWhere.' '.$whereClause, // whereClauseMightContainGroupOrderBy
$groupBy,
$orderBy,
$limit
);
}
/**
* Executes a select based on input query parts array
*
* Usage: 9
*
* @param array Query parts array
* @return pointer MySQL select result pointer / DBAL object
* @see exec_SELECTquery()
*/
function exec_SELECT_queryArray($queryParts) {
return $this->exec_SELECTquery(
$queryParts['SELECT'],
$queryParts['FROM'],
$queryParts['WHERE'],
$queryParts['GROUPBY'],
$queryParts['ORDERBY'],
$queryParts['LIMIT']
);
}
/**
* Creates and executes a SELECT SQL-statement AND traverse result set and returns array with records in.
*
* @param string See exec_SELECTquery()
* @param string See exec_SELECTquery()
* @param string See exec_SELECTquery()
* @param string See exec_SELECTquery()
* @param string See exec_SELECTquery()
* @param string See exec_SELECTquery()
* @param string If set, the result array will carry this field names value as index. Requires that field to be selected of course!
* @return array Array of rows.
*/
function exec_SELECTgetRows($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='',$uidIndexField='') {
$res = $this->exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit);
if ($this->debugOutput) $this->debug('exec_SELECTquery');
if (!$this->sql_error()) {
$output = array();
if ($uidIndexField) {
while($tempRow = $this->sql_fetch_assoc($res)) {
$output[$tempRow[$uidIndexField]] = $tempRow;
}
} else {
while($output[] = $this->sql_fetch_assoc($res));
array_pop($output);
}
}
return $output;
}
/**************************************
*
* Query building
*
**************************************/
/**
* Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
* Usage count/core: 4
*
* @param string See exec_INSERTquery()
* @param array See exec_INSERTquery()
* @param string/array See fullQuoteArray()
* @return string Full SQL query for INSERT (unless $fields_values does not contain any elements in which case it will be false)
* @deprecated use exec_INSERTquery() instead if possible!
*/
function INSERTquery($table,$fields_values,$no_quote_fields=FALSE) {
// Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
if (is_array($fields_values) && count($fields_values)) {
// quote and escape values
$fields_values = $this->fullQuoteArray($fields_values,$table,$no_quote_fields);
// Build query:
$query = 'INSERT INTO '.$table.'
(
'.implode(',
',array_keys($fields_values)).'
) VALUES (
'.implode(',
',$fields_values).'
)';
// Return query:
if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
return $query;
}
}
/**
* Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
* Usage count/core: 6
*
* @param string See exec_UPDATEquery()
* @param string See exec_UPDATEquery()
* @param array See exec_UPDATEquery()
* @param array See fullQuoteArray()
* @return string Full SQL query for UPDATE (unless $fields_values does not contain any elements in which case it will be false)
* @deprecated use exec_UPDATEquery() instead if possible!
*/
function UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE) {
// Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
if (is_string($where)) {
if (is_array($fields_values) && count($fields_values)) {
// quote and escape values
$nArr = $this->fullQuoteArray($fields_values,$table,$no_quote_fields);
$fields = array();
foreach ($nArr as $k => $v) {
$fields[] = $k.'='.$v;
}
// Build query:
$query = 'UPDATE '.$table.'
SET
'.implode(',
',$fields).
(strlen($where)>0 ? '
WHERE
'.$where : '');
// Return query:
if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
return $query;
}
} else {
die('<strong>TYPO3 Fatal Error:</strong> "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !');
}
}
/**
* Creates a DELETE SQL-statement for $table where $where-clause
* Usage count/core: 3
*
* @param string See exec_DELETEquery()
* @param string See exec_DELETEquery()
* @return string Full SQL query for DELETE
* @deprecated use exec_DELETEquery() instead if possible!
*/
function DELETEquery($table,$where) {
if (is_string($where)) {
// Table and fieldnames should be "SQL-injection-safe" when supplied to this function
$query = 'DELETE FROM '.$table.
(strlen($where)>0 ? '
WHERE
'.$where : '');
if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
return $query;
} else {
die('<strong>TYPO3 Fatal Error:</strong> "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !');
}
}
/**
* Creates a SELECT SQL-statement
* Usage count/core: 11
*
* @param string See exec_SELECTquery()
* @param string See exec_SELECTquery()
* @param string See exec_SELECTquery()
* @param string See exec_SELECTquery()
* @param string See exec_SELECTquery()
* @param string See exec_SELECTquery()
* @return string Full SQL query for SELECT
* @deprecated use exec_SELECTquery() instead if possible!
*/
function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='') {
// Table and fieldnames should be "SQL-injection-safe" when supplied to this function
// Build basic query:
$query = 'SELECT '.$select_fields.'
FROM '.$from_table.
(strlen($where_clause)>0 ? '
WHERE
'.$where_clause : '');
// Group by:
if (strlen($groupBy)>0) {
$query.= '
GROUP BY '.$groupBy;
}
// Order by:
if (strlen($orderBy)>0) {
$query.= '
ORDER BY '.$orderBy;
}
// Group by:
if (strlen($limit)>0) {
$query.= '
LIMIT '.$limit;
}
// Return query:
if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
return $query;
}
/**
* Returns a WHERE clause that can find a value ($value) in a list field ($field)
* For instance a record in the database might contain a list of numbers, "34,234,5" (with no spaces between). This query would be able to select that record based on the value "34", "234" or "5" regardless of their positioni in the list (left, middle or right).
* Is nice to look up list-relations to records or files in TYPO3 database tables.
*
* @param string Field name
* @param string Value to find in list
* @param string Table in which we are searching (for DBAL detection of quoteStr() method)
* @return string WHERE clause for a query
*/
function listQuery($field, $value, $table) {
$command = $this->quoteStr($value, $table);
$where = '('.$field.' LIKE \'%,'.$command.',%\' OR '.$field.' LIKE \''.$command.',%\' OR '.$field.' LIKE \'%,'.$command.'\' OR '.$field.'=\''.$command.'\')';
return $where;
}
/**
* Returns a WHERE clause which will make an AND search for the words in the $searchWords array in any of the fields in array $fields.
*
* @param array Array of search words
* @param array Array of fields
* @param string Table in which we are searching (for DBAL detection of quoteStr() method)
* @return string WHERE clause for search
*/
function searchQuery($searchWords,$fields,$table) {
$queryParts = array();
foreach($searchWords as $sw) {
$like=' LIKE \'%'.$this->quoteStr($sw, $table).'%\'';
$queryParts[] = $table.'.'.implode($like.' OR '.$table.'.',$fields).$like;
}
$query = '('.implode(') AND (',$queryParts).')';
return $query ;
}
/**************************************
*
* Various helper functions
*
* Functions recommended to be used for
* - escaping values,
* - cleaning lists of values,
* - stripping of excess ORDER BY/GROUP BY keywords
*
**************************************/
/**
* Escaping and quoting values for SQL statements.
* Usage count/core: 100
*
* @param string Input string
* @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!).
* @return string Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
* @see quoteStr()
*/
function fullQuoteStr($str, $table) {
if (function_exists('mysql_real_escape_string')) {
return '\''.mysql_real_escape_string($str, $this->link).'\'';
} else {
return '\''.mysql_escape_string($str).'\'';
}
}
/**
* Will fullquote all values in the one-dimensional array so they are ready to "implode" for an sql query.
*
* @param array Array with values (either associative or non-associative array)
* @param string Table name for which to quote
* @param string/array List/array of keys NOT to quote (eg. SQL functions) - ONLY for associative arrays
* @return array The input array with the values quoted
* @see cleanIntArray()
*/
function fullQuoteArray($arr, $table, $noQuote=FALSE) {
if (is_string($noQuote)) {
$noQuote = explode(',',$noQuote);
} elseif (!is_array($noQuote)) { // sanity check
$noQuote = FALSE;
}
foreach($arr as $k => $v) {
if ($noQuote===FALSE || !in_array($k,$noQuote)) {
$arr[$k] = $this->fullQuoteStr($v, $table);
}
}
return $arr;
}
/**
* Substitution for PHP function "addslashes()"
* Use this function instead of the PHP addslashes() function when you build queries - this will prepare your code for DBAL.
* 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()!
*
* Usage count/core: 20
*
* @param string Input string
* @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!).
* @return string Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
* @see quoteStr()
*/
function quoteStr($str, $table) {
if (function_exists('mysql_real_escape_string')) {
return mysql_real_escape_string($str, $this->link);
} else {
return mysql_escape_string($str);
}
}
/**
* Escaping values for SQL LIKE statements.
*
* @param string Input string
* @param string Table name for which to escape 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!).
* @return string Output string; % and _ will be escaped with \ (or otherwise based on DBAL handler)
* @see quoteStr()
*/
function escapeStrForLike($str, $table) {
return preg_replace('/[_%]/','\\\$0',$str);
}
/**
* Will convert all values in the one-dimensional array to integers.
* Useful when you want to make sure an array contains only integers before imploding them in a select-list.
* Usage count/core: 7
*
* @param array Array with values
* @return array The input array with all values passed through intval()
* @see cleanIntList()
*/
function cleanIntArray($arr) {
foreach($arr as $k => $v) {
$arr[$k] = intval($arr[$k]);
}
return $arr;
}
/**
* Will force all entries in the input comma list to integers
* Useful when you want to make sure a commalist of supposed integers really contain only integers; You want to know that when you don't trust content that could go into an SQL statement.
* Usage count/core: 6
*
* @param string List of comma-separated values which should be integers
* @return string The input list but with every value passed through intval()
* @see cleanIntArray()
*/
function cleanIntList($list) {
return implode(',',t3lib_div::intExplode(',',$list));
}
/**
* Removes the prefix "ORDER BY" from the input string.
* This function is used when you call the exec_SELECTquery() function and want to pass the ORDER BY parameter by can't guarantee that "ORDER BY" is not prefixed.
* Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
* Usage count/core: 11
*
* @param string eg. "ORDER BY title, uid"
* @return string eg. "title, uid"
* @see exec_SELECTquery(), stripGroupBy()
*/
function stripOrderBy($str) {
return preg_replace('/^ORDER[[:space:]]+BY[[:space:]]+/i','',trim($str));
}
/**
* Removes the prefix "GROUP BY" from the input string.
* This function is used when you call the SELECTquery() function and want to pass the GROUP BY parameter by can't guarantee that "GROUP BY" is not prefixed.
* Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
* Usage count/core: 1
*
* @param string eg. "GROUP BY title, uid"
* @return string eg. "title, uid"
* @see exec_SELECTquery(), stripOrderBy()
*/
function stripGroupBy($str) {
return preg_replace('/^GROUP[[:space:]]+BY[[:space:]]+/i','',trim($str));
}
/**
* Takes the last part of a query, eg. "... uid=123 GROUP BY title ORDER BY title LIMIT 5,2" and splits each part into a table (WHERE, GROUPBY, ORDERBY, LIMIT)
* Work-around function for use where you know some userdefined end to an SQL clause is supplied and you need to separate these factors.
* Usage count/core: 13
*
* @param string Input string
* @return array
*/
function splitGroupOrderLimit($str) {
$str = ' '.$str; // Prepending a space to make sure "[[:space:]]+" will find a space there for the first element.
// Init output array:
$wgolParts = array(
'WHERE' => '',
'GROUPBY' => '',
'ORDERBY' => '',
'LIMIT' => ''
);
// Find LIMIT:
$reg = array();
if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i',$str,$reg)) {
$wgolParts['LIMIT'] = trim($reg[2]);
$str = $reg[1];
}
// Find ORDER BY:
$reg = array();
if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i',$str,$reg)) {
$wgolParts['ORDERBY'] = trim($reg[2]);
$str = $reg[1];
}
// Find GROUP BY:
$reg = array();
if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i',$str,$reg)) {
$wgolParts['GROUPBY'] = trim($reg[2]);
$str = $reg[1];
}
// Rest is assumed to be "WHERE" clause:
$wgolParts['WHERE'] = $str;
return $wgolParts;
}
/**************************************
*
* MySQL wrapper functions
* (For use in your applications)
*
**************************************/
/**
* Executes query
* mysql() wrapper function
* DEPRECATED - use exec_* functions from this class instead!
* Usage count/core: 9
*
* @param string Database name
* @param string Query to execute
* @return pointer Result pointer / DBAL object
*/
function sql($db,$query) {
$res = mysql_query($query, $this->link);
if ($this->debugOutput) $this->debug('sql');
return $res;
}
/**
* Executes query
* mysql_query() wrapper function
* Usage count/core: 1
*
* @param string Query to execute
* @return pointer Result pointer / DBAL object
*/
function sql_query($query) {
$res = mysql_query($query, $this->link);
if ($this->debugOutput) $this->debug('sql_query');
return $res;
}
/**
* Returns the error status on the last sql() execution
* mysql_error() wrapper function
* Usage count/core: 32
*
* @return string MySQL error string.
*/
function sql_error() {
return mysql_error($this->link);
}
/**
* Returns the number of selected rows.
* mysql_num_rows() wrapper function
* Usage count/core: 85
*
* @param pointer MySQL result pointer (of SELECT query) / DBAL object
* @return integer Number of resulting rows.
*/
function sql_num_rows($res) {
return mysql_num_rows($res);
}
/**
* Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
* mysql_fetch_assoc() wrapper function
* Usage count/core: 307
*
* @param pointer MySQL result pointer (of SELECT query) / DBAL object
* @return array Associative array of result row.
*/
function sql_fetch_assoc($res) {
return mysql_fetch_assoc($res);
}
/**
* Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
* The array contains the values in numerical indices.
* mysql_fetch_row() wrapper function
* Usage count/core: 56
*
* @param pointer MySQL result pointer (of SELECT query) / DBAL object
* @return array Array with result rows.
*/
function sql_fetch_row($res) {
return mysql_fetch_row($res);
}
/**
* Free result memory
* mysql_free_result() wrapper function
* Usage count/core: 3
*
* @param pointer MySQL result pointer to free / DBAL object
* @return boolean Returns TRUE on success or FALSE on failure.
*/
function sql_free_result($res) {
return mysql_free_result($res);
}
/**
* Get the ID generated from the previous INSERT operation
* mysql_insert_id() wrapper function
* Usage count/core: 13
*
* @return integer The uid of the last inserted record.
*/
function sql_insert_id() {
return mysql_insert_id($this->link);
}
/**
* Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
* mysql_affected_rows() wrapper function
* Usage count/core: 1
*
* @return integer Number of rows affected by last query
*/
function sql_affected_rows() {
return mysql_affected_rows($this->link);
}
/**
* Move internal result pointer
* mysql_data_seek() wrapper function
* Usage count/core: 3
*
* @param pointer MySQL result pointer (of SELECT query) / DBAL object
* @param integer Seek result number.
* @return boolean Returns TRUE on success or FALSE on failure.
*/
function sql_data_seek($res,$seek) {
return mysql_data_seek($res,$seek);
}
/**
* Get the type of the specified field in a result
* mysql_field_type() wrapper function
* Usage count/core: 2
*
* @param pointer MySQL result pointer (of SELECT query) / DBAL object
* @param integer Field index.
* @return string Returns the name of the specified field index
*/
function sql_field_type($res,$pointer) {
return mysql_field_type($res,$pointer);
}
/**
* Open a (persistent) connection to a MySQL server
* mysql_pconnect() wrapper function
* Usage count/core: 12
*
* @param string Database host IP/domain
* @param string Username to connect with.
* @param string Password to connect with.
* @return pointer Returns a positive MySQL persistent link identifier on success, or FALSE on error.
*/
function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password) {
if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']) {
$this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
} else {
$this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
}
if (!$this->link) {
t3lib_div::sysLog('Could not connect to Mysql server '.$TYPO3_db_host.' with user '.$TYPO3_db_username.'.','Core',4);
} else {
$setDBinit = t3lib_div::trimExplode(chr(10), $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'],true);
foreach ($setDBinit as $v) {
if (mysql_query($v, $this->link) === FALSE) {
t3lib_div::sysLog('Could not initialize DB connection with query "'.$v.'": '.mysql_error($this->link),'Core',3);
}
}
}
return $this->link;
}
/**
* Select a MySQL database
* mysql_select_db() wrapper function
* Usage count/core: 8
*
* @param string Database to connect to.
* @return boolean Returns TRUE on success or FALSE on failure.
*/
function sql_select_db($TYPO3_db) {
$ret = @mysql_select_db($TYPO3_db, $this->link);
if (!$ret) {
t3lib_div::sysLog('Could not select Mysql database '.$TYPO3_db.': '.mysql_error(),'Core',4);
}
return $ret;
}
/**************************************
*
* SQL admin functions
* (For use in the Install Tool and Extension Manager)
*
**************************************/
/**
* Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
* This is only used as a service function in the (1-2-3 process) of the Install Tool. In any case a lookup should be done in the _DEFAULT handler DBMS then.
* Use in Install Tool only!
* Usage count/core: 1
*
* @return array Each entry represents a database name
*/
function admin_get_dbs() {
$dbArr = array();
$db_list = mysql_list_dbs($this->link);
while ($row = mysql_fetch_object($db_list)) {
if ($this->sql_select_db($row->Database)) {
$dbArr[] = $row->Database;
}
}
return $dbArr;
}
/**
* Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
* In a DBAL this method should 1) look up all tables from the DBMS of the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
* Usage count/core: 2
*
* @return array Tables in an array (tablename is in both key and value)
*/
function admin_get_tables() {
$whichTables = array();
$tables_result = mysql_list_tables(TYPO3_db, $this->link);
if (!mysql_error()) {
while ($theTable = mysql_fetch_assoc($tables_result)) {
$whichTables[current($theTable)] = current($theTable);
}
}
return $whichTables;
}
/**
* Returns information about each field in the $table (quering the DBMS)
* In a DBAL this should look up the right handler for the table and return compatible information
* 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.
*
* @param string Table name
* @return array Field information in an associative array with fieldname => field row
*/
function admin_get_fields($tableName) {
$output = array();
$columns_res = mysql_query('SHOW columns FROM '.$tableName, $this->link);
while($fieldRow = mysql_fetch_assoc($columns_res)) {
$output[$fieldRow['Field']] = $fieldRow;
}
return $output;
}
/**
* Returns information about each index key in the $table (quering the DBMS)
* In a DBAL this should look up the right handler for the table and return compatible information
*
* @param string Table name
* @return array Key information in a numeric array
*/
function admin_get_keys($tableName) {
$output = array();
$keyRes = mysql_query('SHOW keys FROM '.$tableName, $this->link);
while($keyRow = mysql_fetch_assoc($keyRes)) {
$output[] = $keyRow;
}
return $output;
}
/**
* mysql() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
* Usage count/core: 10
*
* @param string Query to execute
* @return pointer Result pointer
*/
function admin_query($query) {
$res = mysql_query($query, $this->link);
if ($this->debugOutput) $this->debug('admin_query');
return $res;
}
/******************************
*
* Connecting service
*
******************************/
/**
* Connects to database for TYPO3 sites:
*
* @return void
*/
function connectDB() {
if ($this->sql_pconnect(TYPO3_db_host, TYPO3_db_username, TYPO3_db_password)) {
if (!TYPO3_db) {
die('No database selected');
exit;
} elseif (!$this->sql_select_db(TYPO3_db)) {
die('Cannot connect to the current database, "'.TYPO3_db.'"');
exit;
}
} else {
die('The current username, password or host was not accepted when the connection to the database was attempted to be established!');
exit;
}
}
/******************************
*
* Debugging
*
******************************/
/**
* Debug function: Outputs error if any
*
* @param string Function calling debug()
* @return void
*/
function debug($func) {
$error = $this->sql_error();
if ($error) {
echo t3lib_div::view_array(array(
'caller' => 't3lib_DB::'.$func,
'ERROR' => $error,
'lastBuiltQuery' => $this->debug_lastBuiltQuery,
'debug_backtrace' => t3lib_div::debug_trail()
));
}
}
}
if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']) {
include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']);
}
?>
|