searchwp-shortcodes.php 16.9 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
<?php
/*
Plugin Name: SearchWP Shortcodes
Plugin URI: https://searchwp.com/extensions/shortcodes/
Description: Provides Shortcodes that generate both search forms and results pages for SearchWP search engines
Version: 1.8.3
Author: SearchWP
Author URI: https://searchwp.com/

Copyright 2014-2022 SearchWP

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
*/

// exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! defined( 'SEARCHWP_SHORTCODES_VERSION' ) ) {
	define( 'SEARCHWP_SHORTCODES_VERSION', '1.8.3' );
}

/**
 * instantiate the updater
 */
if ( ! class_exists( 'SWP_Shortcodes_Updater' ) ) {
	// load our custom updater
	include_once( dirname( __FILE__ ) . '/vendor/updater.php' );
}

// set up the updater
function searchwp_shortcodes_update_check(){

	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
		return false;
	}

	// environment check
	if ( ! defined( 'SEARCHWP_PREFIX' ) ) {
		return false;
	}

	if ( ! defined( 'SEARCHWP_EDD_STORE_URL' ) ) {
		return false;
	}

	// SearchWP 4 compat.
	if ( class_exists( '\\SearchWP\\License' ) ) {
		$license_key = \SearchWP\License::get_key();
	} else {
		$license_key = trim( get_option( SEARCHWP_PREFIX . 'license_key' ) );
		$license_key = sanitize_text_field( $license_key );
	}

	// instantiate the updater to prep the environment
	$searchwp_shortcodes_updater = new SWP_Shortcodes_Updater( SEARCHWP_EDD_STORE_URL, __FILE__, array(
			'item_id' 	=> 33253,
			'version'   => SEARCHWP_SHORTCODES_VERSION,
			'license'   => $license_key,
			'item_name' => 'Shortcodes',
			'author'    => 'SearchWP',
			'url'       => site_url(),
		)
	);

	return $searchwp_shortcodes_updater;
}

add_action( 'admin_init', 'searchwp_shortcodes_update_check' );

class SearchWP_Shortcodes {

	public $query   = '';
	public $page    = 1;
	public $results = array();
	public $engine  = 'default';
	public $max_num_pages = 0;
	private $busy = false;

	public function __construct() {
		$this->page     = isset( $_REQUEST['swppg'] ) ? absint( $_REQUEST['swppg'] ) : 1;

		add_shortcode( 'searchwp_search_form', array( $this, 'search_form_output' ) );
		add_shortcode( 'searchwp_search_results_pagination', array( $this, 'search_results_pagination_output' ) );
		add_shortcode( 'searchwp_search_results_paginate_links', array( $this, 'search_results_paginate_links' ) );
		add_shortcode( 'searchwp_search_results_none', array( $this, 'search_results_none_output' ) );
		add_shortcode( 'searchwp_search_results', array( $this, 'search_results_output' ) );
		add_shortcode( 'searchwp_search_result_link', array( $this, 'search_result_link_output' ) );
		add_shortcode( 'searchwp_search_result_excerpt', array( $this, 'search_result_excerpt_output' ) );
		add_shortcode( 'searchwp_search_result_excerpt_global', array( $this, 'search_result_excerpt_global_output' ) );
		add_shortcode( 'searchwp_search_result_excerpt_document', array( $this, 'search_result_excerpt_document_output' ) );
		add_shortcode( 'searchwp_search_result_image', array( $this, 'search_result_image_output' ) );
		add_shortcode( 'searchwp_search_result_permalink', array( $this, 'search_result_permalink_output' ) );
		add_shortcode( 'searchwp_total_results', array( $this, 'total_results_output' ) );
	}

	public function prevent_logging() {
		return true;
	}

	public function search_result_permalink_output( $atts ) {
		global $post;

		$args = shortcode_atts( array(
			'direct' => 'true',
		), $atts );

		$args = apply_filters( 'searchwp_shortcodes_result_permalink_args', $args );

		$direct = 'true' !== strtolower( (string) $args['direct'] ) ? false : true;

		if ( $direct && isset( $post->post_type ) && 'attachment' === $post->post_type ) {
			$permalink = wp_get_attachment_url( $post->ID );
		} else {
			$permalink = get_permalink();
		}

		ob_start();
		echo apply_filters(
			'searchwp_shortcodes_result_permalink',
			'<a class="searchwp-shortcode-result-permalink" href="' . esc_url( $permalink ) . '">' . esc_url( $permalink ) . '</a>',
			array(
				'permalink' => $permalink,
				'post'      => $post,
			)
		);
		return ob_get_clean();
	}

	public function search_result_image_output( $attributes ) {
		global $post;

		$args = shortcode_atts( array(
			'size' => 'thumb',
		), $attributes );

		$args = apply_filters( 'searchwp_shortcodes_result_image_args', $args );

		ob_start();
		echo get_the_post_thumbnail( $post->ID, $args['size'] );
		return ob_get_clean();
	}

	public function total_results_output( $attributes ) {
		if ( $this->busy ) {
			return '';
		}

		$this->busy = true;

		$args = shortcode_atts( array(
			'engine' => 'default',
			'var'    => 'swpquery',
			'text'   => '',
		), $attributes );

		$this->maybe_set_search_query( $args['var'] );

		if ( ! class_exists( 'SearchWP' ) || empty( $this->query ) ) {
			return '';
		}

		add_filter( 'searchwp_log_search', array( $this, 'prevent_logging' ), 31 );
		add_filter( 'searchwp\statistics\log', array( $this, 'prevent_logging' ), 31 );

		// Allow developers to filter the engine at runtime.
		$engine = (string) apply_filters( 'searchwp_shortcodes_engine', (string) $args['engine'] );

		// Perform the search.
		if ( function_exists( 'SWP' ) ) {
			$this->results = SWP()->search( sanitize_text_field( $engine ), $this->query, $this->page );
			remove_filter( 'searchwp_log_search', array( $this, 'prevent_logging' ), 31 );

			$this->busy = false;

			$found_posts = SWP()->foundPosts;
		} else {
			$results = new \SWP_Query( [
				's'      => $this->query,
				'engine' => sanitize_text_field( $engine ),
				'page'   => $this->page,
			] );

			remove_filter( 'searchwp\statistics\log', array( $this, 'prevent_logging' ), 31 );

			$this->busy = false;

			$found_posts = $results->found_posts;
		}

		if ( ! empty( $args['text'] ) ) {
			return $this->total_results_output_text( $found_posts, $args['text'] );
		}

        return absint( $found_posts );
	}

    private function total_results_output_text( $found_posts, $text ) {

	    if ( strpos( $text, '%total%' ) === false && strpos( $text, '%query%' ) === false ) {
		    return wp_kses_post( $text ) . ' ' . $found_posts;
        }

        $query  = wp_strip_all_tags( $this->query );
        $output = str_replace( [ '%total%', '%query%' ], [ $found_posts, $query ], $text );

        return wp_kses_post( $output );
    }

	public function maybe_set_search_query( $var = 'swpquery' ) {
		if ( empty( $this->query ) ) {
			$var         = sanitize_text_field( $var );
			$this->query = isset( $_REQUEST[ $var ] ) ? sanitize_text_field( html_entity_decode ( stripslashes( $_REQUEST[ $var ] ) ) ) : '';
		}
	}

	public function search_form_output( $attributes ) {
		$args = shortcode_atts( array(
			'target'      => '',
			'engine'      => 'default',
			'var'         => 'swpquery',
			'button_text' => __( 'Search', 'searchwp-shortcodes' ),
			'placeholder' => __( 'Search', 'searchwp-shortcodes' ),
		), $attributes );

        if ( isset( $attributes['live_search'] ) ) {
	        $args['live_search'] = filter_var( $attributes['live_search'], FILTER_VALIDATE_BOOLEAN );
        } else {
	        $args['live_search'] = function_exists( 'searchwp_live_search' ) && searchwp_live_search()->get( 'Settings_Api' )->get( 'enable-live-search' );
        }

		$this->maybe_set_search_query( $args['var'] );

		// Allow developers to filter the engine at runtime.
		$engine         = (string) apply_filters( 'searchwp_shortcodes_engine', (string) $args['engine'] );
		$live_ajax_html = $args['live_search'] ? 'data-swplive="true" data-swpengine="' . esc_attr( $engine ) . '"' : '';

		ob_start(); ?>
		<?php do_action( 'searchwp_shortcodes_before_wrapper' ); ?>
		<div class="searchwp-search-form searchwp-supplemental-search-form">
			<?php do_action( 'searchwp_shortcodes_before_form' ); ?>
			<form role="search" method="get" id="searchform" class="searchform" action="<?php echo esc_url( $args['target'] ); ?>">
				<div>
					<?php do_action( 'searchwp_shortcodes_before_label' ); ?>
					<label class="screen-reader-text" for="swpquery"><?php esc_html_e( 'Search for:', 'searchwp-shortcodes' ); ?></label>
					<?php do_action( 'searchwp_shortcodes_after_label' ); ?>
					<?php do_action( 'searchwp_shortcodes_before_input' ); ?>
					<input
						type="text"
						placeholder="<?php echo esc_attr( $args['placeholder'] ); ?>"
						value="<?php echo esc_attr( $this->query ); ?>"
						name="<?php echo esc_attr( $args['var'] ); ?>"
						id="<?php echo esc_attr( $args['var'] ); ?>"
                        <?php echo $live_ajax_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
					<?php do_action( 'searchwp_shortcodes_after_input' ); ?>
					<input type="hidden" name="engine" value="<?php echo esc_attr( $engine ); ?>" />
					<?php do_action( 'searchwp_shortcodes_before_button' ); ?>
					<input type="submit" id="searchsubmit" value="<?php echo esc_attr( $args['button_text'] ); ?>">
					<?php do_action( 'searchwp_shortcodes_after_button' ); ?>
				</div>
			</form>
			<?php do_action( 'searchwp_shortcodes_after_form' ); ?>
		</div>
		<?php
		do_action( 'searchwp_shortcodes_after_wrapper' );

		return ob_get_clean();
	}

	public function search_results_output( $attributes, $content = null ) {
		global $post, $searchwp_shortcodes_posts_per_page;

		if ( $this->busy ) {
			return;
		}

		$this->busy = true;

		$args = shortcode_atts( array(
			'engine'         => 'default',
			'posts_per_page' => 10,
			'var'            => 'swpquery',
		), $attributes );

		$searchwp_shortcodes_posts_per_page = absint( $args['posts_per_page'] );

		$this->maybe_set_search_query( $args['var'] );

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

		// Allow developers to filter the engine at runtime.
		$engine = (string) apply_filters( 'searchwp_shortcodes_engine', (string) $args['engine'] );

		if ( class_exists( 'SearchWP' ) ) {
			$engine = sanitize_text_field( $engine );

			// Set up custom posts per page.
			if ( ! function_exists( 'searchwp_shortcodes_posts_per_page' ) ) {
				function searchwp_shortcodes_posts_per_page() {
					global $searchwp_shortcodes_posts_per_page;

					return absint( $searchwp_shortcodes_posts_per_page );
				}
			}
			add_filter( 'searchwp_posts_per_page', 'searchwp_shortcodes_posts_per_page', 99 );

			// Perform the search.
			if ( function_exists( 'SWP' ) ) {
				$this->results = SWP()->search( $engine, $this->query, $this->page );
			} else {
				$results = new \SWP_Query( [
					's'              => $this->query,
					'engine'         => $engine,
					'page'           => $this->page,
					'posts_per_page' => $searchwp_shortcodes_posts_per_page,
				] );

				$this->results = $results->posts;
				$this->max_num_pages = $results->max_num_pages;
			}
		}

		ob_start();
		if ( ! empty( $this->query ) && ! empty( $this->results ) ) {
			foreach ( $this->results as $post ) {
				setup_postdata( $post );
				echo do_shortcode( $content );
			}
			wp_reset_postdata();
		}

		$this->busy = false;

		return ob_get_clean();
	}

	public function search_result_link_output( $atts ) {
		global $post;

		$args = shortcode_atts( array(
			'direct' => 'true',
		), $atts );

		$direct = 'true' !== strtolower( (string) $args['direct'] ) ? false : true;

		if ( $direct && isset( $post->post_type ) && 'attachment' === $post->post_type ) {
			$permalink = wp_get_attachment_url( $post->ID );
		} else {
			$permalink = get_permalink();
		}

		ob_start();
		echo '<a href="' . esc_url( $permalink ) . '">' . wp_kses_post( get_the_title() ) . '</a>';

		return ob_get_clean();
	}

	public function search_result_excerpt_output() {
		ob_start();
		the_excerpt();
		return ob_get_clean();
	}

	public function search_result_excerpt_global_output() {
		global $post;

		ob_start();
		if ( function_exists( 'searchwp_term_highlight_the_excerpt_global' ) ) {
			searchwp_term_highlight_the_excerpt_global( $post->ID, null, $this->query );
		} else if ( class_exists( 'SearchWP\Entry' ) ) {
			$entry  = new \SearchWP\Entry( 'post' . SEARCHWP_SEPARATOR . $post->post_type, $post->ID );
			$source = $entry->get_source();

			if ( method_exists( $source, 'get_global_excerpt' ) ) {
				return $source->get_global_excerpt( $entry, $this->query );
			} else {
				the_excerpt();
			}
		} else {
			the_excerpt();
		}
		return ob_get_clean();
	}

	public function search_result_excerpt_document_output() {
		global $post;

		ob_start();
		if ( function_exists( 'searchwp_term_highlight_the_excerpt_global' ) ) {
			searchwp_term_highlight_the_excerpt_global( $post->ID, 'searchwp_content', $this->query );
		} else if ( class_exists( 'SearchWP\Utils' ) ) {
			$meta_value = get_post_meta( $post->ID, 'searchwp_content', true );
			if ( ! empty( $meta_value ) && SearchWP\Utils::string_has_substring_from_string( $meta_value, $this->query ) ) {
				return SearchWP\Utils::trim_string_around_substring( $meta_value, $this->query );
			} else {
				the_excerpt();
			}
		} else {
			the_excerpt();
		}
		return ob_get_clean();
	}

	public function search_results_none_output( $atts, $content = null ) {

		if ( isset( $atts ) ) {
			$atts = null;
		}

		ob_start();
		if ( ! empty( $this->query ) && empty( $this->results ) && ! empty( $content ) ) {
			echo wp_kses_post( $content );
		}
		return ob_get_clean();
	}

	public function search_results_paginate_links( $atts ) {
		global $searchwp;

		$max_num_pages = isset( $searchwp->maxNumPages ) ? $searchwp->maxNumPages : $this->max_num_pages;

		// defaults based on https://codex.wordpress.org/Function_Reference/paginate_links
		$atts = shortcode_atts( array(
			'base'               => '%_%',
			'format'             => '?swppg=%#%',
			'total'              => $max_num_pages,
			'current'            => $this->page,
			'show_all'           => false,
			'end_size'           => 1,
			'mid_size'           => 2,
			'prev_next'          => true,
			'prev_text'          => __( '« Previous' ),
			'next_text'          => __( 'Next »' ),
			'type'               => 'plain',
			'add_args'           => false,
			'add_fragment'       => '',
			'before_page_number' => '',
			'after_page_number'  => '',
			'engine'             => 'default',
			'var'                => 'swpquery',
			'big'                => 999999999,
		), $atts );

		$atts['engine'] = (string) apply_filters( 'searchwp_shortcodes_engine', (string) $atts['engine'] );
		$atts['var']    = esc_attr( $atts['var'] );

		$atts = apply_filters( 'searchwp_shortcodes_paginate_links', $atts );

		ob_start();

		if ( $max_num_pages > 1 ) :
			?>
			<div class="searchwp-paginate-links">
				<?php echo wp_kses_post( paginate_links( $atts ) ); ?>
			</div>
			<?php

		endif;

		return ob_get_clean();
	}

	public function search_results_pagination_output( $atts, $content ) {
		global $searchwp;

		if ( isset( $content ) ) {
			$content = '';
		}

		$args = shortcode_atts( array(
			'engine'    => 'default',
			'direction' => 'prev',
			'link_text' => __( 'More' ),
			'var'       => 'swpquery',
		), $atts );

		// Allow developers to filter the engine at runtime.
		$engine = (string) apply_filters( 'searchwp_shortcodes_engine', (string) $args['engine'] );

		$this->maybe_set_search_query( $args['var'] );

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

		if ( 'next' !== strtolower( $args['direction'] ) ) {
			$args['direction'] = 'prev';
		}

		$max_num_pages = isset( $searchwp->maxNumPages ) ? $searchwp->maxNumPages : $this->max_num_pages;

		$prev_page = $this->page > 1 ? $this->page - 1 : false;
		$next_page = $this->page < $max_num_pages ? $this->page + 1 : false;

		ob_start();
		?>
		<?php if ( $max_num_pages > 1 ) : ?>
			<?php if ( 'prev' === strtolower( $args['direction'] ) ) : ?>
				<?php if ( $prev_page ) : ?>
					<div class="nav-previous">
						<?php
						$link = get_permalink() . '?' . esc_attr( $args['var'] ) . '=' . rawurlencode( $this->query ) . '&swppg=' . absint( $prev_page ) . '&engine=' . esc_attr( $engine );
						$link = apply_filters( 'searchwp_shortcodes_pagination_prev', $link );
						?>
						<a href="<?php echo esc_url( $link ); ?>"><?php echo wp_kses_post( $args['link_text'] ); ?></a>
					</div>
				<?php endif; ?>
			<?php else : ?>
				<?php if ( $next_page ) : ?>
					<div class="nav-next">
						<?php
						$link = get_permalink() . '?' . esc_attr( $args['var'] ) . '=' . rawurlencode( $this->query ) . '&swppg=' . absint( $next_page ) . '&engine=' . esc_attr( $engine );
						$link = apply_filters( 'searchwp_shortcodes_pagination_next', $link );
						?>
						<a href="<?php echo esc_url( $link ); ?>"><?php echo wp_kses_post( $args['link_text'] ); ?></a>
					</div>
				<?php endif; ?>
			<?php endif; ?>
		<?php endif; ?>
		<?php
		return ob_get_clean();
	}

}

new SearchWP_Shortcodes();