/**
  * Enqueue our autosuggest script
  */
 public function enqueue_scripts()
 {
     $postfix = defined('SCRIPT_DEBUG') && true === SCRIPT_DEBUG ? '' : '.min';
     if (!is_admin()) {
         wp_enqueue_script('elasticpress-autosuggest', EPAS_URL . "assets/js/elasticpress_autosuggest{$postfix}.js", array('jquery'), EPAS_VERSION, true);
         wp_enqueue_style('elasticpress-autosuggest', EPAS_URL . "assets/css/elasticpress_autosuggest{$postfix}.css", array(), EPAS_VERSION);
         // Output some variables for our JS to use - namely the index name and the post type to use for suggestions
         wp_localize_script('elasticpress-autosuggest', 'ElasticPressAutoSuggest', array('index' => ep_get_index_name(get_current_blog_id()), 'postType' => apply_filters('epas_term_suggest_post_type', 'all')));
     }
 }
Ejemplo n.º 2
0
/**
 * Get all sites, count indexes
 *
 * @return array total index count with last blog id to manipulate blog with an index
 */
function ep_count_indexes()
{
    $sites = ep_get_sites();
    $count_indexes = 0;
    foreach ($sites as $site) {
        if ($index_name = ep_get_index_name($site['blog_id'])) {
            if (ep_index_exists($index_name)) {
                $count_indexes++;
                $last_blog_id_with_index = $site['blog_id'];
            }
        }
    }
    return array('total_indexes' => $count_indexes, 'last_blog_id_with_index' => $last_blog_id_with_index);
}
 /**
  * Setup each test.
  *
  * @since 0.1.0
  */
 public function setUp()
 {
     global $wpdb;
     parent::setUp();
     $wpdb->suppress_errors();
     $admin_id = $this->factory->user->create(array('role' => 'administrator'));
     $this->factory->blog->create_many(2, array('user_id' => $admin_id));
     $sites = ep_get_sites();
     $indexes = array();
     foreach ($sites as $site) {
         switch_to_blog($site['blog_id']);
         ep_delete_index();
         ep_put_mapping();
         $indexes[] = ep_get_index_name();
         restore_current_blog();
     }
     ep_activate();
     ep_delete_network_alias();
     ep_create_network_alias($indexes);
     wp_set_current_user($admin_id);
     EP_WP_Query_Integration::factory()->setup();
     $this->setup_test_post_type();
 }
 public function action_cache_query_results($posts, $search, $query)
 {
     $key = ep_get_index_name() . ' ' . var_export($query->query_vars, true);
     wp_cache_set($key, $posts, __NAMESPACE__);
 }
function get_elastic_crp_posts($args = array())
{
    global $post;
    // Are we matching only the title or the post content as well?
    $match_fields = array('post_title');
    $match_fields_content = array($post->post_title);
    if ($args['match_content']) {
        $match_fields[] = 'post_content';
        $match_fields_content[] = crp_excerpt($post->ID, $args['match_content_words'], false);
    }
    // Limit the related posts by time
    $current_time = current_time('timestamp', 0);
    $from_date = $current_time - $args['daily_range'] * DAY_IN_SECONDS;
    $from_date = gmdate('Y-m-d H:i:s', $from_date);
    $limit = $args['strict_limit'] ? $args['limit'] : $args['limit'] * 3;
    $client = \Grupoadslzone\Singletons\ElasticSearchClient::i();
    /*$clientBuilder = Elasticsearch\ClientBuilder::create();
      $clientBuilder->setHosts(array('http://127.0.0.1:9200'));
      $client = $clientBuilder->build();*/
    require_once plugin_dir_path(__FILE__) . 'includes/SearchQuery.php';
    $search_query = new SearchQuery();
    $search_query->setParamsByWPPost($post);
    $params = ['index' => ep_get_index_name(), 'type' => 'post', 'body' => ['_source' => 'post_id', 'query' => ['more_like_this' => ["fields" => $search_query->getFields(), "like_text" => $search_query->getSearchQuery(), "min_term_freq" => $search_query->getMinTermFreq(), "max_query_terms" => $search_query->getMaxQueryTerms(), "min_word_length" => 2, "minimum_should_match" => $search_query->getMinimumShouldMatch(), "boost" => 9, "boost_terms" => 4]], 'filter' => ["bool" => ["should" => ['range' => ['post_date' => ['from' => $from_date]]], 'must_not' => ['term' => ["post.post_id" => $post->ID]]]], 'from' => 0, 'size' => $limit]];
    //$ret = json_encode($params['body']);
    $response = $client->search($params);
    $results = $response['hits']['hits'];
    return $results;
}
Ejemplo n.º 6
0
 /**
  * Get stats on the current index.
  *
  * @since 0.9.2
  */
 public function stats()
 {
     $this->_connect_check();
     $request_args = array('headers' => ep_format_request_headers());
     $request = wp_remote_get(trailingslashit(ep_get_host(true)) . '_stats/', $request_args);
     if (is_wp_error($request)) {
         WP_CLI::error(implode("\n", $request->get_error_messages()));
     }
     $body = json_decode(wp_remote_retrieve_body($request), true);
     $sites = is_multisite() ? ep_get_sites() : array('blog_id' => get_current_blog_id());
     foreach ($sites as $site) {
         $current_index = ep_get_index_name($site['blog_id']);
         if (isset($body['indices'][$current_index])) {
             WP_CLI::log('====== Stats for: ' . $current_index . " ======");
             WP_CLI::log('Documents:  ' . $body['indices'][$current_index]['total']['docs']['count']);
             WP_CLI::log('Index Size: ' . size_format($body['indices'][$current_index]['total']['store']['size_in_bytes'], 2));
             WP_CLI::log('====== End Stats ======');
         } else {
             WP_CLI::warning($current_index . ' is not currently indexed.');
         }
     }
 }
 public function action_delete_blog_from_index($blog_id)
 {
     if (ep_index_exists(ep_get_index_name($blog_id)) && !apply_filters('ep_keep_index', false)) {
         ep_delete_index(ep_get_index_name($blog_id));
     }
 }
 /**
  * Decode the bulk index response
  *
  * @since 0.9.2
  * @param $body
  * @return array|object|WP_Error
  */
 public function bulk_index_posts($body)
 {
     // create the url with index name and type so that we don't have to repeat it over and over in the request (thereby reducing the request size)
     $url = trailingslashit(EP_HOST) . trailingslashit(ep_get_index_name()) . 'post/_bulk';
     $request_args = array('method' => 'POST', 'body' => $body, 'timeout' => 30, 'headers' => $this->format_request_headers());
     $request = wp_remote_request($url, apply_filters('ep_bulk_index_posts_request_args', $request_args, $body));
     if (is_wp_error($request)) {
         return $request;
     }
     $response = wp_remote_retrieve_response_code($request);
     if (200 !== $response) {
         return new WP_Error($response, wp_remote_retrieve_response_message($request), $request);
     }
     return json_decode(wp_remote_retrieve_body($request), true);
 }
Ejemplo n.º 9
0
 /**
  * Continue index
  *
  * @since  2.1
  */
 public function action_wp_ajax_ep_index()
 {
     if (!check_ajax_referer('ep_nonce', 'nonce', false)) {
         wp_send_json_error();
         exit;
     }
     if (defined('EP_IS_NETWORK') && EP_IS_NETWORK) {
         $index_meta = get_site_option('ep_index_meta', false);
     } else {
         $index_meta = get_option('ep_index_meta', false);
     }
     $status = false;
     // No current index going on. Let's start over
     if (false === $index_meta) {
         $status = 'start';
         $index_meta = array('offset' => 0, 'start' => true);
         if (defined('EP_IS_NETWORK') && EP_IS_NETWORK) {
             $sites = ep_get_sites();
             $index_meta['site_stack'] = array();
             foreach ($sites as $site) {
                 $index_meta['site_stack'][] = array('url' => untrailingslashit($site['domain'] . $site['path']), 'id' => (int) $site['blog_id']);
             }
             $index_meta['current_site'] = array_shift($index_meta['site_stack']);
         } else {
             if (!apply_filters('ep_skip_index_reset', false, $index_meta)) {
                 ep_delete_index();
                 ep_put_mapping();
             }
         }
         if (!empty($_POST['module_sync'])) {
             $index_meta['module_sync'] = esc_attr($_POST['module_sync']);
         }
     } else {
         if (!empty($index_meta['site_stack']) && $index_meta['offset'] >= $index_meta['found_posts']) {
             $status = 'start';
             $index_meta['start'] = true;
             $index_meta['offset'] = 0;
             $index_meta['current_site'] = array_shift($index_meta['site_stack']);
         } else {
             $index_meta['start'] = false;
         }
     }
     $index_meta = apply_filters('ep_index_meta', $index_meta);
     if (defined('EP_IS_NETWORK') && EP_IS_NETWORK) {
         switch_to_blog($index_meta['current_site']['id']);
         if (!empty($index_meta['start'])) {
             if (!apply_filters('ep_skip_index_reset', false, $index_meta)) {
                 ep_delete_index();
                 ep_put_mapping();
             }
         }
     }
     $posts_per_page = apply_filters('ep_index_posts_per_page', 350);
     do_action('ep_pre_dashboard_index', $index_meta, $status);
     $args = apply_filters('ep_index_posts_args', array('posts_per_page' => $posts_per_page, 'post_type' => ep_get_indexable_post_types(), 'post_status' => ep_get_indexable_post_status(), 'offset' => $index_meta['offset'], 'ignore_sticky_posts' => true, 'orderby' => 'ID', 'order' => 'DESC', 'fields' => 'all'));
     $query = new WP_Query($args);
     $index_meta['found_posts'] = $query->found_posts;
     if ($status !== 'start') {
         if ($query->have_posts()) {
             $queued_posts = array();
             while ($query->have_posts()) {
                 $query->the_post();
                 $killed_post_count = 0;
                 $post_args = ep_prepare_post(get_the_ID());
                 if (apply_filters('ep_post_sync_kill', false, $post_args, get_the_ID())) {
                     $killed_post_count++;
                 } else {
                     // Post wasn't killed so process it.
                     $queued_posts[get_the_ID()][] = '{ "index": { "_id": "' . absint(get_the_ID()) . '" } }';
                     if (function_exists('wp_json_encode')) {
                         $queued_posts[get_the_ID()][] = addcslashes(wp_json_encode($post_args), "\n");
                     } else {
                         $queued_posts[get_the_ID()][] = addcslashes(json_encode($post_args), "\n");
                     }
                 }
             }
             if (!empty($queued_posts)) {
                 $flatten = array();
                 foreach ($queued_posts as $post) {
                     $flatten[] = $post[0];
                     $flatten[] = $post[1];
                 }
                 // make sure to add a new line at the end or the request will fail
                 $body = rtrim(implode("\n", $flatten)) . "\n";
                 ep_bulk_index_posts($body);
             }
             $index_meta['offset'] = absint($index_meta['offset'] + $posts_per_page);
             if ($index_meta['offset'] >= $index_meta['found_posts']) {
                 $index_meta['offset'] = $index_meta['found_posts'];
             }
             if (defined('EP_IS_NETWORK') && EP_IS_NETWORK) {
                 update_site_option('ep_index_meta', $index_meta);
             } else {
                 update_option('ep_index_meta', $index_meta);
             }
         } else {
             // We are done (with this site)
             if (defined('EP_IS_NETWORK') && EP_IS_NETWORK) {
                 if (empty($index_meta['site_stack'])) {
                     delete_site_option('ep_index_meta');
                     $sites = ep_get_sites();
                     $indexes = array();
                     foreach ($sites as $site) {
                         switch_to_blog($site['blog_id']);
                         $indexes[] = ep_get_index_name();
                         restore_current_blog();
                     }
                     ep_create_network_alias($indexes);
                 } else {
                     $index_meta['offset'] = (int) $query->found_posts;
                 }
             } else {
                 $index_meta['offset'] = (int) $query->found_posts;
                 delete_option('ep_index_meta');
             }
         }
     } else {
         if (defined('EP_IS_NETWORK') && EP_IS_NETWORK) {
             update_site_option('ep_index_meta', $index_meta);
         } else {
             update_option('ep_index_meta', $index_meta);
         }
     }
     if (defined('EP_IS_NETWORK') && EP_IS_NETWORK) {
         restore_current_blog();
     }
     wp_send_json_success($index_meta);
 }
Ejemplo n.º 10
0
 /**
  * Test index_exists helper function
  */
 public function testIndexExists()
 {
     $sites = ep_get_sites();
     $first_site_index = ep_get_index_name($sites[0]['blog_id']);
     $index_should_exist = ep_index_exists($first_site_index);
     $index_should_not_exist = ep_index_exists($first_site_index . 2);
     $this->assertTrue($index_should_exist);
     $this->assertFalse($index_should_not_exist);
 }
Ejemplo n.º 11
0
 /**
  * Get stats on the current index.
  *
  * @since 0.9.2
  */
 public function stats()
 {
     $this->_connect_check();
     $sites = is_multisite() ? ep_get_sites() : array('blog_id' => get_current_blog_id());
     foreach ($sites as $site) {
         $stats_map = ep_stats($site['blog_id']);
         $current_index = ep_get_index_name($site['blog_id']);
         if (isset($stats_map)) {
             \WP_CLI::log('====== Stats for: ' . $current_index . " ======");
             \WP_CLI::log('Documents:  ' . $stats_map['total']['docs']['count']);
             \WP_CLI::log('Index Size: ' . size_format($stats_map['total']['store']['size_in_bytes'], 2));
             \WP_CLI::log('====== End Stats ======');
         } else {
             \WP_CLI::warning($current_index . ' is not currently indexed.');
         }
     }
 }
Ejemplo n.º 12
0
 /**
  * Retrieves search stats from Elasticsearch.
  *
  * Retrieves various search statistics from the ES server.
  *
  * @since 1.9
  *
  * @param int $blog_id Id of blog to get stats.
  *
  * @return array Contains the status message or the returned statistics.
  */
 public function get_search_status($blog_id = null)
 {
     if (is_wp_error(ep_get_host())) {
         return array('status' => false, 'msg' => esc_html__('Elasticsearch Host is not available.', 'elasticpress'));
     } else {
         if (is_multisite() && null === $blog_id) {
             $path = ep_get_network_alias() . '/_stats/search/';
         } else {
             $path = ep_get_index_name($blog_id) . '/_stats/search/';
         }
         $request = ep_remote_request($path, array('method' => 'GET'));
     }
     if (!is_wp_error($request)) {
         $stats = json_decode(wp_remote_retrieve_body($request));
         if (isset($stats->_all)) {
             return $stats->_all->primaries->search;
         }
         return false;
     }
     return array('status' => false, 'msg' => $request->get_error_message());
 }
Ejemplo n.º 13
0
 /**
  * Determine the index variable to be passed to ep_get_index_url.
  *
  * @param string $scope
  * @since 1.1.1
  * @return mixed
  */
 private function _get_index($scope = 'current')
 {
     $index = null;
     if ('all' === $scope) {
         $index = ep_get_network_alias();
     } elseif (is_int($scope)) {
         $index = ep_get_index_name($scope);
     } elseif (is_array($scope)) {
         $index = array();
         foreach ($scope as $site_id) {
             $index[] = ep_get_index_name($site_id);
         }
     }
     return $index;
 }