OrdersTableMetaQuery.php 16.4 KB
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
<?php
namespace Automattic\WooCommerce\Internal\DataStores\Orders;

defined( 'ABSPATH' ) || exit;

/**
 * Class used to implement meta queries for the orders table datastore via {@see OrdersTableQuery}.
 * Heavily inspired by WordPress' own `WP_Meta_Query` for backwards compatibility reasons.
 *
 * Parts of the implementation have been adapted from {@link https://core.trac.wordpress.org/browser/tags/6.0.1/src/wp-includes/class-wp-meta-query.php}.
 */
class OrdersTableMetaQuery {

	/**
	 * List of non-numeric SQL operators used for comparisons in meta queries.
	 *
	 * @var array
	 */
	private const NON_NUMERIC_OPERATORS = array(
		'=',
		'!=',
		'LIKE',
		'NOT LIKE',
		'IN',
		'NOT IN',
		'EXISTS',
		'NOT EXISTS',
		'RLIKE',
		'REGEXP',
		'NOT REGEXP',
	);

	/**
	 * List of numeric SQL operators used for comparisons in meta queries.
	 *
	 * @var array
	 */
	private const NUMERIC_OPERATORS = array(
		'>',
		'>=',
		'<',
		'<=',
		'BETWEEN',
		'NOT BETWEEN',

	);

	/**
	 * Prefix used when generating aliases for the metadata table.
	 *
	 * @var string
	 */
	private const ALIAS_PREFIX = 'meta';

	/**
	 * Name of the main orders table.
	 *
	 * @var string
	 */
	private $meta_table = '';

	/**
	 * Name of the metadata table.
	 *
	 * @var string
	 */
	private $orders_table = '';

	/**
	 * Sanitized `meta_query`.
	 *
	 * @var array
	 */
	private $queries = array();

	/**
	 * JOIN clauses to add to the main SQL query.
	 *
	 * @var array
	 */
	private $join = array();

	/**
	 * WHERE clauses to add to the main SQL query.
	 *
	 * @var array
	 */
	private $where = array();

	/**
	 * Table aliases in use by the meta query. Used to optimize JOINs when possible.
	 *
	 * @var array
	 */
	private $table_aliases = array();

	/**
	 * Constructor.
	 *
	 * @param OrdersTableQuery $q The main query being performed.
	 */
	public function __construct( OrdersTableQuery $q ) {
		$meta_query = $q->get( 'meta_query' );

		if ( ! $meta_query ) {
			return;
		}

		$this->queries = $this->sanitize_meta_query( $meta_query );

		$this->meta_table   = $q->get_table_name( 'meta' );
		$this->orders_table = $q->get_table_name( 'orders' );

		$this->build_query();
	}

	/**
	 * Returns JOIN and WHERE clauses to be appended to the main SQL query.
	 *
	 * @return array {
	 *     @type string $join  JOIN clause.
	 *     @type string $where WHERE clause.
	 * }
	 */
	public function get_sql_clauses(): array {
		return array(
			'join'  => $this->sanitize_join( $this->join ),
			'where' => $this->flatten_where_clauses( $this->where ),
		);
	}

	/**
	 * Checks whether a given meta_query clause is atomic or not (i.e. not nested).
	 *
	 * @param array $arg The meta_query clause.
	 * @return boolean TRUE if atomic, FALSE otherwise.
	 */
	private function is_atomic( array $arg ): bool {
		return isset( $arg['key'] ) || isset( $arg['value'] );
	}

	/**
	 * Sanitizes the meta_query argument.
	 *
	 * @param array $q A meta_query array.
	 * @return array A sanitized meta query array.
	 */
	private function sanitize_meta_query( array $q ): array {
		$sanitized = array();

		foreach ( $q as $key => $arg ) {
			if ( 'relation' === $key ) {
				$relation = $arg;
			} elseif ( ! is_array( $arg ) ) {
				continue;
			} elseif ( $this->is_atomic( $arg ) ) {
				if ( isset( $arg['value'] ) && array() === $arg['value'] ) {
					unset( $arg['value'] );
				}

				$arg['compare']      = isset( $arg['compare'] ) ? strtoupper( $arg['compare'] ) : ( isset( $arg['value'] ) && is_array( $arg['value'] ) ? 'IN' : '=' );
				$arg['compare_key']  = isset( $arg['compare_key'] ) ? strtoupper( $arg['compare_key'] ) : ( isset( $arg['key'] ) && is_array( $arg['key'] ) ? 'IN' : '=' );

				if ( ! in_array( $arg['compare'], self::NON_NUMERIC_OPERATORS, true ) && ! in_array( $arg['compare'], self::NUMERIC_OPERATORS, true ) ) {
					$arg['compare'] = '=';
				}

				if ( ! in_array( $arg['compare_key'], self::NON_NUMERIC_OPERATORS, true ) ) {
					$arg['compare_key'] = '=';
				}

				$sanitized[ $key ] = $arg;
			} else {
				$sanitized_arg = $this->sanitize_meta_query( $arg );

				if ( $sanitized_arg ) {
					$sanitized[ $key ] = $sanitized_arg;
				}
			}
		}

		if ( $sanitized ) {
			$sanitized['relation'] = 1 === count( $sanitized ) ? 'OR' : $this->sanitize_relation( $relation ?? 'AND' );
		}

		return $sanitized;
	}

	/**
	 * Makes sure we use an AND or OR relation. Defaults to AND.
	 *
	 * @param string $relation An unsanitized relation prop.
	 * @return string
	 */
	private function sanitize_relation( string $relation ): string {
		if ( ! empty( $relation ) && 'OR' === strtoupper( $relation ) ) {
			return 'OR';
		}

		return 'AND';
	}

	/**
	 * Returns the correct type for a given meta type.
	 *
	 * @param string $type MySQL type.
	 * @return string MySQL type.
	 */
	private function sanitize_cast_type( string $type = '' ): string {
		$meta_type = strtoupper( $type );

		if ( ! $meta_type || ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) ) {
			return 'CHAR';
		}

		if ( 'NUMERIC' === $meta_type ) {
			$meta_type = 'SIGNED';
		}

		return $meta_type;
	}

	/**
	 * Makes sure a JOIN array does not have duplicates.
	 *
	 * @param array $join A JOIN array.
	 * @return array A sanitized JOIN array.
	 */
	private function sanitize_join( array $join ): array {
		return array_filter( array_unique( array_map( 'trim', $join ) ) );
	}

	/**
	 * Flattens a nested WHERE array.
	 *
	 * @param array $where A possibly nested WHERE array with AND/OR operators.
	 * @return string An SQL WHERE clause.
	 */
	private function flatten_where_clauses( $where ): string {
		if ( is_string( $where ) ) {
			return trim( $where );
		}

		$chunks   = array();
		$operator = $this->sanitize_relation( $where['operator'] ?? '' );

		foreach ( $where as $key => $w ) {
			if ( 'operator' === $key ) {
				continue;
			}

			$flattened = $this->flatten_where_clauses( $w );
			if ( $flattened ) {
				$chunks[] = $flattened;
			}
		}

		if ( $chunks ) {
			return '(' . implode( " {$operator} ", $chunks ) . ')';
		} else {
			return '';
		}
	}

	/**
	 * Builds all the required internal bits for this meta query.
	 *
	 * @return void
	 */
	private function build_query(): void {
		if ( ! $this->queries ) {
			return;
		}

		$queries     = $this->queries;
		$sql_where   = $this->process( $queries );
		$this->where = $sql_where;

	}

	/**
	 * Processes meta_query entries and generates the necessary table aliases, JOIN statements and WHERE conditions.
	 *
	 * @param array      $arg    A meta query.
	 * @param null|array $parent The parent of the element being processed.
	 * @return array A nested array of WHERE conditions.
	 */
	private function process( array &$arg, &$parent = null ): array {
		$where = array();

		if ( $this->is_atomic( $arg ) ) {
			$arg['alias'] = $this->find_or_create_table_alias_for_clause( $arg, $parent );
			$arg['cast']  = $this->sanitize_cast_type( $arg['type'] ?? '' );

			$where = array_filter(
				array(
					$this->generate_where_for_clause_key( $arg ),
					$this->generate_where_for_clause_value( $arg ),
				)
			);
		} else {
			// Nested.
			$relation = $arg['relation'];
			unset( $arg['relation'] );

			foreach ( $arg as $key => &$clause ) {
				$chunks[] = $this->process( $clause, $arg );
			}

			// Merge chunks of the form OR(m) with the surrounding clause.
			if ( 1 === count( $chunks ) ) {
				$where = $chunks[0];
			} else {
				$where = array_merge(
					array(
						'operator' => $relation,
					),
					$chunks
				);
			}
		}

		return $where;
	}

	/**
	 * Generates a JOIN clause to handle an atomic meta_query clause.
	 *
	 * @param array  $clause An atomic meta_query clause.
	 * @param string $alias  Metadata table alias to use.
	 * @return string An SQL JOIN clause.
	 */
	private function generate_join_for_clause( array $clause, string $alias ): string {
		global $wpdb;

		if ( 'NOT EXISTS' === $clause['compare'] ) {
			if ( 'LIKE' === $clause['compare_key'] ) {
				return $wpdb->prepare(
					"LEFT JOIN {$this->meta_table} AS {$alias} ON ( {$this->orders_table}.id = {$alias}.order_id AND {$alias}.meta_key LIKE %s )", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
					'%' . $wpdb->esc_like( $clause['key'] ) . '%'
				);
			} else {
				return $wpdb->prepare(
					"LEFT JOIN {$this->meta_table} AS {$alias} ON ( {$this->orders_table}.id = {$alias}.order_id AND {$alias}.meta_key = %s )", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
					$clause['key']
				);
			}
		}

		return "INNER JOIN {$this->meta_table} AS {$alias} ON ( {$this->orders_table}.id = {$alias}.order_id )";
	}

	/**
	 * Finds a common table alias that the meta_query clause can use, or creates one.
	 *
	 * @param array $clause       An atomic meta_query clause.
	 * @param array $parent_query The parent query this clause is in.
	 * @return string A table alias for use in an SQL JOIN clause.
	 */
	private function find_or_create_table_alias_for_clause( array $clause, array $parent_query ): string {
		if ( ! empty( $clause['alias'] ) ) {
			return $clause['alias'];
		}

		$alias    = false;
		$siblings = array_filter(
			$parent_query,
			array( __CLASS__, 'is_atomic' )
		);

		foreach ( $siblings as $sibling ) {
			if ( empty( $sibling['alias'] ) ) {
				continue;
			}

			if ( $this->is_operator_compatible_with_shared_join( $clause, $sibling, $parent_query['relation'] ?? 'AND' ) ) {
				$alias = $sibling['alias'];
				break;
			}
		}

		if ( ! $alias ) {
			$alias                 = self::ALIAS_PREFIX . count( $this->table_aliases );
			$this->join[]          = $this->generate_join_for_clause( $clause, $alias );
			$this->table_aliases[] = $alias;
		}

		return $alias;
	}

	/**
	 * Checks whether two meta_query clauses can share a JOIN.
	 *
	 * @param array  $clause    An atomic meta_query clause.
	 * @param array  $sibling   An atomic meta_query clause.
	 * @param string $relation The relation involving both clauses.
	 * @return boolean TRUE if the clauses can share a table alias, FALSE otherwise.
	 */
	private function is_operator_compatible_with_shared_join( array $clause, array $sibling, string $relation = 'AND' ): bool {
		if ( ! $this->is_atomic( $clause ) || ! $this->is_atomic( $sibling ) ) {
			return false;
		}

		$valid_operators = array();

		if ( 'OR' === $relation ) {
			$valid_operators = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' );
		} elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) {
			$valid_operators = array( '!=', 'NOT IN', 'NOT LIKE' );
		}

		return in_array( strtoupper( $clause['compare'] ), $valid_operators, true ) && in_array( strtoupper( $sibling['compare'] ), $valid_operators, true );
	}

	/**
	 * Generates an SQL WHERE clause for a given meta_query atomic clause based on its meta key.
	 * Adapted from WordPress' `WP_Meta_Query::get_sql_for_clause()` method.
	 *
	 * @param array $clause An atomic meta_query clause.
	 * @return string An SQL WHERE clause or an empty string if $clause is invalid.
	 */
	private function generate_where_for_clause_key( array $clause ): string {
		global $wpdb;

		if ( ! array_key_exists( 'key', $clause ) ) {
			return '';
		}

		if ( 'NOT EXISTS' === $clause['compare'] ) {
			return "{$clause['alias']}.order_id IS NULL";
		}

		$alias = $clause['alias'];

		if ( in_array( $clause['compare_key'], array( '!=', 'NOT IN', 'NOT LIKE', 'NOT EXISTS', 'NOT REGEXP' ), true ) ) {
			$i                     = count( $this->table_aliases );
			$subquery_alias        = self::ALIAS_PREFIX . $i;
			$this->table_aliases[] = $subquery_alias;

			$meta_compare_string_start  = 'NOT EXISTS (';
			$meta_compare_string_start .= "SELECT 1 FROM {$this->meta_table} {$subquery_alias} ";
			$meta_compare_string_start .= "WHERE {$subquery_alias}.order_id = {$alias}.order_id ";
			$meta_compare_string_end    = 'LIMIT 1';
			$meta_compare_string_end   .= ')';
		}

		switch ( $clause['compare_key'] ) {
			case '=':
			case 'EXISTS':
				$where = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				break;
			case 'LIKE':
				$meta_compare_value = '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%';
				$where              = $wpdb->prepare( "$alias.meta_key LIKE %s", $meta_compare_value ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				break;
			case 'IN':
				$meta_compare_string = "$alias.meta_key IN (" . substr( str_repeat( ',%s', count( $clause['key'] ) ), 1 ) . ')';
				$where               = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
				break;
			case 'RLIKE':
			case 'REGEXP':
				$operator = $clause['compare_key'];
				if ( isset( $clause['type_key'] ) && 'BINARY' === strtoupper( $clause['type_key'] ) ) {
					$cast = 'BINARY';
				} else {
					$cast = '';
				}
				$where = $wpdb->prepare( "$alias.meta_key $operator $cast %s", trim( $clause['key'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				break;
			case '!=':
			case 'NOT EXISTS':
				$meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key = %s " . $meta_compare_string_end;
				$where               = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
				break;
			case 'NOT LIKE':
				$meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key LIKE %s " . $meta_compare_string_end;

				$meta_compare_value = '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%';
				$where              = $wpdb->prepare( $meta_compare_string, $meta_compare_value ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
				break;
			case 'NOT IN':
				$array_subclause     = '(' . substr( str_repeat( ',%s', count( $clause['key'] ) ), 1 ) . ') ';
				$meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key IN " . $array_subclause . $meta_compare_string_end;
				$where               = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
				break;
			case 'NOT REGEXP':
				$operator = $clause['compare_key'];
				if ( isset( $clause['type_key'] ) && 'BINARY' === strtoupper( $clause['type_key'] ) ) {
					$cast = 'BINARY';
				} else {
					$cast = '';
				}

				$meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key REGEXP $cast %s " . $meta_compare_string_end;
				$where               = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
				break;
			default:
				$where = '';
				break;
		}

		return $where;
	}

	/**
	 * Generates an SQL WHERE clause for a given meta_query atomic clause based on its meta value.
	 * Adapted from WordPress' `WP_Meta_Query::get_sql_for_clause()` method.
	 *
	 * @param array $clause An atomic meta_query clause.
	 * @return string An SQL WHERE clause or an empty string if $clause is invalid.
	 */
	private function generate_where_for_clause_value( $clause ): string {
		global $wpdb;

		if ( ! array_key_exists( 'value', $clause ) ) {
			return '';
		}

		$meta_value = $clause['value'];

		if ( in_array( $clause['compare'], array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) {
			if ( ! is_array( $meta_value ) ) {
				$meta_value = preg_split( '/[,\s]+/', $meta_value );
			}
		} elseif ( is_string( $meta_value ) ) {
			$meta_value = trim( $meta_value );
		}

		$meta_compare = $clause['compare'];

		switch ( $meta_compare ) {
			case 'IN':
			case 'NOT IN':
				$where = $wpdb->prepare( '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')', $meta_value ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
				break;

			case 'BETWEEN':
			case 'NOT BETWEEN':
				$where = $wpdb->prepare( '%s AND %s', $meta_value[0], $meta_value[1] );
				break;

			case 'LIKE':
			case 'NOT LIKE':
				$where = $wpdb->prepare( '%s', '%' . $wpdb->esc_like( $meta_value ) . '%' );
				break;

			// EXISTS with a value is interpreted as '='.
			case 'EXISTS':
				$meta_compare = '=';
				$where        = $wpdb->prepare( '%s', $meta_value );
				break;

			// 'value' is ignored for NOT EXISTS.
			case 'NOT EXISTS':
				$where = '';
				break;

			default:
				$where = $wpdb->prepare( '%s', $meta_value );
				break;
		}

		if ( $where ) {
			if ( 'CHAR' === $clause['cast'] ) {
				return "{$clause['alias']}.meta_value {$meta_compare} {$where}";
			} else {
				return "CAST({$clause['alias']}.meta_value AS {$clause['cast']}) {$meta_compare} {$where}";
			}
		}
	}

}