excerpts-highlights.php 50.7 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 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 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
<?php
/**
 * /lib/excerpts-highlights.php
 *
 * @package Relevanssi
 * @author  Mikko Saari
 * @license https://wordpress.org/about/gpl/ GNU General Public License
 * @see     https://www.relevanssi.com/
 */

/**
 * Generates an excerpt for a post.
 *
 * Takes the excerpt length and type as parameters. These can be omitted, in
 * which case the values are taken from the 'relevanssi_excerpt_length' and
 * 'relevanssi_excerpt_type' options respectively.
 *
 * @global $post The global post object.
 *
 * @param object $t_post         The post object.
 * @param string $query          The search query.
 * @param int    $excerpt_length The length of the excerpt, default null.
 * @param string $excerpt_type   Either 'chars' or 'words', default null.
 *
 * @return string The created excerpt.
 */
function relevanssi_do_excerpt( $t_post, $query, $excerpt_length = null, $excerpt_type = null ) {
	global $post;

	if ( ! $excerpt_length ) {
		$excerpt_length = get_option( 'relevanssi_excerpt_length' );
	}
	if ( ! $excerpt_type ) {
		$excerpt_type = get_option( 'relevanssi_excerpt_type' );
	}

	// Back up the global post object, and replace it with the post we're working on.
	$old_global_post = null;
	if ( null !== $post ) {
		$old_global_post = $post;
	}
	/**
	 * Allows filtering the indexed post before building an excerpt from it.
	 *
	 * @param object $post The post object.
	 */
	$post = apply_filters( 'relevanssi_post_to_excerpt', $t_post ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited

	$remove_stopwords = 'body';

	/**
	 * Filters the search query before excerpt-building.
	 *
	 * Allows filtering the search query before generating an excerpt. This can
	 * useful if you make modifications to the search query, and it may also
	 * help when working with stemming.
	 *
	 * @param string $query The search query.
	 */
	$query = apply_filters( 'relevanssi_excerpt_query', $query );

	$min_word_length = 2;
	/**
	 * Allows creating one-letter highlights.
	 *
	 * @param boolean Set to true to enable one-letter highlights.
	 */
	if ( apply_filters( 'relevanssi_allow_one_letter_highlights', false ) ) {
		$min_word_length = 1;
	}

	$terms = relevanssi_tokenize( $query, $remove_stopwords, $min_word_length, 'search_query' );

	if ( is_array( $query ) ) {
		$untokenized_terms = array_filter( $query );
	} else {
		$untokenized_terms = array_filter( explode( ' ', $query ) );
	}
	$untokenized_terms = array_map(
		function ( $term ) {
			if ( is_numeric( $term ) ) {
				$term = " $term";
			}
			return $term;
		},
		$untokenized_terms
	);

	$untokenized_terms = array_flip(
		relevanssi_remove_stopwords_from_array( $untokenized_terms )
	);
	$terms             = array_merge( $untokenized_terms, $terms );

	// These shortcodes cause problems with Relevanssi excerpts.
	$problem_shortcodes = array( 'layerslider', 'responsive-flipbook', 'breadcrumb', 'robogallery', 'gravityview', 'wp_show_posts' );
	/**
	 * Filters the excerpt-building problem shortcodes.
	 *
	 * Some shortcodes cause problems in Relevanssi excerpt-building. These
	 * shortcodes are disabled before building the excerpt. This filter allows
	 * modifying the list of shortcodes.
	 *
	 * @param array $problem_shortcodes Array of problematic shortcode names.
	 */
	$problem_shortcodes = apply_filters( 'relevanssi_disable_shortcodes_excerpt', $problem_shortcodes );
	array_walk( $problem_shortcodes, 'remove_shortcode' );

	/**
	 * Filters the post content before 'the_content'.
	 *
	 * Filters the post content in excerpt building process before 'the_content'
	 * filter is applied.
	 *
	 * @param string $content The post content.
	 * @param object $post    The post object.
	 * @param string $query   The search query.
	 */
	$content = apply_filters( 'relevanssi_pre_excerpt_content', $post->post_content, $post, $query );

	$pattern = get_shortcode_regex( $problem_shortcodes );
	$content = preg_replace_callback( "/$pattern/", 'strip_shortcode_tag', $content );

	// Add the custom field content.
	if ( 'on' === get_option( 'relevanssi_excerpt_custom_fields' )
		&& 'off' === get_option( 'relevanssi_excerpt_specific_fields' ) ) {
		if ( 'user' === $post->post_type && function_exists( 'relevanssi_get_user_custom_field_content' ) ) {
			$content .= relevanssi_get_user_custom_field_content( $post->ID );
		} else {
			$field_content = relevanssi_get_custom_field_content( $post->ID );
			$content      .= $field_content[0];
		}
	}

	/**
	 * Runs before Relevanssi excerpt building applies `the_content`.
	 */
	do_action( 'relevanssi_pre_the_content' );

	/** This filter is documented in wp-includes/post-template.php */
	$content = apply_filters( 'the_content', $content );

	/**
	 * Runs after Relevanssi excerpt building applies `the_content`.
	 */
	do_action( 'relevanssi_post_the_content' );

	/**
	 * Filters the post content after 'the_content'.
	 *
	 * Filters the post content in excerpt building process after 'the_content'
	 * filter is applied.
	 *
	 * @param string $content The post content.
	 * @param object $post    The post object.
	 * @param string $query   The search query.
	 */
	$content = apply_filters( 'relevanssi_excerpt_content', $content, $post, $query );
	$content = relevanssi_strip_tags( $content );

	// Replace linefeeds and carriage returns with spaces.
	$content = preg_replace( "/\n\r|\r\n|\n|\r/", ' ', $content );

	// Replace spaces inside HTML tags to avoid splitting tags when doing
	// word-based excerpts.
	$content = preg_replace_callback(
		'~<([!a-zA-Z\/][^>].*?)>~s',
		function ( $matches ) {
			return '<' . str_replace( ' ', '*VÄLILYÖNTI*', $matches[1] ) . '>';
		},
		$content
	);

	if ( 'OR' === get_option( 'relevanssi_implicit_operator' )
		|| 'on' === get_option( 'relevanssi_index_synonyms' ) ) {
		$query = relevanssi_add_synonyms( $query );
	}

	// Find the appropriate spot from the post.
	$excerpts = relevanssi_create_excerpts( $content, $terms, $query, $excerpt_length, $excerpt_type );
	if ( function_exists( 'relevanssi_add_source_to_excerpts' ) ) {
		relevanssi_add_source_to_excerpts( $excerpts, 'content' );
	}

	$custom_field_excerpts = array();
	if ( 'on' === get_option( 'relevanssi_excerpt_specific_fields' )
		&& 'on' === get_option( 'relevanssi_excerpt_custom_fields' ) ) {
		$custom_field_content  = relevanssi_get_custom_field_content( $post->ID );
		$custom_field_excerpts = array();
		foreach ( $custom_field_content as $field => $value ) {
			$field_excerpts = relevanssi_create_excerpts(
				$value,
				$terms,
				$query,
				$excerpt_length,
				$excerpt_type
			);
			if ( function_exists( 'relevanssi_add_source_to_excerpts' ) ) {
				relevanssi_add_source_to_excerpts( $field_excerpts, $field );
				$field_excerpts = array_filter(
					$field_excerpts,
					function ( $excerpt ) {
						return $excerpt['hits'];
					}
				);
			} elseif ( is_array( $field_excerpts ) ) {
				if ( $field_excerpts[0]['hits'] > $excerpts[0]['hits'] ) {
					$excerpts = $field_excerpts;
				}
			}
			$custom_field_excerpts = array_merge( $custom_field_excerpts, $field_excerpts );
		}
	}

	$comment_excerpts = array();
	if ( 'none' !== get_option( 'relevanssi_index_comments' ) ) {
		$comment_content = relevanssi_strip_tags( relevanssi_get_comments( $post->ID ) );
		if ( ! empty( $comment_content ) ) {
			$comment_excerpts = relevanssi_create_excerpts(
				$comment_content,
				$terms,
				$query,
				$excerpt_length,
				$excerpt_type
			);
			if ( function_exists( 'relevanssi_add_source_to_excerpts' ) ) {
				relevanssi_add_source_to_excerpts( $comment_excerpts, 'comments' );
				$comment_excerpts = array_filter(
					$comment_excerpts,
					function ( $excerpt ) {
						return $excerpt['hits'];
					}
				);
			} elseif ( is_array( $comment_excerpts ) ) {
				if ( $comment_excerpts[0]['hits'] > $excerpts[0]['hits'] ) {
					$excerpts = $comment_excerpts;
				}
			}
		}
	}

	$excerpt_excerpts = array();
	if ( 'off' !== get_option( 'relevanssi_index_excerpt' ) ) {
		$excerpt_content = relevanssi_strip_tags( $post->post_excerpt );
		if ( ! empty( $excerpt_content ) ) {
			$excerpt_excerpts = relevanssi_create_excerpts(
				$excerpt_content,
				$terms,
				$query,
				$excerpt_length,
				$excerpt_type
			);
			if ( function_exists( 'relevanssi_add_source_to_excerpts' ) ) {
				relevanssi_add_source_to_excerpts( $excerpt_excerpts, 'excerpt' );
				$excerpt_excerpts = array_filter(
					$excerpt_excerpts,
					function ( $excerpt ) {
						return $excerpt['hits'];
					}
				);
			} elseif ( is_array( $excerpt_excerpts ) ) {
				if ( $excerpt_excerpts[0]['hits'] > $excerpts[0]['hits'] ) {
					$excerpts = $excerpt_excerpts;
				}
			}
		}
	}

	if ( function_exists( 'relevanssi_combine_excerpts' ) ) {
		$excerpts = relevanssi_combine_excerpts(
			$post->ID,
			$excerpts,
			$comment_excerpts,
			$excerpt_excerpts,
			$custom_field_excerpts
		);
	}

	/**
	 * Filters the ellipsis Relevanssi uses in excerpts.
	 *
	 * @param string $ellipsis Default '...'.
	*/
	$ellipsis  = apply_filters( 'relevanssi_ellipsis', '...' );
	$highlight = get_option( 'relevanssi_highlight' );

	$excerpt_text = '';

	foreach ( $excerpts as $excerpt ) {
		$whole_post_excerpted = false;
		if ( $excerpt['text'] === $post->post_content ) {
			$whole_post_excerpted = true;
		}

		/**
		 * Filters excerpt text.
		 *
		 * Filters the individual excerpt part text (full excerpt in the free
		 * version) before highlighting and ellipsis addition.
		 *
		 * @param string The excerpt text.
		 * @param int    The post ID.
		 *
		 * @return string
		 */
		$excerpt['text'] = apply_filters( 'relevanssi_excerpt', $excerpt['text'], $post->ID );

		if ( 'none' !== $highlight ) {
			if ( ! is_admin() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
				$excerpt['text'] = relevanssi_highlight_terms( $excerpt['text'], $query );
			}
		}

		if ( ! empty( $excerpt['text'] ) ) {
			$excerpt['text'] = relevanssi_close_tags( $excerpt['text'] );
		}

		if ( ! $whole_post_excerpted ) {
			if ( ! $excerpt['start'] && ! empty( $excerpt['text'] ) ) {
				$excerpt['text'] = $ellipsis . $excerpt['text'];
			}

			if ( ! empty( $excerpt['text'] ) ) {
				$excerpt['text'] = $excerpt['text'] . $ellipsis;
			}
		}

		/**
		 * Filters individual excerpt parts.
		 *
		 * Filters the individual excerpt parts (full excerpt in the free
		 * version) after highlighting, ellipsis and the wrapping span tag have
		 * been added.
		 *
		 * @param string The excerpt text.
		 * @param array  The excerpt array (keys 'text', 'start', 'source',
		 * 'hits').
		 * @param int    The post ID.
		 *
		 * @return string
		 */
		$excerpt_text .= apply_filters(
			'relevanssi_excerpt_part',
			'<span class="excerpt_part">' . $excerpt['text'] . '</span>',
			$excerpt,
			$post->ID
		);
	}

	if ( null !== $old_global_post ) {
		$post = $old_global_post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
	}

	return $excerpt_text;
}

/**
 * Creates an excerpt from content.
 *
 * This is provided for backwards compatibility. The new version of the function
 * supports the Premium capability to return multiple excerpts. Since that
 * changes the return value of the function, this function is provided to
 * return the original return value.
 *
 * @uses relevanssi_create_excerpts()
 *
 * @param string $content        The content.
 * @param array  $terms          The search terms, tokenized.
 * @param string $query          The search query.
 * @param int    $excerpt_length The length of the excerpt, default 30.
 * @param string $excerpt_type   Either 'chars' or 'words', default 'words'.
 *
 * @return array Element 0 is the excerpt, element 1 the number of term hits,
 * element 2 is true, if the excerpt is from the start of the content.
 */
function relevanssi_create_excerpt( $content, $terms, $query, $excerpt_length = 30, $excerpt_type = 'words' ) {
	$excerpts = relevanssi_create_excerpts( $content, $terms, $query, $excerpt_length, $excerpt_type );
	usort(
		$excerpts,
		function ( $a, $b ) {
			return $b['hits'] - $a['hits'];
		}
	);

	$excerpt = array(
		0 => $excerpts[0]['text'],
		1 => $excerpts[0]['hits'],
		2 => $excerpts[0]['start'],
	);
	return $excerpt;
}

/**
 * Creates an excerpt from content.
 *
 * Relevanssi Premium has the capability to generate multiple excerpts from one
 * post. While the free version only generates one excerpt per post, this
 * function supports the multiple excerpt behaviour by returning an array of
 * excerpts, even though just one excerpt is returned.
 *
 * @see relevanssi_create_excerpt()
 *
 * @param string $content        The content.
 * @param array  $terms          The search terms, tokenized.
 * @param string $query          The search query.
 * @param int    $excerpt_length The length of the excerpt, default 30.
 * @param string $excerpt_type   Either 'chars' or 'words', default 'words'.
 *
 * @return array An array of excerpts. In each excerpt, there are following
 * parts: 'text' has the excerpt text, 'hits' the number of keyword matches in
 * the excerpt, 'start' is true if the excerpt is from the beginning of the
 * content.
 */
function relevanssi_create_excerpts( $content, $terms, $query, $excerpt_length = 30, $excerpt_type = 'words' ) {
	$content = preg_replace( '/\s+/u', ' ', $content );
	if ( ' ' !== relevanssi_substr( $content, 0, 1 ) ) {
		$content = ' ' . $content;
	}
	$content = html_entity_decode( $content );
	// Finds all the phrases in the query.
	$phrases = relevanssi_extract_phrases( stripslashes( $query ) );
	$terms   = relevanssi_remove_quotes_from_array_keys( $terms );

	/**
	 * This process generates an array of terms, which has single terms and all the
	 * phrases.
	 */
	$remove_stopwords = false;
	$non_phrase_terms = array();
	foreach ( $phrases as $phrase ) {
		$phrase_terms = array_keys( relevanssi_tokenize( $phrase, $remove_stopwords, -1, 'search_query' ) );
		foreach ( array_keys( $terms ) as $term ) { // array_keys(), because tokenized terms have the term as key.
			if ( ! in_array( $term, $phrase_terms, true ) ) {
				$non_phrase_terms[ $term ] = true;
			}
		}

		$terms            = $non_phrase_terms;
		$terms[ $phrase ] = true;
	}

	// Sort the longest search terms first, because those are generally more significant.
	uksort( $terms, 'relevanssi_strlen_sort' );

	$excerpts = array();
	$start    = false;
	if ( 'chars' === $excerpt_type ) {
		$prev_count = floor( $excerpt_length / 6 );

		list( $excerpt_text, $best_excerpt_term_hits, $start ) =
		relevanssi_extract_relevant(
			array_keys( $terms ),
			$content,
			$excerpt_length + 1, // There's one space in the beginning of the content.
			$prev_count
		);
		$excerpt    = array(
			'text'  => $excerpt_text,
			'hits'  => $best_excerpt_term_hits,
			'start' => $start,
		);
		$excerpts[] = $excerpt;
	} elseif ( function_exists( 'relevanssi_extract_multiple_excerpts' ) && get_option( 'relevanssi_max_excerpts', 1 ) > 1 ) {
		$excerpts = relevanssi_extract_multiple_excerpts(
			array_keys( $terms ),
			$content,
			$excerpt_length
		);
	} else {
		list( $excerpt_text, $best_excerpt_term_hits, $start ) =
		relevanssi_extract_relevant_words(
			array_keys( $terms ),
			$content,
			$excerpt_length
		);
		$excerpt    = array(
			'text'  => $excerpt_text,
			'hits'  => $best_excerpt_term_hits,
			'start' => $start,
		);
		$excerpts[] = $excerpt;
	}

	array_walk(
		$excerpts,
		function ( &$excerpt ) {
			$excerpt['text'] = str_replace( '*VÄLILYÖNTI*', ' ', $excerpt['text'] );
		}
	);
	return $excerpts;
}

/**
 * Manages the highlighting in documents.
 *
 * Uses relevanssi_highlight_terms() to do the highlighting. Attached to
 * 'the_content' and 'comment_text' filter hooks.
 *
 * @global object  $wp_query               The global WP_Query object.
 * @global boolean $relevanssi_test_enable If true, this is a test.
 *
 * @param string $content The content to highlight.
 *
 * @return string The content with highlights.
 */
function relevanssi_highlight_in_docs( $content ) {
	global $wp_query, $relevanssi_test_enable;
	if ( ( is_singular() && is_main_query() ) || $relevanssi_test_enable ) {
		if ( isset( $wp_query->query_vars['highlight'] ) ) {
			// Local search.
			$query   = relevanssi_add_synonyms( $wp_query->query_vars['highlight'] );
			$in_docs = true;

			$highlighted_content = relevanssi_highlight_terms( $content, $query, $in_docs );
			if ( ! empty( $highlighted_content ) ) {
				// Sometimes the content comes back empty; until I figure out why, this tries to be a solution.
				$content = $highlighted_content;
			}
		}
	}

	return $content;
}

/**
 * Adds highlighting to content.
 *
 * Adds highlighting to content based on Relevanssi highlighting settings (if
 * you want to override the settings, 'pre_option_relevanssi_highlight' filter
 * hook is your friend).
 *
 * @param string       $content          The content to highlight.
 * @param string|array $query            The search query (should be a string,
 * can also be an array of string).
 * @param boolean      $convert_entities Are we highlighting post content?
 * Default false.
 *
 * @return string The $content with highlighting.
 */
function relevanssi_highlight_terms( $content, $query, $convert_entities = false ) {
	$type = get_option( 'relevanssi_highlight' );
	if ( 'none' === $type ) {
		return $content;
	}

	switch ( $type ) {
		case 'mark':
			$start_emp = '<mark>';
			$end_emp   = '</mark>';
			break;
		case 'strong':
			$start_emp = '<strong>';
			$end_emp   = '</strong>';
			break;
		case 'em':
			$start_emp = '<em>';
			$end_emp   = '</em>';
			break;
		case 'col':
			$col = get_option( 'relevanssi_txt_col' );
			if ( ! $col ) {
				$col = '#ff0000';
			}
			$start_emp = "<span style='color: $col'>";
			$end_emp   = '</span>';
			break;
		case 'bgcol':
			$col = get_option( 'relevanssi_bg_col' );
			if ( ! $col ) {
				$col = '#ff0000';
			}
			$start_emp = "<span style='background-color: $col'>";
			$end_emp   = '</span>';
			break;
		case 'css':
			$css = get_option( 'relevanssi_css' );
			if ( ! $css ) {
				$css = 'color: #ff0000';
			}
			$start_emp = "<span style='$css'>";
			$end_emp   = '</span>';
			break;
		case 'class':
			$css = get_option( 'relevanssi_class' );
			if ( ! $css ) {
				$css = 'relevanssi-query-term';
			}
			$start_emp = "<span class='$css'>";
			$end_emp   = '</span>';
			break;
		default:
			return $content;
	}

	$start_emp_token = '**{[';
	$end_emp_token   = ']}**';

	if ( function_exists( 'mb_internal_encoding' ) ) {
		mb_internal_encoding( 'UTF-8' );
	}

	/**
	 * Runs before tokenizing the terms in highlighting.
	 */
	do_action( 'relevanssi_highlight_tokenize' );

	/**
	 * Filters the query during highlighting before tokenizing it.
	 *
	 * This filter hook allows you to modify the search query when it is used
	 * in highlighting. You could, for example, remove unwanted words from the
	 * search term or to force phrase highlighting for non-phrase searches.
	 *
	 * @param string $query The search query.
	 */
	$query = apply_filters( 'relevanssi_highlight_query', $query );

	// Setting min_word_length to 2, in order to avoid 1-letter highlights.
	$min_word_length = 2;
	/**
	 * Allows creating one-letter highlights.
	 *
	 * @param boolean Set to true to enable one-letter highlights.
	 */
	if ( apply_filters( 'relevanssi_allow_one_letter_highlights', false ) ) {
		$min_word_length = 1;
	}

	$remove_stopwords = 'body';
	$terms            = array_keys(
		relevanssi_tokenize(
			$query,
			$remove_stopwords,
			$min_word_length,
			'search_query'
		)
	);

	if ( ! is_array( $query ) ) {
		$query = explode( ' ', relevanssi_strtolower( $query ) );
	}

	$body_stopwords = function_exists( 'relevanssi_fetch_body_stopwords' )
		? relevanssi_fetch_body_stopwords()
		: array();

	$untokenized_terms = array_filter(
		$query,
		function ( $value ) use ( $min_word_length, $body_stopwords ) {
			if ( in_array( $value, $body_stopwords, true ) ) {
				return false;
			}
			if ( relevanssi_strlen( $value ) > $min_word_length ) {
				return true;
			}
			return false;
		}
	);

	$terms = array_unique( array_merge( $untokenized_terms, $terms ) );
	array_walk( $terms, 'relevanssi_array_walk_trim' ); // Numeric search terms begin with a space.

	if ( is_array( $query ) ) {
		$query = implode( ' ', $query );
	}
	$phrases = relevanssi_extract_phrases( stripslashes( $query ) );

	$remove_stopwords = false;
	$non_phrase_terms = array();
	foreach ( $phrases as $phrase ) {
		$phrase_terms = array_keys( relevanssi_tokenize( $phrase, $remove_stopwords, -1, 'search_query' ) );
		foreach ( $terms as $term ) {
			if ( ! in_array( $term, $phrase_terms, true ) ) {
				$non_phrase_terms[] = $term;
			}
		}
		$terms   = $non_phrase_terms;
		$terms[] = $phrase;
	}

	usort( $terms, 'relevanssi_strlen_sort' );

	$content = strtr( $content, array( "\xC2\xAD" => '' ) );
	$content = relevanssi_entity_decode( $content, ENT_QUOTES, 'UTF-8' );

	if ( ! $convert_entities ) {
		$content = str_replace( "\n", ' ', $content );
	}

	foreach ( $terms as $term ) {
		$pr_term = preg_quote( $term, '/' );
		$pr_term = relevanssi_add_accent_variations( $pr_term );

		// Support for wildcard matching (a Premium feature).
		$pr_term = str_replace(
			array( '\*', '\?' ),
			array( '\S*', '.' ),
			$pr_term
		);

		$regex       = "/([\W])($pr_term)([\W])/iu";
		$three_parts = true;

		if ( 'never' !== get_option( 'relevanssi_fuzzy' ) ) {
			$regex       = "/([\W]{$pr_term}|{$pr_term}[\W])/iu";
			$three_parts = false;
		}

		if ( 'on' === get_option( 'relevanssi_expand_highlights' ) ) {
			$regex       = "/([\w]*{$pr_term}[\W]|[\W]{$pr_term}[\w]*)/iu";
			$three_parts = false;
		}

		if ( $three_parts ) {
			$replace = '\\1' . $start_emp_token . '\\2' . $end_emp_token . '\\3';
		} else {
			$replace = $start_emp_token . '\\1' . $end_emp_token;
		}

		/**
		 * Filters the regular expression used for highlighting.
		 *
		 * @param array  $array   The regex and the replacement.
		 */
		$regex = apply_filters( 'relevanssi_highlight_regex', $regex, $pr_term );

		// Add an extra space so that the regex that looks for a non-word
		// character after the search term will find one, even if the word is
		// at the end of the content (especially in titles).
		$content .= ' ';

		$content = trim(
			preg_replace(
				$regex,
				$replace,
				' ' . $content
			)
		);
		/**
		 * The method here leaves extra spaces or HTML tag closing brackets
		 * inside the highlighting. That is cleaned away here.
		 */
		$replace_regex = '/(.)(' . preg_quote( $start_emp_token, '/' ) . ')(>|\s)/iu';
		$content       = preg_replace( $replace_regex, '\1\3\2', $content );

		$replace_regex = '/^(' . preg_quote( $start_emp_token, '/' ) . ')\s/iu';
		$content       = preg_replace( $replace_regex, '\1', $content );

		$replace_regex = '/(\s)(' . preg_quote( $end_emp_token, '/' ) . ')(.)/iu';
		$content       = preg_replace( $replace_regex, '\2\1\3', $content );

		$replace_regex = '/\s(' . preg_quote( $end_emp_token, '/' ) . ')/iu';
		$content       = preg_replace( $replace_regex, '\1', $content );

		// The starting tokens can get interlaced this way, let's unknot them.
		$content = str_replace(
			substr( $start_emp_token, 0, -1 ) . $start_emp_token . substr( $start_emp_token, -1, 1 ),
			$start_emp_token . $start_emp_token,
			$content
		);

		if ( preg_match_all( '/<.*>/Usm', $content, $matches ) > 0 ) {
			// Remove highlights from inside HTML tags.
			foreach ( $matches as $match ) {
				$new_match = str_replace( $start_emp_token, '', $match );
				$new_match = str_replace( $end_emp_token, '', $new_match );
				$content   = str_replace( $match, $new_match, $content );
			}
		}

		$start_quoted = preg_quote( $start_emp_token, '/' );
		$end_quoted   = preg_quote( $end_emp_token, '/' );
		if (
			preg_match_all(
				'/&' . $start_quoted . '([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6})' . $end_quoted . ';/U',
				$content,
				$matches
			) > 0 ) {
			// Remove highlights from inside HTML entities.
			foreach ( $matches as $match ) {
				$new_match = str_replace( $start_emp_token, '', $match );
				$new_match = str_replace( $end_emp_token, '', $new_match );
				$content   = str_replace( $match, $new_match, $content );
			}
		}

		if ( preg_match_all( '/<(style|script|object|embed|pre|code).*<\/(style|script|object|embed|pre|code)>/Us', $content, $matches ) > 0 ) {
			// Remove highlights in style, object, embed, script and pre tags.
			foreach ( $matches as $match ) {
				$new_match = str_replace( $start_emp_token, '', $match );
				$new_match = str_replace( $end_emp_token, '', $new_match );
				$content   = str_replace( $match, $new_match, $content );
			}
		}
	}

	$content = relevanssi_remove_nested_highlights( $content, $start_emp_token, $end_emp_token );
	$content = relevanssi_fix_entities( $content, $convert_entities );

	/**
	 * Allows cleaning unwanted highlights.
	 *
	 * This filter lets you clean unwanted highlights, for example from within
	 * <pre> tags. To remove a highlight, remove the matching starting and
	 * ending tokens from the $content string.
	 *
	 * @param string $content         The highlighted content.
	 * @param string $start_emp_token A token that signifies the start of a
	 * highlight.
	 * @param string $end_emp_token   A token that signifies the end of a
	 * highlight.
	 *
	 * @return string The highlighted content.
	 */
	$content = apply_filters(
		'relevanssi_clean_excerpt',
		$content,
		$start_emp_token,
		$end_emp_token
	);

	$content = str_replace( $start_emp_token, $start_emp, $content );
	$content = str_replace( $end_emp_token, $end_emp, $content );
	$content = str_replace( $end_emp . $start_emp, '', $content );
	if ( function_exists( 'mb_ereg_replace' ) ) {
		$pattern = $end_emp . '\s*' . $start_emp;
		$content = mb_ereg_replace( $pattern, ' ', $content );
	}

	return $content;
}

/**
 * Fixes problems with entities.
 *
 * For excerpts, runs htmlentities() on the excerpt, then converts the allowed
 * tags back into tags.
 *
 * @param string  $excerpt The excerpt to fix.
 * @param boolean $in_docs If true, we are manipulating post content, and need
 * to work in a different fashion.
 *
 * @return string The $excerpt with entities fixed.
 */
function relevanssi_fix_entities( $excerpt, $in_docs ) {
	if ( ! $in_docs ) {
		// For excerpts, use htmlentities() to convert.
		$excerpt = htmlentities( $excerpt, ENT_NOQUOTES, 'UTF-8' );

		// Except for allowed tags, which are turned back into tags.
		$tags = get_option( 'relevanssi_excerpt_allowable_tags', '' );
		$tags = trim( str_replace( '<', ' <', $tags ) );
		$tags = explode( ' ', $tags );

		$closing_tags = relevanssi_generate_closing_tags( $tags );

		$tags_entitied = htmlentities(
			implode(
				' ',
				$tags
			),
			ENT_NOQUOTES,
			'UTF-8'
		);
		$tags_entitied = explode( ' ', $tags_entitied );

		$closing_tags_entitied = htmlentities(
			implode(
				' ',
				$closing_tags
			),
			ENT_NOQUOTES,
			'UTF-8'
		);
		$closing_tags_entitied = explode( ' ', $closing_tags_entitied );

		$tags_entitied_regexped = array();

		$i = 0;
		foreach ( $tags_entitied as $tag ) {
			$tag     = str_replace( '&gt;', '(.*?)&gt;', $tag );
			$pattern = "~$tag~";

			$tags_entitied_regexped[] = $pattern;

			$matching_tag = $tags[ $i ];
			$matching_tag = str_replace( '>', '\1>', $matching_tag );
			$tags[ $i ]   = $matching_tag;
			++$i;
		}

		$closing_tags_entitied_regexped = array();
		foreach ( $closing_tags_entitied as $tag ) {
			$pattern = '~' . preg_quote( $tag, '~' ) . '~';

			$closing_tags_entitied_regexped[] = $pattern;
		}

		$tags          = array_merge( $tags, $closing_tags );
		$tags_entitied = array_merge(
			$tags_entitied_regexped,
			$closing_tags_entitied_regexped
		);

		$excerpt = preg_replace( $tags_entitied, $tags, $excerpt );

		// In case there are attributes. This is the easiest solution, as
		// using quotes and apostrophes un-entitied can't really break
		// anything.
		$excerpt = str_replace( '&quot;', '"', $excerpt );
		$excerpt = str_replace( '&#039;', "'", $excerpt );
	} else {
		// Running htmlentities() for whole posts tends to ruin things.
		// However, we may want to run htmlentities() for anything inside
		// <pre> and <code> tags.
		/**
		 * Choose whether htmlentities() is run inside <pre> tags or not. If
		 * your pages have HTML code inside <pre> tags, set this to false.
		 *
		 * @param boolean If true, htmlentities() will be used inside <pre>
		 * tags.
		 */
		if ( apply_filters( 'relevanssi_entities_inside_pre', true ) ) {
			$excerpt = relevanssi_entities_inside( $excerpt, 'pre' );
		}
		/**
		 * Choose whether htmlentities() is run inside <code> tags or not. If
		 * your pages have HTML code inside <code> tags, set this to false.
		 *
		 * @param boolean If true, htmlentities() will be used inside <code>
		 * tags.
		 */
		if ( apply_filters( 'relevanssi_entities_inside_code', true ) ) {
			$excerpt = relevanssi_entities_inside( $excerpt, 'code' );
		}
	}
	return $excerpt;
}

/**
 * Runs htmlentities() for content inside specified tags.
 *
 * @param string $content The content.
 * @param string $tag     The tag.
 *
 * @return string $content The content with HTML code inside the $tag tags
 * ran through htmlentities().
 */
function relevanssi_entities_inside( $content, $tag ) {
	$hits = preg_match_all( '/<' . $tag . '.*?>(.*?)<\/' . $tag . '>/ims', $content, $matches );
	if ( $hits > 0 ) {
		$replacements = array();
		foreach ( $matches[1] as $match ) {
			if ( ! empty( $match ) ) {
				$replacements[] = '<xxx' . $tag . '\1>'
					. htmlentities( $match, ENT_QUOTES, 'UTF-8' )
					. '</xxx' . $tag . '>';
			}
		}
		if ( ! empty( $replacements ) ) {
			$count_replacements = count( $replacements );
			for ( $i = 0; $i < $count_replacements; $i++ ) {
				$patterns[] = '/<' . $tag . '(.*?)>(.*?)<\/' . $tag . '>/ims';
			}
			$content = preg_replace( $patterns, $replacements, $content, 1 );
		}
		$content = str_replace( 'xxx' . $tag, $tag, $content );
	}
	return $content;
}

/**
 * Removes nested highlights from a string.
 *
 * If there are highlights within highlights in a string, this function will
 * clean out the nested highlights, leaving just the outmost highlight tokens.
 *
 * @param string $str    The content.
 * @param string $begin  The beginning highlight token.
 * @param string $end    The ending highlight token.
 *
 * @return string The string with nested highlights cleaned out.
 */
function relevanssi_remove_nested_highlights( $str, $begin, $end ) {
	$bits       = explode( $begin, $str );
	$new_bits   = array( $bits[0] );
	$count_bits = count( $bits );
	$depth      = -1;
	for ( $i = 1; $i < $count_bits; $i++ ) {
		++$depth;
		if ( 0 === $depth ) {
			$new_bits[] = $begin;
		}
		if ( empty( $bits[ $i ] ) ) {
			continue;
		}
		$end_count = substr_count( $bits[ $i ], $end );
		if ( $end_count ) {
			if ( substr_count( $bits[ $i ], $end ) < $depth ) {
				$new_bits[] = str_replace( $end, '', $bits[ $i ], $count );
				$depth     -= $count;
			} elseif ( substr_count( $bits[ $i ], $end ) >= $depth ) {
				$end_p      = preg_quote( $end, '#' );
				$new_bits[] = preg_replace( '#' . $end_p . '#', '', $bits[ $i ], $depth );
				$depth      = -1;
			}
		} else {
			$new_bits[] = $bits[ $i ];
		}
	}
	return join( '', $new_bits );
}

/**
 * Finds the locations of each word.
 *
 * Originally lifted from http://www.boyter.org/2013/04/building-a-search-result-extract-generator-in-php/
 * Finds the location of each word in the fulltext.
 *
 * @author Ben Boyter
 *
 * @param array  $words    An array of words to locate.
 * @param string $fulltext The fulltext where to find them.
 *
 * @return array Array of locations.
 */
function relevanssi_extract_locations( $words, $fulltext ) {
	$locations = array();
	foreach ( $words as $word ) {
		$count_locations = 0;
		$wordlen         = relevanssi_strlen( $word );
		$loc             = relevanssi_stripos( $fulltext, $word, 0 );
		while ( false !== $loc ) {
			$locations[] = $loc;
			$loc         = relevanssi_stripos( $fulltext, $word, $loc + $wordlen );
			++$count_locations;
			/**
			 * Optimizes the excerpt creation.
			 *
			 * @param boolean If true, stop looking after ten locations are found.
			 */
			if ( apply_filters( 'relevanssi_optimize_excerpts', false ) ) {
				// If more than ten locations are found, quit: there's probably a
				// good one in there, and this saves plenty of time.
				if ( $count_locations > 10 ) {
					break;
				}
			}
		}
	}

	$locations = array_unique( $locations );
	sort( $locations );

	return $locations;
}

/**
 * Counts how many times the words appear in the text.
 *
 * @param array  $words         An array of words.
 * @param string $complete_text The text where to count the words.
 *
 * @return int Number of times the words appear in the text.
 */
function relevanssi_count_matches( $words, $complete_text ) {
	$count = 0;
	$text  = '';

	// Add the space in case the match is the last word in the text.
	$lowercase_text = relevanssi_strtolower( $complete_text, 'UTF-8' ) . ' ';

	$count_words = count( $words );
	for ( $t = 0; $t < $count_words; $t++ ) {
		$word_slice = relevanssi_strtolower(
			relevanssi_add_accent_variations(
				preg_quote(
					$words[ $t ],
					'/'
				)
			),
			'UTF-8'
		);
		// Support for wildcard matching (a Premium feature).
		$word_slice = str_replace(
			array( '\*', '\?' ),
			array( '\S*', '.' ),
			$word_slice
		);

		if ( 'never' !== get_option( 'relevanssi_fuzzy' ) ) {
			$regex = "/[\W]{$word_slice}|{$word_slice}[\W]/iu";
		} else {
			$regex = "/[\W]{$word_slice}[\W]/iu";
		}

		$lines = preg_split( $regex, $lowercase_text );
		if ( $lines && count( $lines ) > 1 ) {
			$count_lines = count( $lines );
			for ( $tt = 0; $tt < $count_lines; $tt++ ) {
				if ( $tt < ( count( $lines ) - 1 ) ) {
					$text = $text . $lines[ $tt ] . '=***=';
				} else {
					$text = $text . $lines[ $tt ];
				}
			}
		}
	}

	$lines = explode( '=***=', $text );
	$count = count( $lines ) - 1;

	return $count;
}

/**
 * Works out which is the most relevant portion to display.
 *
 * This is done by looping over each match and finding the smallest distance
 * between two found strings. The idea being that the closer the terms are the
 * better match the snippet would be. When checking for matches we only change
 * the location if there is a better match. The only exception is where we have
 * only two matches in which case we just take the first as will be equally
 * distant.
 *
 * @author Ben Boyter
 *
 * @param array $locations Locations of the words.
 * @param int   $prevcount How much text to include before the location.
 *
 * @return int Starting position for the snippet.
 */
function relevanssi_determine_snip_location( $locations, $prevcount ) {
	if ( ! is_array( $locations ) || empty( $locations ) ) {
		return 0;
	}

	// If we only have 1 match we dont actually do the for loop so set to the first.
	$startpos     = $locations[0];
	$loc_count    = count( $locations );
	$smallestdiff = PHP_INT_MAX;

	// If we only have 2 skip as its probably equally relevant.
	if ( $loc_count > 2 ) {
		// Skip the first as we check 1 behind.
		for ( $i = 1; $i < $loc_count; $i++ ) {
			if ( $i === $loc_count - 1 ) { // At the end.
				$diff = $locations[ $i ] - $locations[ $i - 1 ];
			} else {
				$diff = $locations[ $i + 1 ] - $locations[ $i ];
			}

			if ( $smallestdiff > $diff ) {
				$smallestdiff = $diff;
				$startpos     = $locations[ $i ];
			}
		}
	}

	if ( $startpos > $prevcount ) {
		$startpos = $startpos - $prevcount;
	} else {
		$startpos = 0;
	}

	return $startpos;
}

/**
 * Extracts relevant part of the full text.
 *
 * Finds the part of full text with as many relevant words as possible. 1/6
 * ratio on prevcount tends to work pretty well and puts the terms in the middle
 * of the excerpt.
 *
 * Source: https://boyter.org/2013/04/building-a-search-result-extract-generator-in-php/
 *
 * @author Ben Boyter
 *
 * @param array  $words          An array of relevant words.
 * @param string $fulltext       The source text.
 * @param int    $excerpt_length The length of the excerpt, default 300
 * characters.
 * @param int    $prevcount      How much text include before the words, default
 * 50 characters.
 *
 * @return array The excerpt, number of words in the excerpt, true if it's the
 * start of the $fulltext.
 */
function relevanssi_extract_relevant( $words, $fulltext, $excerpt_length = 300, $prevcount = 50 ) {
	$text_length = relevanssi_strlen( $fulltext );

	if ( $text_length <= $excerpt_length ) {
		return array( $fulltext, 1, 0 );
	}

	$locations = relevanssi_extract_locations( $words, $fulltext );
	$startpos  = relevanssi_determine_snip_location( $locations, $prevcount );

	// If we are going to snip too much...
	if ( $text_length - $startpos < $excerpt_length ) {
		$startpos -= ( $text_length - $startpos ) / 2;
	}

	$substr = function_exists( 'mb_substr' ) ? 'mb_substr' : 'substr';

	$excerpt = call_user_func( $substr, $fulltext, $startpos, $excerpt_length );

	$start = false;
	if ( 0 === $startpos ) {
		$start = true;
	}

	$besthits = count( relevanssi_extract_locations( $words, $excerpt ) );

	return array( $excerpt, $besthits, $start );
}

/**
 * Extracts relevant words of the full text.
 *
 * Finds the part of full text with as many relevant words as possible. If the
 * excerpt length parameter is less than 1, the function will immediately
 * return an empty excerpt in order to avoid an endless loop.
 *
 * @param array  $terms          An array of relevant words.
 * @param string $content        The source text.
 * @param int    $excerpt_length The length of the excerpt, default 30 words.
 *
 * @return array The excerpt, number of words in the excerpt, true if it's the
 * start of the $fulltext.
 */
function relevanssi_extract_relevant_words( $terms, $content, $excerpt_length = 30 ) {
	if ( $excerpt_length < 1 ) {
		return array( '', 0, false );
	}

	$words       = array_filter( explode( ' ', $content ) );
	$offset      = 0;
	$tries       = 0;
	$excerpt     = '';
	$count_words = count( $words );
	$start       = false;
	$gap         = 0;

	$best_excerpt_term_hits = -1;

	$excerpt_candidates = $count_words / $excerpt_length;
	if ( $excerpt_candidates > 200 ) {
		/**
		 * Adjusts the gap between excerpt candidates.
		 *
		 * The default value for the gap is number of words / 200 minus the
		 * excerpt length, which means Relevanssi tries to create 200 excerpts.
		 *
		 * @param int The gap between excerpt candidates.
		 * @param int $count_words    The number of words in the content.
		 * @param int $excerpt_length The length of the excerpt.
		 */
		$gap = apply_filters(
			'relevanssi_excerpt_gap',
			floor( $count_words / 200 - $excerpt_length ),
			$count_words,
			$excerpt_length
		);
	}

	while ( $offset < $count_words ) {
		if ( $offset + $excerpt_length > $count_words ) {
			$offset = $count_words - $excerpt_length;
			if ( $offset < 0 ) {
				$offset = 0;
			}
		}
		$excerpt_slice = array_slice( $words, $offset, $excerpt_length );
		$excerpt_slice = ' ' . implode( ' ', $excerpt_slice );
		$count_matches = relevanssi_count_matches( $terms, $excerpt_slice );
		if ( $count_matches > 0 && $count_matches > $best_excerpt_term_hits ) {
			$best_excerpt_term_hits = $count_matches;
			$excerpt                = $excerpt_slice;
			if ( 0 === $offset ) {
				$start = true;
			} else {
				$start = false;
			}
		}
		++$tries;

		/**
		 * Enables the excerpt optimization.
		 *
		 * If your posts are very long, building excerpts can be really slow.
		 * To speed up the process, you can enable optimization, which means
		 * Relevanssi only creates 50 excerpt candidates.
		 *
		 * @param boolean Return true to enable optimization, default false.
		 */
		if ( apply_filters( 'relevanssi_optimize_excerpts', false ) ) {
			if ( $tries > 50 ) {
				// An optimization trick: try only 50 times.
				break;
			}
		}

		$offset += $excerpt_length + $gap;
	}

	if ( '' === $excerpt && $gap > 0 ) {
		$result = relevanssi_get_first_match( $words, $terms, $excerpt_length );

		$excerpt                = $result['excerpt'];
		$start                  = $result['start'];
		$best_excerpt_term_hits = $result['best_excerpt_term_hits'];
	}

	if ( '' === $excerpt ) {
		/**
		 * Nothing found, take the beginning of the post. +2, because the first
		 * index is an empty space and the last index is the rest of the post.
		 */
		$excerpt = explode( ' ', $content, $excerpt_length + 2 );
		array_pop( $excerpt );
		$excerpt = implode( ' ', $excerpt );
		$start   = true;
	}

	return array( trim( $excerpt ), $best_excerpt_term_hits, $start );
}

/**
 * Finds the first match in the content.
 *
 * Looks for search terms in the post content and stops immediately when the
 * first match is found. Then an excerpt is returned where the match is in the
 * middle of the excerpt.
 *
 * @param array $words          An array of words to look in.
 * @param array $terms          An array of search terms to look for.
 * @param int   $excerpt_length The length of the excerpt.
 *
 * @return array The found excerpt in 'excerpt', a boolean in 'start' that's
 * true if the excerpt was from the start of the content and the number of
 * matches found in the excerpt in 'best_excerpt_term_hits'.
 */
function relevanssi_get_first_match( array $words, array $terms, int $excerpt_length ) {
	$offset                 = 0;
	$excerpt                = '';
	$start                  = false;
	$best_excerpt_term_hits = 0;

	foreach ( $words as $word ) {
		if ( in_array( $word, $terms, true ) ) {
			$offset = floor( $offset - $excerpt_length / 2 );
			if ( $offset < 0 ) {
				$offset = 0;
			}
			$excerpt_slice = array_slice( $words, $offset, $excerpt_length );
			$excerpt       = ' ' . implode( ' ', $excerpt_slice );
			$start         = $offset ? false : true;
			$count_matches = relevanssi_count_matches( $terms, $excerpt );

			$best_excerpt_term_hits = $count_matches;
			break;
		}
		++$offset;
	}

	return array(
		'excerpt'                => $excerpt,
		'start'                  => $start,
		'best_excerpt_term_hits' => $best_excerpt_term_hits,
	);
}

/**
 * Adds accented variations to letters.
 *
 * In order to have non-accented letters in search terms match the accented terms in
 * full text, this function adds accent variations to the search terms.
 *
 * @param string $word The word to manipulate.
 *
 * @return string The word with accent variations.
 */
function relevanssi_add_accent_variations( $word ) {
	/**
	 * Filters the accent replacement array.
	 *
	 * @param array Array of replacements. 'from' has the source characters, 'to' the replacements.
	 */
	$replacement_arrays = apply_filters(
		'relevanssi_accents_replacement_arrays',
		array(
			'from'    => array( 'a', 'c', 'e', 'i', 'o', 'u', 'n' ),
			'to'      => array( '(?:a|á|à|â)', '(?:c|ç)', '(?:e|é|è|ê|ë)', '(?:i|í|ì|î|ï)', '(?:o|ó|ò|ô|õ)', '(?:u|ú|ù|ü|û)', '(?:n|ñ)' ),
			'from_re' => array( "/(s)('|’)?$/", "/[^\(\|:]('|’)/" ),
			'to_re'   => array( "(?:(?:'|’)?\\1|\\1(?:'|’)?)", "?('|’)?" ),
		)
	);

	if ( ! $replacement_arrays ) {
		return $word;
	}

	$len        = relevanssi_strlen( $word );
	$word_array = array();
	$escaped    = false;
	for ( $i = 0; $i < $len; $i++ ) {
		$char = relevanssi_substr( $word, $i, 1 );
		if ( '\\' === $char && ! $escaped ) {
			$escaped = true;
			continue;
		}
		if ( $escaped ) {
			$escaped = false;
			$char    = '\\' . $char;
		}
		$word_array[] = $char;
	}
	$word = implode( '-?', $word_array );
	$word = str_ireplace( $replacement_arrays['from'], $replacement_arrays['to'], $word );
	$word = preg_replace( $replacement_arrays['from_re'], $replacement_arrays['to_re'], $word );

	return $word;
}

/**
 * Fetches the custom field content for a post.
 *
 * @param int $post_id The post ID.
 *
 * @return array The custom field content in an array. The array either has the
 * the field names as keys (if relevanssi_excerpt_specific_fields is on) or has
 * everything in one string in index 0 (if relevanssi_excerpt_specific_fields is
 * off).
 */
function relevanssi_get_custom_field_content( $post_id ): array {
	$custom_field_content = array();
	$custom_field_string  = '';

	$custom_fields = relevanssi_generate_list_of_custom_fields( $post_id );

	$child_pdf_content = array();
	if ( function_exists( 'relevanssi_get_child_pdf_content' ) ) {
		$child_pdf_content = relevanssi_get_child_pdf_content( $post_id );
		$custom_fields[]   = '_relevanssi_child_pdf_content';
	}

	/**
	 * Filters the list of custom fields used for the excerpt.
	 *
	 * @param array $custom_fields The list of custom fields.
	 * @param int   $post_id       The post ID.
	 */
	$custom_fields = apply_filters( 'relevanssi_excerpt_custom_fields', $custom_fields, $post_id );

	foreach ( $custom_fields as $field ) {
		/* Documented in lib/indexing.php. */
		$values = apply_filters(
			'relevanssi_custom_field_value',
			get_post_meta(
				$post_id,
				$field,
				false
			),
			$field,
			$post_id
		);
		if ( '_relevanssi_child_pdf_content' === $field ) {
			$values = $child_pdf_content;
		}
		if ( empty( $values ) || ! is_array( $values ) ) {
			continue;
		}
		foreach ( $values as $value ) {
			// Quick hack : allow indexing of PODS relationship custom fields. @author TMV.
			if ( is_array( $value ) && isset( $value['post_title'] ) ) {
				$value = $value['post_title'];
			}

			// Flatten other array data.
			if ( is_array( $value ) ) {
				$value_as_string = '';
				array_walk_recursive(
					$value,
					function ( $val ) use ( &$value_as_string ) {
						if ( is_string( $val ) ) {
							// Sometimes this can be something weird.
							$value_as_string .= ' ' . $val;
						}
					}
				);
				$value = $value_as_string;
			}
			if ( ! isset( $custom_field_content[ $field ] ) ) {
				$custom_field_content[ $field ] = '';
			}
			$custom_field_content[ $field ] .= ' ' . $value;
			$custom_field_string            .= ' ' . $value;
		}
	}

	if ( 'off' === get_option( 'relevanssi_excerpt_specific_fields' ) ) {
		return array(
			/**
			 * Filters the custom field content for excerpt use.
			 *
			 * @param string $custom_field_content Custom field content for excerpts.
			 * @param int    $post_id              The post ID.
			 * @param array  $custom_fields        The list of custom field names.
			 */
			apply_filters(
				'relevanssi_excerpt_custom_field_content',
				$custom_field_string,
				$post_id,
				$custom_fields
			),
		);
	} else {
		/**
		 * Filters the custom field content for excerpt use.
		 *
		 * Here the custom field content is in an array, with the field names as
		 * keys.
		 *
		 * @param array $custom_field_content Custom field content for excerpts.
		 * @param int   $post_id              The post ID.
		 */
		return apply_filters(
			'relevanssi_excerpt_specific_custom_field_content',
			$custom_field_content,
			$post_id
		);
	}
}

/**
 * Kills the autoembed filter hook on 'the_content'.
 *
 * @global array $wp_filter The global filter array.
 *
 * It's an object hook, so this isn't as simple as doing remove_filter(). This
 * needs to be done, because autoembed discovery can take a very, very long
 * time.
 */
function relevanssi_kill_autoembed() {
	global $wp_filter;
	if ( isset( $wp_filter['the_content']->callbacks ) ) {
		foreach ( $wp_filter['the_content']->callbacks as $priority => $bucket ) {
			foreach ( array_keys( $bucket ) as $key ) {
				if ( 'autoembed' === substr( $key, -9 ) ) {
					unset( $wp_filter['the_content']->callbacks[ $priority ][ $key ] );
				}
			}
		}
	}
}

/**
 * Adjusts things before `the_content` is applied in excerpt-building.
 *
 * Removes the `prepend_attachment` filter hook and enables the `noindex`
 * shortcode.
 */
function relevanssi_excerpt_pre_the_content() {
	// This will print out the attachment file name in front of the excerpt, and we
	// don't want that.
	remove_filter( 'the_content', 'prepend_attachment' );

	remove_shortcode( 'noindex' );
	add_shortcode( 'noindex', 'relevanssi_noindex_shortcode_indexing' );
}

/**
 * Adjusts things after `the_content` is applied in excerpt-building.
 *
 * Reapplies the `prepend_attachment` filter hook and disables the `noindex`
 * shortcode.
 */
function relevanssi_excerpt_post_the_content() {
	add_filter( 'the_content', 'prepend_attachment' );

	remove_shortcode( 'noindex' );
	add_shortcode( 'noindex', 'relevanssi_noindex_shortcode' );
}

/**
 * Adds a highlighted title in the post object in $post->post_highlighted_title.
 *
 * @param WP_Post $post  The post object (passed as reference).
 * @param string  $query The search query.
 *
 * @uses relevanssi_highlight_terms
 */
function relevanssi_highlight_post_title( &$post, $query ) {
	$post->post_highlighted_title = wp_strip_all_tags( $post->post_title );
	$highlight                    = get_option( 'relevanssi_highlight' );
	if ( 'none' !== $highlight ) {
		if ( ! is_admin() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
			$q_for_highlight = 'on' === get_option( 'relevanssi_index_synonyms', 'off' )
			? relevanssi_add_synonyms( $query )
			: $query;

			$post->post_highlighted_title = relevanssi_highlight_terms(
				$post->post_highlighted_title,
				$q_for_highlight
			);
		}
	}
}

/**
 * Replaces $post->post_excerpt with the Relevanssi-generated excerpt and puts
 * the original excerpt in $post->original_excerpt.
 *
 * @param WP_Post $post           The post object (passed as reference).
 * @param string  $query          The search query.
 *
 * @uses relevanssi_do_excerpt
 */
function relevanssi_add_excerpt( &$post, $query ) {
	if ( isset( $post->blog_id ) && function_exists( 'switch_to_blog' ) ) {
		switch_to_blog( $post->blog_id );
	}
	$post->original_excerpt = $post->post_excerpt;
	/**
	 * Filters whether an excerpt should be added to a post or not.
	 *
	 * If this filter hook returns false, Relevanssi does not create an excerpt
	 * for the post. The original excerpt is still copied to
	 * $post->original_excerpt.
	 *
	 * @param boolean If true, create an excerpt. Default true.
	 * @param WP_Post $post  The post object.
	 * @param string  $query The search query.
	 */
	if ( apply_filters( 'relevanssi_excerpt_post', true, $post, $query ) ) {
		$excerpt_length     = get_option( 'relevanssi_excerpt_length' );
		$excerpt_type       = get_option( 'relevanssi_excerpt_type' );
		$post->post_excerpt = relevanssi_do_excerpt(
			$post,
			$query,
			$excerpt_length,
			$excerpt_type
		);
	}
	if ( isset( $post->blog_id ) && function_exists( 'restore_current_blog' ) ) {
		restore_current_blog();
	}
}

/**
 * Runs html_entity_decode(), then restores entities inside data attributes.
 *
 * First replace all &quot; entities inside data attributes with REL_QUOTE,
 * then decode, then replace REL_QUOTE with &quot; to restore the data
 * attributes.
 *
 * @uses html_entity_decode
 *
 * @param string $content The content to decode.
 * @param int    $flags   The flags for html_entity_decode, default ENT_QUOTES.
 * @param string $charset The charset for html_entity_decode, default 'UTF-8'.
 *
 * @return string The decoded content.
 */
function relevanssi_entity_decode( $content, $flags = ENT_QUOTES, $charset = 'UTF-8' ) {
	if ( preg_match_all( '/data-[\w-]+?="([^"]*?)"/sm', $content, $matches ) ) {
		$source  = array();
		$replace = array();
		foreach ( $matches[1] as $match ) {
			$source[]  = $match;
			$replace[] = str_replace( '&quot;', 'REL_QUOTE', $match );
		}
		$content = str_replace( $source, $replace, $content );
	}
	$content = html_entity_decode( $content, $flags, $charset );
	if ( preg_match_all( '/data-[\w-]+?="([^"]*?)"/sm', $content, $matches ) ) {
		$source  = array();
		$replace = array();
		foreach ( $matches[1] as $match ) {
			$source[]  = $match;
			$replace[] = htmlentities( $match );
		}
		$content = str_replace( $source, $replace, $content );
	}

	$content = str_replace( 'REL_QUOTE', '&quot;', $content );
	return $content;
}