wp/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php
changeset 16 a86126ab1dd4
parent 9 177826044cd9
child 18 be944660c56a
--- a/wp/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php	Tue Oct 22 16:11:46 2019 +0200
+++ b/wp/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php	Tue Dec 15 13:49:49 2020 +0100
@@ -70,7 +70,7 @@
 	 *
 	 * @param int             $object_id Object ID to fetch meta for.
 	 * @param WP_REST_Request $request   Full details about the request.
-	 * @return WP_Error|object Object containing the meta values by name, otherwise WP_Error object.
+	 * @return array Array containing the meta values keyed by name.
 	 */
 	public function get_value( $object_id, $request ) {
 		$fields   = $this->get_registered_fields();
@@ -79,15 +79,18 @@
 		foreach ( $fields as $meta_key => $args ) {
 			$name       = $args['name'];
 			$all_values = get_metadata( $this->get_meta_type(), $object_id, $meta_key, false );
+
 			if ( $args['single'] ) {
 				if ( empty( $all_values ) ) {
 					$value = $args['schema']['default'];
 				} else {
 					$value = $all_values[0];
 				}
+
 				$value = $this->prepare_value_for_response( $value, $request, $args );
 			} else {
 				$value = array();
+
 				foreach ( $all_values as $row ) {
 					$value[] = $this->prepare_value_for_response( $row, $request, $args );
 				}
@@ -126,12 +129,13 @@
 	 *
 	 * @since 4.7.0
 	 *
-	 * @param array           $meta      Array of meta parsed from the request.
-	 * @param int             $object_id Object ID to fetch meta for.
-	 * @return WP_Error|null WP_Error if one occurs, null on success.
+	 * @param array $meta      Array of meta parsed from the request.
+	 * @param int   $object_id Object ID to fetch meta for.
+	 * @return null|WP_Error Null on success, WP_Error object on failure.
 	 */
 	public function update_value( $meta, $object_id ) {
 		$fields = $this->get_registered_fields();
+
 		foreach ( $fields as $meta_key => $args ) {
 			$name = $args['name'];
 			if ( ! array_key_exists( $name, $meta ) ) {
@@ -143,6 +147,21 @@
 			 * from the database and then relying on the default value.
 			 */
 			if ( is_null( $meta[ $name ] ) ) {
+				$args = $this->get_registered_fields()[ $meta_key ];
+
+				if ( $args['single'] ) {
+					$current = get_metadata( $this->get_meta_type(), $object_id, $meta_key, true );
+
+					if ( is_wp_error( rest_validate_value_from_schema( $current, $args['schema'] ) ) ) {
+						return new WP_Error(
+							'rest_invalid_stored_value',
+							/* translators: %s: Custom field key. */
+							sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $name ),
+							array( 'status' => 500 )
+						);
+					}
+				}
+
 				$result = $this->delete_meta_value( $object_id, $meta_key, $name );
 				if ( is_wp_error( $result ) ) {
 					return $result;
@@ -150,13 +169,24 @@
 				continue;
 			}
 
-			$is_valid = rest_validate_value_from_schema( $meta[ $name ], $args['schema'], 'meta.' . $name );
+			$value = $meta[ $name ];
+
+			if ( ! $args['single'] && is_array( $value ) && count( array_filter( $value, 'is_null' ) ) ) {
+				return new WP_Error(
+					'rest_invalid_stored_value',
+					/* translators: %s: Custom field key. */
+					sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $name ),
+					array( 'status' => 500 )
+				);
+			}
+
+			$is_valid = rest_validate_value_from_schema( $value, $args['schema'], 'meta.' . $name );
 			if ( is_wp_error( $is_valid ) ) {
 				$is_valid->add_data( array( 'status' => 400 ) );
 				return $is_valid;
 			}
 
-			$value = rest_sanitize_value_from_schema( $meta[ $name ], $args['schema'] );
+			$value = rest_sanitize_value_from_schema( $value, $args['schema'] );
 
 			if ( $args['single'] ) {
 				$result = $this->update_meta_value( $object_id, $meta_key, $name, $value );
@@ -184,10 +214,11 @@
 	 */
 	protected function delete_meta_value( $object_id, $meta_key, $name ) {
 		$meta_type = $this->get_meta_type();
+
 		if ( ! current_user_can( "delete_{$meta_type}_meta", $object_id, $meta_key ) ) {
 			return new WP_Error(
 				'rest_cannot_delete',
-				/* translators: %s: custom field key */
+				/* translators: %s: Custom field key. */
 				sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
 				array(
 					'key'    => $name,
@@ -225,10 +256,11 @@
 	 */
 	protected function update_multi_meta_value( $object_id, $meta_key, $name, $values ) {
 		$meta_type = $this->get_meta_type();
+
 		if ( ! current_user_can( "edit_{$meta_type}_meta", $object_id, $meta_key ) ) {
 			return new WP_Error(
 				'rest_cannot_update',
-				/* translators: %s: custom field key */
+				/* translators: %s: Custom field key. */
 				sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
 				array(
 					'key'    => $name,
@@ -237,13 +269,21 @@
 			);
 		}
 
-		$current = get_metadata( $meta_type, $object_id, $meta_key, false );
+		$current_values = get_metadata( $meta_type, $object_id, $meta_key, false );
+		$subtype        = get_object_subtype( $meta_type, $object_id );
 
-		$to_remove = $current;
+		$to_remove = $current_values;
 		$to_add    = $values;
 
 		foreach ( $to_add as $add_key => $value ) {
-			$remove_keys = array_keys( $to_remove, $value, true );
+			$remove_keys = array_keys(
+				array_filter(
+					$current_values,
+					function ( $stored_value ) use ( $meta_key, $subtype, $value ) {
+						return $this->is_meta_value_same_as_stored_value( $meta_key, $subtype, $stored_value, $value );
+					}
+				)
+			);
 
 			if ( empty( $remove_keys ) ) {
 				continue;
@@ -260,14 +300,19 @@
 			unset( $to_add[ $add_key ] );
 		}
 
-		// `delete_metadata` removes _all_ instances of the value, so only call once.
-		$to_remove = array_unique( $to_remove );
+		/*
+		 * `delete_metadata` removes _all_ instances of the value, so only call once. Otherwise,
+		 * `delete_metadata` will return false for subsequent calls of the same value.
+		 * Use serialization to produce a predictable string that can be used by array_unique.
+		 */
+		$to_remove = array_map( 'maybe_unserialize', array_unique( array_map( 'maybe_serialize', $to_remove ) ) );
 
 		foreach ( $to_remove as $value ) {
 			if ( ! delete_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
 				return new WP_Error(
 					'rest_meta_database_error',
-					__( 'Could not update meta value in database.' ),
+					/* translators: %s: Custom field key. */
+					sprintf( __( 'Could not update the meta value of %s in database.' ), $meta_key ),
 					array(
 						'key'    => $name,
 						'status' => WP_Http::INTERNAL_SERVER_ERROR,
@@ -280,7 +325,8 @@
 			if ( ! add_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
 				return new WP_Error(
 					'rest_meta_database_error',
-					__( 'Could not update meta value in database.' ),
+					/* translators: %s: Custom field key. */
+					sprintf( __( 'Could not update the meta value of %s in database.' ), $meta_key ),
 					array(
 						'key'    => $name,
 						'status' => WP_Http::INTERNAL_SERVER_ERROR,
@@ -305,10 +351,11 @@
 	 */
 	protected function update_meta_value( $object_id, $meta_key, $name, $value ) {
 		$meta_type = $this->get_meta_type();
+
 		if ( ! current_user_can( "edit_{$meta_type}_meta", $object_id, $meta_key ) ) {
 			return new WP_Error(
 				'rest_cannot_update',
-				/* translators: %s: custom field key */
+				/* translators: %s: Custom field key. */
 				sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
 				array(
 					'key'    => $name,
@@ -321,16 +368,15 @@
 		$old_value = get_metadata( $meta_type, $object_id, $meta_key );
 		$subtype   = get_object_subtype( $meta_type, $object_id );
 
-		if ( 1 === count( $old_value ) ) {
-			if ( (string) sanitize_meta( $meta_key, $value, $meta_type, $subtype ) === $old_value[0] ) {
-				return true;
-			}
+		if ( 1 === count( $old_value ) && $this->is_meta_value_same_as_stored_value( $meta_key, $subtype, $old_value[0], $value ) ) {
+			return true;
 		}
 
-		if ( ! update_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
+		if ( ! update_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash_strings_only( $value ) ) ) {
 			return new WP_Error(
 				'rest_meta_database_error',
-				__( 'Could not update meta value in database.' ),
+				/* translators: %s: Custom field key. */
+				sprintf( __( 'Could not update the meta value of %s in database.' ), $meta_key ),
 				array(
 					'key'    => $name,
 					'status' => WP_Http::INTERNAL_SERVER_ERROR,
@@ -342,6 +388,29 @@
 	}
 
 	/**
+	 * Checks if the user provided value is equivalent to a stored value for the given meta key.
+	 *
+	 * @since 5.5.0
+	 *
+	 * @param string $meta_key     The meta key being checked.
+	 * @param string $subtype      The object subtype.
+	 * @param mixed  $stored_value The currently stored value retrieved from get_metadata().
+	 * @param mixed  $user_value   The value provided by the user.
+	 * @return bool
+	 */
+	protected function is_meta_value_same_as_stored_value( $meta_key, $subtype, $stored_value, $user_value ) {
+		$args      = $this->get_registered_fields()[ $meta_key ];
+		$sanitized = sanitize_meta( $meta_key, $user_value, $this->get_meta_type(), $subtype );
+
+		if ( in_array( $args['type'], array( 'string', 'number', 'integer', 'boolean' ), true ) ) {
+			// The return value of get_metadata will always be a string for scalar types.
+			$sanitized = (string) $sanitized;
+		}
+
+		return $sanitized === $stored_value;
+	}
+
+	/**
 	 * Retrieves all the registered meta fields.
 	 *
 	 * @since 4.7.0
@@ -390,15 +459,21 @@
 			$type = ! empty( $rest_args['type'] ) ? $rest_args['type'] : null;
 			$type = ! empty( $rest_args['schema']['type'] ) ? $rest_args['schema']['type'] : $type;
 
-			if ( ! in_array( $type, array( 'string', 'boolean', 'integer', 'number' ) ) ) {
+			if ( null === $rest_args['schema']['default'] ) {
+				$rest_args['schema']['default'] = static::get_empty_value_for_type( $type );
+			}
+
+			$rest_args['schema'] = $this->default_additional_properties_to_false( $rest_args['schema'] );
+
+			if ( ! in_array( $type, array( 'string', 'boolean', 'integer', 'number', 'array', 'object' ), true ) ) {
 				continue;
 			}
 
 			if ( empty( $rest_args['single'] ) ) {
-				$rest_args['schema']['items'] = array(
-					'type' => $rest_args['type'],
+				$rest_args['schema'] = array(
+					'type'  => 'array',
+					'items' => $rest_args['schema'],
 				);
-				$rest_args['schema']['type']  = 'array';
 			}
 
 			$registered[ $name ] = $rest_args;
@@ -449,34 +524,21 @@
 	 * @return mixed Value prepared for output. If a non-JsonSerializable object, null.
 	 */
 	public static function prepare_value( $value, $request, $args ) {
-		$type = $args['schema']['type'];
-
-		// For multi-value fields, check the item type instead.
-		if ( 'array' === $type && ! empty( $args['schema']['items']['type'] ) ) {
-			$type = $args['schema']['items']['type'];
+		if ( $args['single'] ) {
+			$schema = $args['schema'];
+		} else {
+			$schema = $args['schema']['items'];
 		}
 
-		switch ( $type ) {
-			case 'string':
-				$value = (string) $value;
-				break;
-			case 'integer':
-				$value = (int) $value;
-				break;
-			case 'number':
-				$value = (float) $value;
-				break;
-			case 'boolean':
-				$value = (bool) $value;
-				break;
+		if ( '' === $value && in_array( $schema['type'], array( 'boolean', 'integer', 'number' ), true ) ) {
+			$value = static::get_empty_value_for_type( $schema['type'] );
 		}
 
-		// Don't allow objects to be output.
-		if ( is_object( $value ) && ! ( $value instanceof JsonSerializable ) ) {
+		if ( is_wp_error( rest_validate_value_from_schema( $value, $schema ) ) ) {
 			return null;
 		}
 
-		return $value;
+		return rest_sanitize_value_from_schema( $value, $schema );
 	}
 
 	/**
@@ -484,10 +546,10 @@
 	 *
 	 * @since 4.7.0
 	 *
-	 * @param  mixed           $value   The meta value submitted in the request.
-	 * @param  WP_REST_Request $request Full details about the request.
-	 * @param  string          $param   The parameter name.
-	 * @return WP_Error|string The meta array, if valid, otherwise an error.
+	 * @param mixed           $value   The meta value submitted in the request.
+	 * @param WP_REST_Request $request Full details about the request.
+	 * @param string          $param   The parameter name.
+	 * @return array|false The meta array, if valid, false otherwise.
 	 */
 	public function check_meta_is_array( $value, $request, $param ) {
 		if ( ! is_array( $value ) ) {
@@ -496,4 +558,62 @@
 
 		return $value;
 	}
+
+	/**
+	 * Recursively add additionalProperties = false to all objects in a schema if no additionalProperties setting
+	 * is specified.
+	 *
+	 * This is needed to restrict properties of objects in meta values to only
+	 * registered items, as the REST API will allow additional properties by
+	 * default.
+	 *
+	 * @since 5.3.0
+	 *
+	 * @param array $schema The schema array.
+	 * @return array
+	 */
+	protected function default_additional_properties_to_false( $schema ) {
+		switch ( $schema['type'] ) {
+			case 'object':
+				foreach ( $schema['properties'] as $key => $child_schema ) {
+					$schema['properties'][ $key ] = $this->default_additional_properties_to_false( $child_schema );
+				}
+
+				if ( ! isset( $schema['additionalProperties'] ) ) {
+					$schema['additionalProperties'] = false;
+				}
+				break;
+			case 'array':
+				$schema['items'] = $this->default_additional_properties_to_false( $schema['items'] );
+				break;
+		}
+
+		return $schema;
+	}
+
+	/**
+	 * Gets the empty value for a schema type.
+	 *
+	 * @since 5.3.0
+	 *
+	 * @param string $type The schema type.
+	 * @return mixed
+	 */
+	protected static function get_empty_value_for_type( $type ) {
+		switch ( $type ) {
+			case 'string':
+				return '';
+			case 'boolean':
+				return false;
+			case 'integer':
+				return 0;
+			case 'number':
+				return 0.0;
+			case 'array':
+			case 'object':
+				return array();
+			default:
+				return null;
+		}
+	}
 }