Synonyms.php 17.5 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 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
<?php
/**
 * SearchWP Synonyms.
 *
 * @package SearchWP
 * @author  Jon Christopher
 */

namespace SearchWP\Logic;

use SearchWP\Query;
use SearchWP\Settings;
use SearchWP\Utils;
use SearchWP\Support\Str;

/**
 * Class Synonyms is responsible for applying synonyms to Tokens.
 *
 * @since 4.0
 */
class Synonyms {

	/**
	 * The language code.
	 *
	 * @since 4.0
	 *
	 * @var string
	 */
	private $language_code;

	/**
	 * A flag to track the detection of the synonyms in a search string.
	 *
	 * @since 4.2.3
	 *
	 * @var bool
	 */
	private $found_synonym = false;

	/**
	 * Original search string before applying synonyms modifications.
	 *
	 * @since 4.2.3
	 *
	 * @var string
	 */
	private $original_search_string = '';

	/**
	 * Synonyms.
	 *
	 * @since 4.0
	 *
	 * @var array
	 */
	private $synonyms = [];

	/**
	 * Grouped synonyms.
	 *
	 * @since 4.2.3
	 *
	 * @var array
	 */
	public static $synonym_groups = [];

	/**
	 * Synonyms constructor.
	 *
	 * @since 4.0
	 */
	public function __construct() {

		// TODO: Build in support for multilanguage setups (WPML, Polylang, soon to be core).
		$this->language_code = strtolower( substr( get_locale(), 0, 2 ) );

		// TODO: Running the hooks will be moved out of the constructor as a part of the plugin bootstrap rewiring.
		$this->hooks();
	}

	/**
	 * Class hooks.
	 *
	 * @since 4.2.3
	 *
	 * @return void
	 */
	private function hooks() {

		// Apply synonyms to query search string.
		add_filter( 'searchwp\query\search_string', [ $this, 'apply' ], 5, 2 );
	}

	/**
	 * Applies synonyms to tokens.
	 *
	 * @since 4.0
	 *
	 * @param string $search_string Original search string.
	 * @param Query  $query         Query object.
	 *
	 * @return string Synonyms applied.
	 */
	public function apply( string $search_string, Query $query ): string {

		$search_string = Str::lower( $search_string );

		$query->set_debug_data( 'string.synonyms.before', $search_string );

		$this->set_original_search_string( $search_string );
		$this->set_initial_synonym_groups( $search_string );

		$this->set_synonyms( $search_string, $query );
		$this->set_partial_matches( $search_string, $query );

		$search_string = $this->apply_synonyms( $search_string, $query );
		$search_string = $this->remove_duplicate_words_from_string( $search_string );

		$this->remove_duplicate_tokens_from_token_groups();

		$query->set_debug_data( 'string.synonyms.after', $search_string );

		return $search_string;
	}

	/**
	 * Getter for saved Synonyms.
	 *
	 * @since 4.0
	 *
	 * @return array
	 */
	public function get(): array {

		$synonyms = Settings::get( 'synonyms' );

		return $synonyms === false ? [] : $this->normalize( $synonyms );
	}

	/**
	 * Normalizes synonym model.
	 *
	 * @since 4.0
	 *
	 * @param array $synonyms Incoming synonyms.
	 *
	 * @return array Normalized synonyms.
	 */
	public function normalize( array $synonyms = [] ): array {

		return array_values( array_filter( array_map( function( $synonym ) {
			if ( empty( $synonym['sources'] ) || empty( $synonym['synonyms'] ) ) {
				return false;
			}

			return [
				'sources' => implode( ', ', array_map( function( $source ) {
					return trim( sanitize_text_field( $source ) );
				}, explode( ',', $synonym['sources'] ) ) ),
				'synonyms' => implode( ', ', array_map( function( $source ) {
					return trim( sanitize_text_field( $source ) );
				}, explode( ',', $synonym['synonyms'] ) ) ),
				'replace' => ! empty( $synonym['replace'] )
			];
		}, $synonyms ) ) );
	}

	/**
	 * Updates saved synonyms.
	 *
	 * @since 4.0
	 *
	 * @param array $synonyms Synonyms to save.
	 *
	 * @return array Saved Synonyms.
	 */
	public function save( array $synonyms = [] ): array {

		$synonyms = $this->normalize( $synonyms );

		Settings::update( 'synonyms', $synonyms );

		return $synonyms;
	}

	/**
	 * Save the original search string for future use.
	 *
	 * @since 4.2.3
	 *
	 * @param string $search_string Search string.
	 *
	 * @return void
	 */
	private function set_original_search_string( string $search_string ) {

		$this->original_search_string = $search_string;
	}

	/**
	 * Set initial empty synonym groups to fill them with synonyms later.
	 *
	 * @since 4.2.3
	 *
	 * @param string $search_string Search string.
	 *
	 * @return void
	 */
	private function set_initial_synonym_groups( string $search_string ) {

		// Remove any quote if present.
		$search_string = Str::remove_quotes( $search_string );

		self::$synonym_groups = array_fill_keys( explode( ' ', $search_string ), [] );
	}

	/**
	 * Sets the synonyms for this application.
	 *
	 * @since 4.0
	 * @since 4.2.3 Changed public set() to private set_synonyms()
	 *
	 * @param string $search_string Query search string.
	 * @param Query  $query         Query object.
	 *
	 * @return void Synonyms.
	 */
	private function set_synonyms( string $search_string, Query $query ) {

		$synonyms = $this->get();

		// Allow developers to customize.
		$synonyms = (array) apply_filters( 'searchwp\synonyms', $synonyms, [
			'search_string' => $search_string,
			'query'         => $query,
		] );

		// Ensure valid format.
		$this->synonyms = array_filter( $synonyms, function( $synonym ) {
			return isset( $synonym['sources'] )
			       && isset( $synonym['synonyms'] )
			       && isset( $synonym['replace'] );
		} );
	}

	/**
	 * Applies partial matches to synonyms.
	 *
	 * @since 4.1
	 * @since 4.2.3 Changed to private method
	 *
	 * @param string $search_string Query search string.
	 * @param Query  $query         Query object.
	 *
	 * @return void
	 */
	private function set_partial_matches( string $search_string, Query $query ) {

		if ( empty( $this->synonyms ) ) {
			return;
		}

		$data = [
			'search' => $search_string,
			'query'  => $query,
		];

		// Apply our (wildcard-based) partial matching by default.
		if ( ! apply_filters( 'searchwp\synonyms\partial_matches', true, $data ) ) {
			return;
		}

		$synonyms = $this->synonyms;

		// Pad the search string to prevent overrun.
		$_search_string = ' ' . $this->original_search_string . ' ';

		foreach ( $synonyms as $index => $synonym ) {
			$sources = array_map( 'trim', explode( ',', $synonym['sources'] ) );

			foreach ( $sources as $source ) {
				// In order for partial matching to apply, a wildcard character (*) is used
				// because there are too many common cases where more generalized partial
				// matching has too many overruns and it triggers unwanted synonym hits.
				if ( ! Str::contains( $source, '*' ) ) {
					continue;
				}

				// Convert the wildcard into something that won't be double encoded.
				$placeholder     = Utils::get_placeholder( false );
				$source          = Str::remove_quotes( $source );
				$original_source = $source;
				$source          = str_replace( '*', $placeholder, $source );

				$needle = $original_source[0] !== '*' ?
					str_replace( $placeholder, '\S*\s', preg_quote( $source, '/' ) ) :
					str_replace( $placeholder, '\s\S*', preg_quote( $source, '/' ) );

				$pattern = '/' . $needle . '/ius';
				$term    = ' ' . Str::remove_quotes( $_search_string ) . ' ';

				if ( 1 === preg_match( $pattern, $term, $matches ) ) {
					$new_sources = implode( ',', array_map( 'trim', $matches ) );
					$this->synonyms[ $index ]['sources'] = str_replace( $original_source, $new_sources, $this->synonyms[ $index ]['sources'] );
				}
			}
		}
	}

	/**
	 * Apply synonyms to a search string.
	 *
	 * @since 4.2.3
	 *
	 * @param string $search_string Search string.
	 * @param Query  $query         Query object.
	 *
	 * @return string
	 */
	private function apply_synonyms( string $search_string, Query $query ): string {

		$synonyms = $this->synonyms;

		if ( empty( $synonyms ) ) {
			self::$synonym_groups = [];
			return $search_string;
		}

		foreach ( $synonyms as $synonym ) {
			// Multiple sources can be set using comma separation.
			$sources = array_filter( array_map( 'trim', explode( ',', $synonym['sources'] ) ) );

			if ( empty( $sources ) ) {
				continue;
			}

			// Reset the found synonyms flag before using it.
			$this->found_synonym = false;

			$search_string = $this->process_synonym_sources( $search_string, $sources, $synonym );

			// Assume that one synonym replacement is enough and in doing so prevent
			// redundant synonym application, but also base that on a hook to allow
			// developers to 'stack' synonyms when that's what they want to do.
			if ( apply_filters( 'searchwp\synonyms\aggressive', true ) && $this->found_synonym ) {
				break;
			}
		}

		// If no synonyms match was found empty the synonym groups
		if ( empty( array_values( self::$synonym_groups ) ) ) {
			self::$synonym_groups = [];
		}

		return $search_string;
	}

	/**
	 * Process single synonym sources.
	 *
	 * @since 4.2.3
	 *
	 * @param string $search_string Search string.
	 * @param array  $sources       Single synonym sources.
	 * @param array  $synonym       Single synonym data.
	 *
	 * @return string
	 */
	private function process_synonym_sources( string $search_string, array $sources, array $synonym ): string {

		// Iterate over the sources to see if there's a match.
		foreach ( $sources as $source ) {

			// If source contains a wildcard we can skip it as it was already processed for partial matches.
			if ( Str::contains( $source, '*' ) ) {
				continue;
			}

			$source = Str::lower( $source );

			// Strip quotes from the source and check if the source is present in the string.
			// If there is no match we can skip it.
			if ( ! preg_match( '/\s' . preg_quote(	Str::remove_quotes( $source ), '/' ) . '\s/iu',
				' ' . Str::remove_quotes( $search_string ) . ' '
			) ) {
				continue;
			}

			// If there's a space in the search string and the synonym source opt to replace only the whole source.
			if ( Str::contains( $search_string, ' ' ) && Str::contains( $source, ' ' ) ) {
				$search_string = $this->process_compound_source( $search_string, $source, $synonym );
			} else {
				$search_string = $this->process_regular_source( $search_string, $source, $synonym );
			}
		}

		return $search_string;
	}

	/**
	 * Process single compound (consisting of several words) source.
	 *
	 * @since 4.2.3
	 *
	 * @param string $search_string Search string.
	 * @param string $source        Single source.
	 * @param array  $synonym       Single synonym data.
	 *
	 * @return string
	 */
	private function process_compound_source( string $search_string, string $source, array $synonym ): string {

		$search_string_before = $search_string;

		if ( $this->is_not_strict_synonym_match( $search_string, $source ) ) {
			return $search_string;
		}

		if ( $synonym['replace'] ) {
			$search_string = $this->process_compound_source_replace( $search_string, $source, $synonym );
		} else {
			$search_string = $this->process_compound_source_no_replace( $search_string, $synonym );
		}

		// If the synonyms are present in the group as a source they should be removed.
		foreach ( explode( ' ', $source ) as $source_tokens ) {
			$source_tokens = Str::remove_quotes( $source_tokens );
			if ( isset( self::$synonym_groups[ $source_tokens ] ) ) {
				unset( self::$synonym_groups[ $source_tokens ] );
			}
		}

		// We can now add the synonyms tokens as new sources.
		$this->add_synonym_tokens_to_synonym_groups( $synonym );

		if ( $search_string_before !== $search_string ) {
			$this->found_synonym = true;
		}

		return $search_string;

		// TODO: use searchwp\query\tokens\limit hook to adjust limit based on count( $synonym['synonyms'] ) if necessary?
	}

	/**
	 * Process compound (consisting of several words) source replacing it with a synonym.
	 *
	 * @since 4.2.4
	 *
	 * @param string $search_string Search string.
	 * @param string $source        Single source.
	 * @param array  $synonym       Single synonym data.
	 *
	 * @return string
	 */
	private function process_compound_source_replace( string $search_string, string $source, array $synonym ): string {

		// Non strict quotes on synonyms sources.
		if ( ! apply_filters( 'searchwp\synonyms\strict', false ) ) {

			// Match quotes between search string and source.
			$source = Str::remove_quotes( $source );
			$source = Str::contains( $search_string, '"' ) ? '"' . $source . '"' : $source;
		}

		return $this->replace_source_with_synonyms_in_string( $search_string, $source, $synonym );
	}

	/**
	 * Process compound (consisting of several words) source without replacing it with a synonym.
	 *
	 * @since 4.2.4
	 *
	 * @param string $search_string Search string.
	 * @param array  $synonym       Single synonym data.
	 *
	 * @return string
	 */
	private function process_compound_source_no_replace( string $search_string, array $synonym ): string {

		return $search_string . ' ' . $synonym['synonyms'];
	}

	/**
	 * Process regular non-compound (one word) source.
	 *
	 * @since 4.2.3
	 *
	 * @param string $search_string Search string.
	 * @param string $source        Single source.
	 * @param array  $synonym       Single synonym data.
	 *
	 * @return string
	 */
	private function process_regular_source( string $search_string, string $source, array $synonym ): string {

		$search_string_before = $search_string;

		if ( $synonym['replace'] ) {
			$search_string = $this->process_regular_source_replace( $search_string, $source, $synonym );
		} else {
			$search_string = $this->process_regular_source_no_replace( $search_string, $source, $synonym );
		}

		if ( $search_string_before !== $search_string ) {
			$this->found_synonym = true;
		}

		return $search_string;

		// TODO: use searchwp\query\tokens\limit hook to adjust limit based on count( $synonym['synonyms'] ) if necessary?
	}

	/**
	 * Process regular non-compound (one word) source replacing it with a synonym.
	 *
	 * @since 4.2.3
	 *
	 * @param string $search_string Search string.
	 * @param string $source        Single source.
	 * @param array  $synonym       Single synonym data.
	 *
	 * @return string
	 */
	private function process_regular_source_replace( string $search_string, string $source, array $synonym ): string {

		if ( $this->is_not_strict_synonym_match( $search_string, $source ) ) {
			return $search_string;
		}

		$search_string = $this->replace_source_with_synonyms_in_string( $search_string, $source, $synonym );

		if ( isset( self::$synonym_groups[ $source ] ) ) {
			unset( self::$synonym_groups[ $source ] );
		}

		$this->add_synonym_tokens_to_synonym_groups( $synonym );

		return $search_string;
	}

	/**
	 * Process regular non-compound (one word) source without replacing it with a synonym.
	 *
	 * @since 4.2.3
	 *
	 * @param string $search_string Search string.
	 * @param string $source        Single source.
	 * @param array  $synonym       Single synonym data.
	 *
	 * @return string
	 */
	private function process_regular_source_no_replace( string $search_string, string $source, array $synonym ): string {

		$search_string .= ' ' . $synonym['synonyms'];

		if ( in_array( $source, array_keys( self::$synonym_groups ), true ) ) {
			self::$synonym_groups[ $source ] = array_merge( self::$synonym_groups[ $source ], array_map( 'trim', explode( ',', $synonym['synonyms'] ) ) );
		} else {
			self::$synonym_groups[ $source ] = array_map( 'trim', explode( ',', $synonym['synonyms'] ) );
		}

		return $search_string;
	}

	/**
	 * Replaces the synonym source with the synonyms in the string.
	 *
	 * @since 4.2.4
	 *
	 * @param string $search_string Search string.
	 * @param string $source        Single source.
	 * @param array  $synonym       Single synonym data.
	 *
	 * @return string
	 */
	private function replace_source_with_synonyms_in_string( string $search_string, string $source, array $synonym ): string {

		return trim(
			preg_replace(
				'/\s' . preg_quote( $source, '/' ) . '\s/iu',
				' ' . $synonym['synonyms'] . ' ',
				' ' . $search_string . ' '
			)
		);
	}

	/**
	 * Add tokens from a specific synonym to the synonym groups.
	 *
	 * @since 4.2.4
	 *
	 * @param array $synonym Single synonym data.
	 */
	private function add_synonym_tokens_to_synonym_groups( array $synonym ) {

		$synonyms = Str::remove_quotes( $synonym['synonyms'] );

		$replace_synonyms = explode( ' ', preg_replace( '/[,\s]+/', ' ', $synonyms ) );
		$new_tokens       = array_fill_keys( $replace_synonyms, [] );

		self::$synonym_groups = array_merge( self::$synonym_groups, $new_tokens );
	}

	/**
	 * Remove duplicate token between sources and synonyms from token groups.
	 *
	 * @since 4.2.3
	 *
	 * @return void
	 */
	private function remove_duplicate_tokens_from_token_groups(): void {

		$synonym_groups_keys = array_keys( self::$synonym_groups );

		foreach ( self::$synonym_groups as $tokens ) {
			foreach ( $tokens as $token ) {
				if ( in_array( $token, $synonym_groups_keys, true ) && empty( self::$synonym_groups[ $token ] ) ) {
					unset( self::$synonym_groups[ $token ] );
				}
			}
		}
	}

	/**
	 * Returns true if source and search string both have or both don't have quotes and the synonyms are strict.
	 *
	 * @since 4.2.4
	 *
	 * @param string $search_string Search string.
	 * @param string $source        Single source.
	 *
	 * @return bool
	 */
	private function is_not_strict_synonym_match( $search_string, $source ): bool {

		return apply_filters( 'searchwp\synonyms\strict', false )
			&& Str::contains( $search_string, '"' ) !== Str::contains( $source, '"'	);
	}

	/**
	 * Remove duplicate words from a string preserving quoted phrases.
	 *
	 * @since 4.2.4
	 *
	 * @param string $string Input string.
	 *
	 * @return string
	 */
	private function remove_duplicate_words_from_string( string $string ): string {

		// Extract any single keyword and preserve quoted phrases as a single entry.
		// "[^"]+" matches any quoted substring.
		// [^\s,]+ matches any single keyword separated by commas or spaces.
		preg_match_all( '/"[^"]+"|[^\s,]+/', $string, $matches );

		// Remove duplicates and return the final string.
		return implode( ' ', array_unique( $matches[0] ) );
	}
}