Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Post Previews
- *
- * Allows previewing unpublished posts while logged out using a token
- */
- class Jetpack_Post_Previews {
- /**
- * Temporary holder of post object if it can be previewed.
- */
- public $shared_post;
- /**
- * Name for the preview URL paramenter.
- */
- const QUERY_VAR_NAME = 'jppreview';
- /**
- * If the post is already published and we need to preview the latest autosave.
- */
- var $is_autosave_preview = false;
- static function create_nonce( $post_id ) {
- $i = wp_nonce_tick();
- return substr( wp_hash( $i . '|' . $post_id, 'nonce' ), -12, 10 );
- }
- static function verify_nonce( $nonce, $post_id ) {
- $i = wp_nonce_tick();
- // Nonce generated 0-12 hours ago
- $expected = substr( wp_hash( $i . '|' . $post_id, 'nonce' ), -12, 10 );
- return hash_equals( $expected, $nonce );
- }
- static function get_preview_link( $post ) {
- $link = get_permalink( $post->ID );
- $query_args = array(
- 'preview' => 'true',
- self::QUERY_VAR_NAME => self::create_nonce( $post->ID ),
- );
- return add_query_arg( $query_args, $link );
- }
- function query_vars( $qvars ) {
- $qvars[] = self::QUERY_VAR_NAME;
- return $qvars;
- }
- function can_view( $post_id ) {
- $preview_nonce = $_GET[ self::QUERY_VAR_NAME ];
- if ( '' != $preview_nonce && self::verify_nonce( $preview_nonce, $post_id ) ) {
- return true;
- }
- return false;
- }
- function capture_preview_vars() {
- if ( isset( $_GET[ 'preview_id' ] ) && isset( $_GET[ 'preview_nonce' ] ) ) {
- $post_id = intval( $_GET[ 'preview_id' ] );
- if ( $this->can_view( $post_id ) ) {
- $this->is_autosave_preview = true;
- unset( $_GET[ 'preview_id' ] );
- unset( $_GET[ 'preview_nonce' ] );
- }
- }
- }
- function posts_results_intercept( $posts ) {
- if ( 1 != count( $posts ) ) {
- return $posts;
- }
- $post = & $posts[ 0 ];
- $status = $post->post_status;
- if ( 'publish' != $status && $this->can_view( $post->ID ) ) {
- $this->shared_post = & $post;
- } else if ( $this->is_autosave_preview && $this->can_view( $post->ID ) ) {
- $autosave = wp_get_post_autosave( $post->ID );
- $this->shared_post = & $autosave;
- }
- return $posts;
- }
- function the_posts_intercept( $posts ) {
- if ( !is_null( $this->shared_post ) ) {
- return array( & $this->shared_post );
- }
- return $posts;
- }
- function __construct() {
- add_filter( 'query_vars', array( $this, 'query_vars' ) );
- if ( isset( $_REQUEST[ self::QUERY_VAR_NAME ] ) ) {
- add_action( 'init', array( $this, 'capture_preview_vars' ), 9 );
- add_filter( 'posts_results', array( $this, 'posts_results_intercept' ) );
- add_filter( 'the_posts', array( $this, 'the_posts_intercept' ) );
- }
- }
- }
- new Jetpack_Post_Previews();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement