/**
  * Get related posts by post id and post type
  *
  * @param $post_id
  *
  * @return array
  */
 public function get_related_posts($post_id, $limit = -1)
 {
     global $wpdb;
     // Build SQl
     $sql = "\n\t\tSELECT O.`word`, P.`ID`, P.`post_title`, SUM( R.`weight` ) AS `related_weight`\n\t\tFROM `" . RP4WP_Related_Word_Manager::get_database_table() . "` O\n\t\tINNER JOIN `" . RP4WP_Related_Word_Manager::get_database_table() . "` R ON R.`word` = O.`word`\n\t\tINNER JOIN `" . $wpdb->posts . "` P ON P.`ID` = R.`post_id`\n\t\tWHERE 1=1\n\t\tAND O.`post_id` = %d\n\t\tAND R.`post_type` = 'post'\n\t\tAND R.`post_id` != %d\n\t\tAND P.`post_status` = 'publish'\n\t\tGROUP BY P.`id`\n\t\tORDER BY `related_weight` DESC\n\t\t";
     // Check & Add Limit
     if (-1 != $limit) {
         $sql .= "\n\t\t\tLIMIT 0,%d";
     }
     // Prepare SQL
     $sql = $wpdb->prepare($sql, $post_id, $post_id, $limit);
     // Get post from related cache
     return $wpdb->get_results($sql);
 }
    /**
     * The screen content
     *
     * @since  1.0.0
     * @access public
     */
    public function content()
    {
        // Do we have a reinstall?
        if (isset($_GET['reinstall'])) {
            // Check nonce
            if (!wp_verify_nonce(isset($_GET['rp4wp_nonce']) ? $_GET['rp4wp_nonce'] : '', RP4WP_Constants::NONCE_REINSTALL)) {
                wp_die('Woah! It looks like something else tried to run the Related Posts for WordPress installation wizard! We were able to stop them, nothing was lost. Please report this incident at <a href="http://wordpress.org/support/plugin/related-posts-for-wp" target="_blank">our forums.</a>');
            }
            global $wpdb;
            // Get ID's of related post link posts
            $link_ids = get_posts(array('post_type' => RP4WP_Constants::LINK_PT, 'fields' => 'ids', 'posts_per_page' => -1));
            // Only run queries if we have ID's
            if (count($link_ids) > 0) {
                // Delete all link posts
                $wpdb->query("DELETE FROM {$wpdb->posts} WHERE `ID` IN (" . implode(",", $link_ids) . ");");
                // Delete all link post meta
                $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE `post_id` IN (" . implode(",", $link_ids) . ");");
            }
            // Remove the post meta we attached to posts
            $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE `meta_key` = 'rp4wp_auto_linked' OR `meta_key` = 'rp4wp_cached' ");
            // Empty word cache
            $wpdb->query("DELETE FROM " . RP4WP_Related_Word_Manager::get_database_table() . " WHERE 1=1");
        }
        // The steps
        $steps = array(1 => __('Caching Posts', 'related-posts-for-wp'), 2 => __('Linking Posts', 'related-posts-for-wp'), 3 => __('Finished', 'related-posts-for-wp'));
        // What's the current step?
        $cur_step = isset($_GET['step']) ? $_GET['step'] : 1;
        // Check installer resume options
        if (1 == $cur_step) {
            // Add is installing site option
            add_site_option(RP4WP_Constants::OPTION_IS_INSTALLING, true);
        } elseif (3 == $cur_step) {
            // Installer is done, remove the option
            delete_site_option(RP4WP_Constants::OPTION_IS_INSTALLING);
        }
        ?>
		<div class="wrap">
			<h2>Related Posts for WordPress <?php 
        _e('Installation', 'related-posts-for-wp');
        ?>
</h2>

			<ul class="install-steps">
				<?php 
        foreach ($steps as $step => $label) {
            echo "<li id='step-bar-" . $step . "'" . ($cur_step == $step ? " class='step-bar-active'" : "") . "><span>" . $step . '. ' . $label . "</span></li>" . PHP_EOL;
        }
        ?>
			</ul>
			<br class="clear" />

			<h3><?php 
        echo $steps[$cur_step];
        ?>
</h3>

			<?php 
        $cur_step = isset($_GET['step']) ? $_GET['step'] : 1;
        echo "<div class='rp4wp-step rp4wp-step-" . $cur_step . "' rel='" . $cur_step . "'>";
        echo "<input type='hidden' id='rp4wp_total_posts' value='" . wp_count_posts('post')->publish . "' />" . PHP_EOL;
        echo "<input type='hidden' id='rp4wp_admin_url' value='" . admin_url() . "' />" . PHP_EOL;
        if (1 == $cur_step) {
            // Echo current uncached posts
            $related_word_manager = new RP4WP_Related_Word_Manager();
            echo "<input type='hidden' id='rp4wp_uncached_posts' value='" . $related_word_manager->get_uncached_post_count() . "' />" . PHP_EOL;
            ?>
				<p><?php 
            _e('Thank you for choosing Related Posts for WordPress!', 'related-posts-for-wp');
            ?>
</p>
				<p><?php 
            _e('Before you can start using Related Posts for WordPress we need to cache your current posts.', 'related-posts-for-wp');
            ?>
</p>
				<p><?php 
            _e("This is a one time process which might take some time now, depending on the amount of posts you have, but will ensure your website's performance when using the plugin.", 'related-posts-for-wp');
            ?>
</p>

				<p style="font-weight: bold;"><?php 
            _e('Do NOT close this window, wait for this process to finish and this wizard to take you to the next step.', 'related-posts-for-wp');
            ?>
</p>

				<div id="progressbar"></div>
			<?php 
        } elseif (2 == $cur_step) {
            // Echo current uncached posts
            $related_post_manager = new RP4WP_Related_Post_Manager();
            echo "<input type='hidden' id='rp4wp_uncached_posts' value='" . $related_post_manager->get_uncached_post_count() . "' />" . PHP_EOL;
            ?>
				<p style="font-weight: bold;"><?php 
            _e('Great! All your posts were successfully cached!', 'related-posts-for-wp');
            ?>
</p>
				<p><?php 
            _e("You can let me link your posts, based on what I think is related, to each other. And don't worry, if I made a mistake at one of your posts you can easily correct this by editing it manually!", 'related-posts-for-wp');
            ?>
</p>
				<p><?php 
            _e('Want me to start linking posts to each other? Fill in the amount of related posts each post should have and click on the "Link now" button. Rather link your posts manually? Click "Skip linking".', 'related-posts-for-wp');
            ?>
</p>
				<p style="font-weight: bold;"><?php 
            _e('Do NOT close this window if you click the "Link now" button, wait for this process to finish and this wizard to take you to the next step.', 'related-posts-for-wp');
            ?>
</p>
				<br class="clear" />
				<p class="rp4wp-install-link-box">
					<label for="rp4wp_related_posts_amount"><?php 
            _e('Amount of related posts per post:', 'related-posts-for-wp');
            ?>
</label><input class="form-input-tip" type="text" id="rp4wp_related_posts_amount" value="<?php 
            echo RP4WP()->settings->get_option('automatic_linking_post_amount');
            ?>
" />
					<a href="javascript:;" class="button button-primary button-large rp4wp-link-now-btn" id="rp4wp-link-now"><?php 
            _e('Link now', 'related-posts-for-wp');
            ?>
</a>
					<a href="<?php 
            echo admin_url();
            ?>
?page=rp4wp_install&step=3" class="button"><?php 
            _e('Skip linking', 'related-posts-for-wp');
            ?>
</a>
				</p>
				<br class="clear" />
				<div id="progressbar"></div>
			<?php 
        } elseif (3 == $cur_step) {
            ?>
				<p><?php 
            _e("That's it, you're good to go!", 'related-posts-for-wp');
            ?>
</p>
				<p><?php 
            printf(__('Thanks again for using Related Posts for WordPress and if you have any questions be sure to ask them at the %sWordPress.org forums.%s', 'related-posts-for-wp'), '<a href="http://wordpress.org/support/plugin/related-posts-for-wp" target="_blank">', '</a>');
            ?>
</p>
			<?php 
        }
        ?>
		</div>

		</div>

	<?php 
    }
 /**
  * Get related posts by post id and post type
  *
  * @param int $post_id
  * @param String $post_type
  * @param int $limit
  *
  * @return array
  */
 public function get_related_posts($post_id, $post_type, $limit = -1)
 {
     global $wpdb;
     // Post Type Manager
     $ptm = new RP4WP_Post_Type_Manager();
     // Int y'all
     $post_id = intval($post_id);
     // Related post types
     $related_post_types = $ptm->get_installed_post_type($post_type);
     // Only continue of we've got > 1 related post type
     if (0 === count($related_post_types)) {
         return array();
     }
     // Format the related post types
     $formatted_post_types = "( '" . implode("','", esc_sql($related_post_types)) . "' )";
     // Get max post age
     $max_post_age = 0;
     if (isset(RP4WP::get()->settings['general_' . $post_type])) {
         // set the correct options from step 3
         $max_post_age = intval(RP4WP::get()->settings['general_' . $post_type]->get_option('max_post_age'));
     }
     // Build SQl
     $sql = "\n\t\tSELECT R.`post_id` AS `ID`\n\t\tFROM `" . RP4WP_Related_Word_Manager::get_database_table() . "` O\n\t\tINNER JOIN `" . RP4WP_Related_Word_Manager::get_database_table() . "` R ON R.`word` = O.`word` ";
     // only join post table when max post age is set
     if ($max_post_age > 0) {
         $sql .= "INNER JOIN `" . $wpdb->posts . "` P ON P.`ID` = R.`post_id`";
     }
     // add WHERE statements
     $sql .= "\n\t\tWHERE 1=1\n\t\tAND O.`post_id` = %d\n\t\tAND R.`post_type` IN " . $formatted_post_types . "\n\t\tAND R.`post_id` != %d\n\t\t";
     // get excluded ids
     $excluded_ids = get_option(RP4WP_Constants::OPTION_EXCLUDED, '');
     // check if there are excluded ids
     if (false !== $excluded_ids && !empty($excluded_ids)) {
         // add excluded where statement to query
         $sql .= "AND R.`post_id` NOT IN (" . $excluded_ids . ")\n\t\t\t";
     }
     // check if we got a maximum post age for this post type
     // check is max post age is > 0
     if ($max_post_age > 0) {
         // calculate date in past
         $date_time_oldest = new DateTime();
         $date_time_oldest = $date_time_oldest->modify('-' . $max_post_age . 'days');
         // make the post age key filterable
         $post_age_column = apply_filters('rp4wp_post_age_column', 'post_date');
         // add to SQL
         $sql .= "AND P.`" . $post_age_column . "` >= '" . $date_time_oldest->format('Y-m-d') . "'\n\t\t\t\t";
     }
     // add group by and order by to SQL
     $sql .= "GROUP BY R.`post_id`\n\t\tORDER BY SUM( R.`weight` ) DESC\n\t\t";
     // Check & Add Limit
     if (-1 != $limit) {
         $sql .= "\n\t\t\tLIMIT 0,%d";
         // Prepare SQL
         $sql = $wpdb->prepare($sql, $post_id, $post_id, $limit);
     } else {
         // Prepare SQL
         $sql = $wpdb->prepare($sql, $post_id, $post_id);
     }
     // Allow filtering of SQL to find related posts
     $sql = apply_filters('rp4wp_get_related_posts_sql', $sql, $post_id, $post_type, $limit);
     // Get post from related cache
     return $wpdb->get_results($sql);
 }