/**
  * Remove duplicate words from a string
  *
  * @param $content
  *
  * @return array|string
  */
 function remove_duplicate_words_from_string($content)
 {
     if (!class_exists('SearchWPIndexer')) {
         return $content;
     }
     $searchwp_indexer = new SearchWPIndexer();
     // standardize the content
     $content = $searchwp_indexer->clean_content($content);
     $content = explode(' ', $content);
     $content = array_map('trim', $content);
     // remove the dupes
     $content = array_unique($content);
     // put it back as a string
     $content = implode(' ', $content);
     return $content;
 }
    /**
     * Callback for plugin activation, outputs admin notice
     *
     * @since 1.0
     */
    function activation()
    {
        if (false == searchwp_get_setting('activated')) {
            searchwp_set_setting('activated', 1);
            // reset the counts
            if (class_exists('SearchWPIndexer')) {
                $indexer = new SearchWPIndexer();
                $indexer->update_running_counts();
            }
            ?>
			<div class="updated">
				<p><?php 
            echo sprintf(__('SearchWP has been activated and the index is now being built. <a href="%s">View progress and settings</a>', 'searchwp'), esc_url(admin_url('options-general.php?page=searchwp')));
            ?>
</p>
			</div>
			<?php 
            // trigger the initial indexing
            do_action('searchwp_log', 'Request index (activation)');
            $this->trigger_index();
        }
    }
 function searchwp_extract_pdf_metadata($post_id)
 {
     $indexer = new SearchWPIndexer();
     return $indexer->extract_pdf_metadata(absint($post_id));
 }
	/**
	 * Render view callback
	 */
	function render_view_advanced() {
		global $wpdb;
		?>
		<div class="searchwp-advanced-settings-wrapper swp-group">
			<div class="searchwp-advanced-settings-actions">
				<div class="searchwp-emergency-actions swp-group">
					<?php
					$valid_database_environment = SWP()->custom_db_tables_exist();
					if ( ! $valid_database_environment ) {
						$this->implement_action( array(
							'name'                  => 'recreate_db_tables',
							'label'                 => __( 'Recreate Database Tables', 'searchwp' ),
							'description'           => __( "SearchWP's database tables cannot be found. This may happen if a site migration was incomplete. Recreate the tables and initiate an index build.", 'searchwp' ),
							'results_message'       => sprintf( __( 'Database tables created! <a href="%s">Rebuild index &raquo;</a>', 'searchwp' ), admin_url( 'options-general.php?page=searchwp' ) ),
							'hide_after_trigger'    => true,
						), array( $this, 'recreate_db_tables' ) );
						?>
					<?php } ?>
				</div>
				<div class="searchwp-common-actions swp-group">
					<?php
					$this->implement_action( array(
						'name'              => 'index_reset',
						'label'             => __( 'Reset Index', 'searchwp' ),
						'description'       => __( '<strong>Completely</strong> empty the index. <em>Search statistics will be left as is.</em>', 'searchwp' ),
						'results_message'   => sprintf( __( 'The index <strong>has been reset</strong>. <a href="%s">Rebuild index &raquo;</a>', 'searchwp' ), admin_url( 'options-general.php?page=searchwp' ) ),
					), array( $this, 'reset_index' ) );

					$this->implement_action( array(
						'name'              => 'indexer_wake',
						'label'             => __( 'Wake Up Indexer', 'searchwp' ),
						'description'       => __( 'If the indexer appears to have stalled, try waking it up.', 'searchwp' ),
						'results_message'   => sprintf( __( 'Attempted to wake up the indexer. <a href="%s">View progress &raquo;</a>', 'searchwp' ), admin_url( 'options-general.php?page=searchwp' ) ),
					), array( $this, 'indexer_wake' ) );
					?>
				</div>
				<p class="searchwp-show-less-common-actions">
					<a class="button" href="#"><?php _e( 'Show More', 'searchwp' ); ?></a>
				</p>
				<div class="searchwp-less-common-actions swp-group">
				<?php
				$this->implement_action( array(
					'name'              => 'stats_reset',
					'label'             => __( 'Reset Statistics', 'searchwp' ),
					'description'       => __( '<strong>Completely</strong> reset your Search Statistics. <em>Existing index will be left as is.</em>', 'searchwp' ),
					'results_message'   => __( 'Search statistics reset', 'searchwp' ),
				), array( $this, 'reset_stats' ) );

				$this->implement_action( array(
					'name'              => 'indexer_toggle',
					'label'             => __( 'Toggle Indexer', 'searchwp' ),
					'description'       => __( 'Toggle the indexer status. It will pick up where it left off when re-enabled.', 'searchwp' ),
					'results_message'   => false,
				), array( $this, 'indexer_toggle' ) );

				$this->implement_action( array(
					'name'              => 'conflict_notices_reset',
					'label'             => __( 'Restore Conflict Notices', 'searchwp' ),
					'description'       => __( 'Restore all dismissed conflict notifications.', 'searchwp' ),
					'results_message'   => __( 'Conflict notices restored', 'searchwp' ),
				), array( $this, 'conflict_notices_reset' ) );

				$nuke_on_delete = searchwp_get_setting( 'nuke_on_delete' );
				$nuke_on_delete = empty( $nuke_on_delete ) ? false : true;
				$this->implement_action( array(
					'name'              => 'toggle_nuke_on_delete',
					'label'             => __( 'Toggle Nuke on Delete' ),
					'heading'           => $nuke_on_delete && ! isset( $_GET['action'] ) ? __( 'Nuke on Delete' ) . '<span class="description" style="display:inline-block;padding-left:0.5em;padding-right:1em;color:red;text-transform:uppercase;">' . __( 'Enabled' ) . '</span>' : __( 'Nuke on Delete' ),
					'description'       => __( 'Remove <strong>all traces</strong> of SearchWP upon plugin deletion (including index).', 'searchwp' ),
					'results_message'   => false,
				), array( $this, 'toggle_nuke_on_delete' ) );
				?>
				</div>
			</div>
			<div class="searchwp-advanced-settings-stats">
				<div class="postbox swp-meta-box metabox-holder searchwp-settings-stats">
					<h3 class="hndle">
						<span><?php _e( 'Index Statistics', 'searchwp' ); ?></span>
					</h3>
					<?php $stats = SWP()->settings['stats']; ?>
					<div class="inside">
						<p><?php echo sprintf( __( 'The indexer reacts to edits made and will apply updates accordingly. <a href="%s" target="_BLANK">More information &raquo;</a>', 'searchwp' ), 'https://searchwp.com/docs/kb/how-searchwp-works/' ); ?></p>
						<table class="searchwp-data-vis" cellpadding="0" cellspacing="0">
							<tbody>
								<?php if ( isset( $stats['last_activity'] ) ) : ?>
									<tr>
										<th><?php _e( 'Last Activity', 'searchwp' ); ?></th>
										<td>
											<?php echo esc_html( date_i18n( get_option( 'date_format' ), $stats['last_activity'] ) ); ?>
											<?php echo esc_html( date( 'H:i:s', $stats['last_activity'] ) ); ?>
										</td>
									</tr>
								<?php endif; ?>
								<?php if ( isset( $stats['done'] ) ) : ?>
									<tr>
										<th><?php _e( 'Indexed', 'searchwp' ); ?></th>
										<td><code><?php echo absint( $stats['done'] ); ?></code> <?php echo 1 == absint( $stats['done'] ) ? __( 'entry', 'searchwp' ) : __( 'entries', 'searchwp' ); ?></td>
									</tr>
								<?php endif; ?>
								<?php if ( isset( $stats['remaining'] ) ) : ?>
									<tr>
										<th><?php _e( 'Unindexed', 'searchwp' ); ?></th>
										<td><code><?php echo absint( $stats['remaining'] ); ?></code> <?php echo 1 == absint( $stats['remaining'] ) ? __( 'entry', 'searchwp' ) : __( 'entries', 'searchwp' ); ?></td>
									</tr>
								<?php endif; ?>
								<?php
									$indexer = new SearchWPIndexer();
									$row_count = $indexer->get_main_table_row_count();
								?>
								<tr>
									<th><?php _e( 'Main row count', 'searchwp' ); ?></th>
									<td><code><?php echo absint( $row_count ); ?></code> <?php echo 1 == absint( $row_count ) ? __( 'row', 'searchwp' ) : __( 'rows', 'searchwp' ); ?></td>
								</tr>
							</tbody>
						</table>
						<p class="description"><?php _e( 'Note: the index is always kept as small as posisble.', 'searchwp' ); ?></p>
					</div>
				</div>
			</div>
			<script type="text/javascript">
				jQuery(document).ready(function ($) {

//					var $stats_meta_box = $('.searchwp-settings-stats'),
//						$actions_meta_boxes = $('.searchwp-common-actions');
//
//					if($stats_meta_box.outerHeight()<$actions_meta_boxes.outerHeight()){
//						$stats_meta_box.height($actions_meta_boxes.outerHeight()-$stats_meta_box.css('marginTop').replace('px','')-$stats_meta_box.css('marginBottom').replace('px','')-2);
//					}

					$('#swp-indexer-index_reset').click(function () {
						if (confirm('<?php echo esc_js( __( 'Are you SURE you want to delete the entire SearchWP index?', 'searchwp' ) ); ?>')) {
							return confirm('<?php echo esc_js( __( 'Are you completely sure? THIS CAN NOT BE UNDONE!', 'searchwp' ) ); ?>');
						}
						return false;
					});
					$('#swp-indexer-stats_reset').click(function () {
						if (confirm('<?php echo esc_js( __( 'Are you SURE you want to completely reset your Search Stats?', 'searchwp' ) ); ?>')) {
							return confirm('<?php echo esc_js( __( 'Are you completely sure? THIS CAN NOT BE UNDONE!', 'searchwp' ) ); ?>');
						}
						return false;
					});
					$('.searchwp-show-less-common-actions a').click(function(e){
						e.preventDefault();
						$('.searchwp-show-less-common-actions').hide();
						$('.searchwp-less-common-actions').show();
					});
				});
			</script>
		</div>
		<?php
		include dirname( __FILE__ ) . '/export-import.php';
	}
 /**
  * Tap in to the SearchWP indexing process and check if a WP Document Revisions post is being indexed. If it is, we're
  * going to retrieve the most recent revision and extract the PDF content of that file. We'll store that data as a
  * pseudo Custom Field called wp_document_revision, allowing SearchWP to search for that content
  *
  * @param $post_metadata
  * @param $post_to_index
  *
  * @return bool
  */
 function index_wp_document_revisions($post_metadata, $post_to_index)
 {
     // make sure it's a WP Document Revisions Document
     if ('document' !== $post_to_index->post_type) {
         return $post_metadata;
     }
     if (!class_exists('SearchWPIndexer')) {
         return $post_metadata;
     }
     // get the latest Revision
     $rev_id = $this->mywpdr_get_latest_revision($post_to_index);
     $rev_post = get_post($rev_id);
     $revision = get_post($rev_post->post_content);
     // grab the PDF content from Xpdf
     $indexer = new SearchWPIndexer();
     $indexer->set_post($revision);
     $pdf_content = $indexer->extract_pdf_text(absint($revision->ID));
     // add it to the pseudo-metadata array
     $post_metadata['swp_wp_document_revision'] = $pdf_content;
     return $post_metadata;
 }
 function get_unindexed_posts()
 {
     if (!class_exists('SearchWPIndexer')) {
         return array();
     }
     add_filter('searchwp_index_chunk_size', array($this, 'posts_per_page'));
     $indexer = new SearchWPIndexer();
     $unindexed_posts = $indexer->find_unindexed_posts();
     remove_filter('searchwp_index_chunk_size', array($this, 'posts_per_page'));
     return $unindexed_posts;
 }
    function output()
    {
        global $wpdb;
        $theme_data = wp_get_theme();
        /** @noinspection PhpUndefinedFieldInspection */
        $theme = $theme_data->Name . ' ' . $theme_data->Version;
        // Try to identifty the hosting provider
        $host = false;
        if (defined('WPE_APIKEY')) {
            $host = 'WP Engine';
        } elseif (defined('PAGELYBIN')) {
            $host = 'Pagely';
        }
        $utf8mb4_failed_upgrade = false;
        if (searchwp_get_option('utf8mb4_upgrade_failed')) {
            $utf8mb4_failed_upgrade = true;
        }
        ?>
	<form action="" method="post" dir="ltr">
		<textarea readonly="readonly" onclick="this.focus();this.select()" class="searchwp-system-info-textarea" name="searchwp-sysinfo" title="<?php 
        _e('To copy the system info, click below then press CTRL + C (PC) or CMD + C (Mac).', 'searchwp');
        ?>
">
### Begin System Info ###

## Please include this information when posting support requests ##

<?php 
        if ($utf8mb4_failed_upgrade) {
            ?>
Failed utf8mb4 upgrade:   Yes
<?php 
        }
        ?>

Multisite:                <?php 
        echo is_multisite() ? 'Yes' . "\n" : 'No' . "\n";
        ?>

SITE_URL:                 <?php 
        echo esc_url(site_url()) . "\n";
        ?>
HOME_URL:                 <?php 
        echo esc_url(home_url()) . "\n";
        ?>

SearchWP Version:         <?php 
        echo esc_textarea($this->searchwp->version) . "\n";
        ?>
WordPress Version:        <?php 
        echo esc_textarea(get_bloginfo('version')) . "\n";
        ?>
Permalink Structure:      <?php 
        echo esc_textarea(get_option('permalink_structure')) . "\n";
        ?>
Active Theme:             <?php 
        echo esc_textarea($theme) . "\n";
        if ($host) {
            ?>
Host:                     <?php 
            echo esc_textarea($host) . "\n";
        }
        ?>

Registered Post Stati:    <?php 
        echo esc_textarea(implode(', ', get_post_stati())) . "\n\n";
        ?>

PHP Version:              <?php 
        echo esc_textarea(PHP_VERSION) . "\n";
        ?>
MySQL Version:            <?php 
        echo esc_textarea($wpdb->db_version()) . "\n";
        ?>
Web Server Info:          <?php 
        echo esc_textarea($_SERVER['SERVER_SOFTWARE']) . "\n";
        ?>

WordPress Memory Limit:   <?php 
        echo esc_textarea(WP_MEMORY_LIMIT);
        echo "\n";
        ?>
PHP Safe Mode:            <?php 
        echo ini_get('safe_mode') ? 'Yes' : 'No';
        echo "\n";
        ?>
PHP Memory Limit:         <?php 
        echo esc_textarea(ini_get('memory_limit')) . "\n";
        ?>
PHP Upload Max Size:      <?php 
        echo esc_textarea(ini_get('upload_max_filesize')) . "\n";
        ?>
PHP Post Max Size:        <?php 
        echo esc_textarea(ini_get('post_max_size')) . "\n";
        ?>
PHP Upload Max Filesize:  <?php 
        echo esc_textarea(ini_get('upload_max_filesize')) . "\n";
        ?>
PHP Time Limit:           <?php 
        echo esc_textarea(ini_get('max_execution_time')) . "\n";
        ?>
PHP Max Input Vars:       <?php 
        echo esc_textarea(ini_get('max_input_vars')) . "\n";
        ?>
PHP Arg Separator:        <?php 
        echo esc_textarea(ini_get('arg_separator.output')) . "\n";
        ?>
PHP Allow URL File Open:  <?php 
        echo ini_get('allow_url_fopen') ? 'Yes' : 'No';
        echo "\n";
        ?>

WP_DEBUG:                 <?php 
        echo defined('WP_DEBUG') ? WP_DEBUG ? 'Enabled' . "\n" : 'Disabled' . "\n" : 'Not set' . "\n";
        ?>

WP Table Prefix:          <?php 
        echo 'Length: ' . strlen($wpdb->prefix);
        echo ' Status:';
        if (strlen($wpdb->prefix) > 16) {
            echo ' ERROR: Too Long';
        } else {
            echo ' Acceptable';
        }
        echo "\n";
        ?>

Show On Front:            <?php 
        echo esc_textarea(get_option('show_on_front')) . "\n";
        ?>
Page On Front:            <?php 
        $id = get_option('page_on_front');
        echo esc_textarea(get_the_title($id) . ' (#' . $id . ')') . "\n";
        ?>
Page For Posts:           <?php 
        $id = get_option('page_for_posts');
        echo esc_textarea(get_the_title($id) . ' (#' . $id . ')') . "\n";
        ?>

<?php 
        $request['cmd'] = '_notify-validate';
        $params = array('sslverify' => false, 'timeout' => 60, 'user-agent' => 'SearchWP', 'body' => $request);
        $response = wp_remote_post('https://searchwp.com/', $params);
        if (!is_wp_error($response) && $response['response']['code'] >= 200 && $response['response']['code'] < 300) {
            $WP_REMOTE_POST = 'wp_remote_post() works' . "\n";
        } else {
            $WP_REMOTE_POST = 'wp_remote_post() does not work' . "\n";
        }
        ?>
WP Remote Post:           <?php 
        echo esc_textarea($WP_REMOTE_POST);
        ?>

Session:                  <?php 
        echo isset($_SESSION) ? 'Enabled' : 'Disabled';
        echo "\n";
        ?>
Session Name:             <?php 
        echo esc_html(ini_get('session.name'));
        echo "\n";
        ?>
Cookie Path:              <?php 
        echo esc_html(ini_get('session.cookie_path'));
        echo "\n";
        ?>
Save Path:                <?php 
        echo esc_html(ini_get('session.save_path'));
        echo "\n";
        ?>
Use Cookies:              <?php 
        echo ini_get('session.use_cookies') ? 'On' : 'Off';
        echo "\n";
        ?>
Use Only Cookies:         <?php 
        echo ini_get('session.use_only_cookies') ? 'On' : 'Off';
        echo "\n";
        ?>

DISPLAY ERRORS:           <?php 
        echo ini_get('display_errors') ? 'On (' . ini_get('display_errors') . ')' : 'N/A';
        echo "\n";
        ?>
FSOCKOPEN:                <?php 
        echo function_exists('fsockopen') ? 'Your server supports fsockopen.' : 'Your server does not support fsockopen.';
        echo "\n";
        ?>
cURL:                     <?php 
        echo function_exists('curl_init') ? 'Your server supports cURL.' : 'Your server does not support cURL.';
        echo "\n";
        ?>
SOAP Client:              <?php 
        echo class_exists('SoapClient') ? 'Your server has the SOAP Client enabled.' : 'Your server does not have the SOAP Client enabled.';
        echo "\n";
        ?>
SUHOSIN:                  <?php 
        echo extension_loaded('suhosin') ? 'Your server has SUHOSIN installed.' : 'Your server does not have SUHOSIN installed.';
        echo "\n";
        ?>

TEMPLATES:

search.php                <?php 
        echo file_exists(get_stylesheet_directory() . '/search.php') ? 'Yes' : 'No';
        ?>


POTENTIAL TEMPLATE CONFLICTS:

<?php 
        $conflicts = new SearchWP_Conflicts();
        if (!empty($conflicts->search_template_conflicts)) {
            foreach ($conflicts->search_template_conflicts as $line_number => $the_conflicts) {
                echo esc_textarea('Line ' . absint($line_number) . ': ' . implode(', ', $the_conflicts)) . "\n";
            }
        } else {
            echo "NONE\n";
        }
        ?>

POTENTIAL FILTER CONFLICTS

<?php 
        if (!empty($conflicts->filter_conflicts)) {
            foreach ($conflicts->filter_conflicts as $filter_name => $potential_conflict) {
                foreach ($potential_conflict as $conflict) {
                    echo esc_textarea($filter_name . ' => ' . $conflict) . "\n";
                }
            }
        } else {
            echo "NONE\n";
        }
        ?>

ACTIVE PLUGINS:

<?php 
        $plugins = get_plugins();
        $active_plugins = get_option('active_plugins', array());
        foreach ($plugins as $plugin_path => $plugin) {
            // if the plugin isn't active, don't show it.
            if (!in_array($plugin_path, $active_plugins)) {
                continue;
            }
            echo esc_textarea($plugin['Name'] . ': ' . $plugin['Version']) . "\n";
        }
        if (is_multisite()) {
            ?>

	NETWORK ACTIVE PLUGINS:

	<?php 
            $plugins = wp_get_active_network_plugins();
            $active_plugins = get_site_option('active_sitewide_plugins', array());
            foreach ($plugins as $plugin_path) {
                $plugin_base = plugin_basename($plugin_path);
                // If the plugin isn't active, don't show it.
                if (!array_key_exists($plugin_base, $active_plugins)) {
                    continue;
                }
                $plugin = get_plugin_data($plugin_path);
                echo esc_textarea($plugin['Name'] . ' :' . $plugin['Version']) . "\n";
            }
        }
        ?>

STATS:

<?php 
        if (isset($this->searchwp->settings['stats'])) {
            if (!empty($this->searchwp->settings['stats']['last_activity'])) {
                $this->searchwp->settings['stats']['last_activity'] = human_time_diff($this->searchwp->settings['stats']['last_activity'], current_time('timestamp')) . ' ago';
            }
            echo esc_textarea(print_r($this->searchwp->settings['stats'], true));
            echo "\n";
        } else {
            echo esc_textarea(print_r(get_option(SEARCHWP_PREFIX . 'settings'), true));
            echo "\n";
        }
        $indexer = new SearchWPIndexer();
        $row_count = $indexer->get_main_table_row_count();
        echo 'Main table row count: ';
        echo absint($row_count);
        echo "\n";
        if (isset($this->searchwp->settings['running'])) {
            echo 'Running: ';
            echo !empty($this->searchwp->settings['running']) ? 'Yes' : 'No';
            echo "\n";
        }
        if (isset($this->searchwp->settings['busy'])) {
            echo 'Busy: ';
            echo !empty($this->searchwp->settings['busy']) ? 'Yes' : 'No';
            echo "\n";
        }
        if (isset($this->searchwp->settings['doing_delta'])) {
            echo 'Doing Delta: ';
            echo !empty($this->searchwp->settings['running']) ? 'Yes' : 'No';
            echo "\n";
        }
        if (isset($this->searchwp->settings['processing_purge_queue'])) {
            echo 'Processing Purge Queue: ';
            echo !empty($this->searchwp->settings['processing_purge_queue']) ? 'Yes' : 'No';
            echo "\n";
        }
        if (isset($this->searchwp->settings['paused'])) {
            echo 'Paused: ';
            echo !empty($this->searchwp->settings['paused']) ? 'Yes' : 'No';
            echo "\n";
        }
        ?>

SETTINGS:

<?php 
        if (isset($this->searchwp->settings['engines'])) {
            echo esc_textarea(print_r($this->searchwp->settings['engines'], true));
        }
        ?>

PURGE QUEUE:

<?php 
        echo isset($this->searchwp->settings['purgeQueue']) ? esc_textarea(print_r($this->searchwp->settings['purgeQueue'], true)) : '[Empty]';
        ?>


### End System Info ###</textarea></form>
	<?php 
    }