@@ -911,8 +911,9 @@ function _weak_escape( $string ) {
911911 }
912912
913913 /**
914- * Real escape, using mysql_real_escape_string()
914+ * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
915915 *
916+ * @see mysqli_real_escape_string()
916917 * @see mysql_real_escape_string()
917918 * @since 2.8.0
918919 * @access private
@@ -921,12 +922,20 @@ function _weak_escape( $string ) {
921922 * @return string escaped
922923 */
923924 function _real_escape ( $ string ) {
924- if ( $ this ->dbh )
925- return mysql_real_escape_string ( $ string , $ this ->dbh );
925+ if ( $ this ->dbh ) {
926+ $ escaped = mysql_real_escape_string ( $ string , $ this ->dbh );
927+ } else {
928+ $ class = get_class ( $ this );
929+ if ( function_exists ( '__ ' ) ) {
930+ /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
931+ _doing_it_wrong ( $ class , sprintf ( __ ( '%s must set a database connection for use with escaping. ' ), $ class ), '3.6.0 ' );
932+ } else {
933+ _doing_it_wrong ( $ class , sprintf ( '%s must set a database connection for use with escaping. ' , $ class ), '3.6.0 ' );
934+ }
935+ $ escaped = addslashes ( $ string );
936+ }
926937
927- $ class = get_class ( $ this );
928- _doing_it_wrong ( $ class , "$ class must set a database connection for use with escaping. " , E_USER_NOTICE );
929- return addslashes ( $ string );
938+ return $ this ->add_placeholder_escape ( $ escaped );
930939 }
931940
932941 /**
@@ -1000,65 +1009,120 @@ function escape_by_ref( &$string ) {
10001009 /**
10011010 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
10021011 *
1003- * The following directives can be used in the query format string:
1012+ * The following placeholders can be used in the query string:
10041013 * %d (integer)
10051014 * %f (float)
10061015 * %s (string)
1007- * %% (literal percentage sign - no argument needed)
10081016 *
1009- * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
1010- * Literals (%) as parts of the query must be properly written as %%.
1017+ * All placeholders MUST be left unquoted in the query string. A corresponding argument MUST be passed for each placeholder.
10111018 *
1012- * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
1013- * Does not support sign, padding, alignment, width or precision specifiers.
1014- * Does not support argument numbering/swapping.
1019+ * For compatibility with old behavior, numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes
1020+ * added by this function, so should be passed with appropriate quotes around them for your usage.
10151021 *
1016- * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
1022+ * Literal percentage signs (%) in the query string must be written as %%. Percentage wildcards (for example,
1023+ * to use in LIKE syntax) must be passed via a substitution argument containing the complete LIKE string, these
1024+ * cannot be inserted directly in the query string. Also see {@see esc_like()}.
10171025 *
1018- * Both %d and %s should be left unquoted in the query string.
1026+ * Arguments may be passed as individual arguments to the method, or as a single array containing all arguments. A combination
1027+ * of the two is not supported.
10191028 *
1020- * <code>
1021- * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
1022- * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
1023- * </code>
1029+ * Examples:
1030+ * $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", array( 'foo', 1337, '%bar' ) );
1031+ * $wpdb->prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
10241032 *
1025- * @link http ://php.net/sprintf Description of syntax.
1033+ * @link https ://secure. php.net/sprintf Description of syntax.
10261034 * @since 2.3.0
10271035 *
1028- * @param string $query Query statement with sprintf()-like placeholders
1029- * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
1030- * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
1031- * being called like {@link http://php.net/sprintf sprintf()}.
1032- * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
1033- * {@link http://php.net/sprintf sprintf()}.
1034- * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
1035- * if there was something to prepare
1036- */
1037- function prepare ( $ query , $ args ) {
1038- if ( is_null ( $ query ) )
1036+ * @param string $query Query statement with sprintf()-like placeholders
1037+ * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called with an array of arguments,
1038+ * or the first variable to substitute into the query's placeholders if being called with individual arguments.
1039+ * @param mixed $args,... further variables to substitute into the query's placeholders if being called wih individual arguments.
1040+ * @return string|void Sanitized query string, if there is a query to prepare.
1041+ */
1042+ public function prepare ( $ query , $ args ) {
1043+ if ( is_null ( $ query ) ) {
10391044 return ;
1045+ }
1046+
1047+ // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
1048+ if ( strpos ( $ query , '% ' ) === false ) {
1049+ wp_load_translations_early ();
1050+ _doing_it_wrong ( 'wpdb::prepare ' , sprintf ( __ ( 'The query argument of %s must have a placeholder. ' ), 'wpdb::prepare() ' ), '3.9.0 ' );
1051+ }
10401052
10411053 $ args = func_get_args ();
10421054 array_shift ( $ args );
10431055
1044- // If args were passed as an array (as in vsprintf), move them up
1056+ // If args were passed as an array (as in vsprintf), move them up.
1057+ $ passed_as_array = false ;
10451058 if ( is_array ( $ args [0 ] ) && count ( $ args ) == 1 ) {
1059+ $ passed_as_array = true ;
10461060 $ args = $ args [0 ];
10471061 }
10481062
10491063 foreach ( $ args as $ arg ) {
10501064 if ( ! is_scalar ( $ arg ) && ! is_null ( $ arg ) ) {
1051- _doing_it_wrong ( 'wpdb::prepare ' , sprintf ( 'Unsupported value type (%s). ' , gettype ( $ arg ) ), '3.8.22 ' );
1065+ wp_load_translations_early ();
1066+ _doing_it_wrong ( 'wpdb::prepare ' , sprintf ( __ ( 'Unsupported value type (%s). ' ), gettype ( $ arg ) ), '4.8.2 ' );
1067+ }
1068+ }
1069+
1070+ /*
1071+ * Specify the formatting allowed in a placeholder. The following are allowed:
1072+ *
1073+ * - Sign specifier. eg, $+d
1074+ * - Numbered placeholders. eg, %1$s
1075+ * - Padding specifier, including custom padding characters. eg, %05s, %'#5s
1076+ * - Alignment specifier. eg, %05-s
1077+ * - Precision specifier. eg, %.2f
1078+ */
1079+ $ allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0| \'.)?[-+0-9]*(?:\.[0-9]+)? ' ;
1080+
1081+ /*
1082+ * If a %s placeholder already has quotes around it, removing the existing quotes and re-inserting them
1083+ * ensures the quotes are consistent.
1084+ *
1085+ * For backwards compatibility, this is only applied to %s, and not to placeholders like %1$s, which are frequently
1086+ * used in the middle of longer strings, or as table name placeholders.
1087+ */
1088+ $ query = str_replace ( "'%s' " , '%s ' , $ query ); // Strip any existing single quotes.
1089+ $ query = str_replace ( '"%s" ' , '%s ' , $ query ); // Strip any existing double quotes.
1090+ $ query = preg_replace ( '/(?<!%)%s/ ' , "'%s' " , $ query ); // Quote the strings, avoiding escaped strings like %%s.
1091+
1092+ $ query = preg_replace ( "/(?<!%)(%( $ allowed_format)?f)/ " , '% \\2F ' , $ query ); // Force floats to be locale unaware.
1093+
1094+ $ query = preg_replace ( "/%(?:%|$|(?!( $ allowed_format)?[sdF]))/ " , '%% \\1 ' , $ query ); // Escape any unescaped percents.
1095+
1096+ // Count the number of valid placeholders in the query.
1097+ $ placeholders = preg_match_all ( "/(^|[^%]|(%%)+)%( $ allowed_format)?[sdF]/ " , $ query , $ matches );
1098+
1099+ if ( count ( $ args ) !== $ placeholders ) {
1100+ if ( 1 === $ placeholders && $ passed_as_array ) {
1101+ // If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
1102+ wp_load_translations_early ();
1103+ _doing_it_wrong ( 'wpdb::prepare ' , __ ( 'The query only expected one placeholder, but an array of multiple placeholders was sent. ' ), '4.9.0 ' );
1104+
1105+ return ;
1106+ } else {
1107+ /*
1108+ * If we don't have the right number of placeholders, but they were passed as individual arguments,
1109+ * or we were expecting multiple arguments in an array, throw a warning.
1110+ */
1111+ wp_load_translations_early ();
1112+ _doing_it_wrong ( 'wpdb::prepare ' ,
1113+ /* translators: 1: number of placeholders, 2: number of arguments passed */
1114+ sprintf ( __ ( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d). ' ),
1115+ $ placeholders ,
1116+ count ( $ args ) ),
1117+ '4.8.3 '
1118+ );
10521119 }
10531120 }
10541121
1055- $ query = str_replace ( "'%s' " , '%s ' , $ query ); // in case someone mistakenly already singlequoted it
1056- $ query = str_replace ( '"%s" ' , '%s ' , $ query ); // doublequote unquoting
1057- $ query = preg_replace ( '|(?<!%)%f| ' , '%F ' , $ query ); // Force floats to be locale unaware
1058- $ query = preg_replace ( '|(?<!%)%s| ' , "'%s' " , $ query ); // quote the strings, avoiding escaped strings like %%s
1059- $ query = preg_replace ( '/%(?:%|$|([^dsF]))/ ' , '%% \\1 ' , $ query ); // escape any unescaped percents
10601122 array_walk ( $ args , array ( $ this , 'escape_by_ref ' ) );
1061- return @vsprintf ( $ query , $ args );
1123+ $ query = @vsprintf ( $ query , $ args );
1124+
1125+ return $ this ->add_placeholder_escape ( $ query );
10621126 }
10631127
10641128 /**
@@ -1324,6 +1388,64 @@ function query( $query ) {
13241388 return $ return_val ;
13251389 }
13261390
1391+ /**
1392+ * Generates and returns a placeholder escape string for use in queries returned by ::prepare().
1393+ *
1394+ * @since 4.8.3
1395+ *
1396+ * @return string String to escape placeholders.
1397+ */
1398+ public function placeholder_escape () {
1399+ static $ placeholder ;
1400+
1401+ if ( ! $ placeholder ) {
1402+ // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
1403+ $ algo = function_exists ( 'hash ' ) ? 'sha256 ' : 'sha1 ' ;
1404+ // Old WP installs may not have AUTH_SALT defined.
1405+ $ salt = defined ( 'AUTH_SALT ' ) ? AUTH_SALT : rand ();
1406+
1407+ $ placeholder = '{ ' . hash_hmac ( $ algo , uniqid ( $ salt , true ), $ salt ) . '} ' ;
1408+ }
1409+
1410+ /*
1411+ * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything
1412+ * else attached to this filter will recieve the query with the placeholder string removed.
1413+ */
1414+ if ( ! has_filter ( 'query ' , array ( $ this , 'remove_placeholder_escape ' ) ) ) {
1415+ add_filter ( 'query ' , array ( $ this , 'remove_placeholder_escape ' ), 0 );
1416+ }
1417+
1418+ return $ placeholder ;
1419+ }
1420+
1421+ /**
1422+ * Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
1423+ *
1424+ * @since 4.8.3
1425+ *
1426+ * @param string $query The query to escape.
1427+ * @return string The query with the placeholder escape string inserted where necessary.
1428+ */
1429+ public function add_placeholder_escape ( $ query ) {
1430+ /*
1431+ * To prevent returning anything that even vaguely resembles a placeholder,
1432+ * we clobber every % we can find.
1433+ */
1434+ return str_replace ( '% ' , $ this ->placeholder_escape (), $ query );
1435+ }
1436+
1437+ /**
1438+ * Removes the placeholder escape strings from a query.
1439+ *
1440+ * @since 4.8.3
1441+ *
1442+ * @param string $query The query from which the placeholder will be removed.
1443+ * @return string The query with the placeholder removed.
1444+ */
1445+ public function remove_placeholder_escape ( $ query ) {
1446+ return str_replace ( $ this ->placeholder_escape (), '% ' , $ query );
1447+ }
1448+
13271449 /**
13281450 * Insert a row into a table.
13291451 *
0 commit comments