<?php	
/*
Plugin name: Admin-Post-Diff
Plugin URI: 
Description: Adding a diff output to the status messages displayed in post/pages editor.
Author: Thorsten Ott
Author URI: http://thorsten-ott.de/
*/


/**
 * check if the content of the current post is different from the post_content in $_POST and store the diff in _filtered_diff post_meta
 *
 * @param int $post_id the post id of the post that is edited
 * @return bool returns false if no post_id was given or $_POST['post_content'] is not set,otherwise true
 */
function check_post_diff( $post_id = '' ) {
	if ( isset( $_POST['post_content'] ) && !empty( $post_id ) ) {
		$posted_content = stripslashes_deep( $_POST['post_content'] );
		$this_post = get_post( $post_id );
		if ( $this_post && $content = wp_text_diff( $posted_content, $this_post->post_content ) )
			add_post_meta( $post_id, '_filtered_diff', $content );
	else
		delete_post_meta( $post_id, '_filtered_diff' );
		return false;
	}
	return true;
}

/**
 * Filter function that alters the admin message to include the diff stored in _filtered_diff post meta
 *
 * @param string $message the message text that should be altered. text is appended to the message
 * @return string the altered message
 */
function print_post_diff( $message = '' ) {
	global $post;
	if ( $diff = get_post_meta( $post->ID, '_filtered_diff' ) )
		delete_post_meta( $post->ID, '_filtered_diff' ); // make sure we show it only once
		
	if( !is_array( $diff ) )
		return $message;
	
	$diff_txt = array_pop($diff);
	if ( empty( $diff_txt ) ) // should not happen, but who knows
		return $message;
		
	return $message . '<div class="admin-message-diff-container" style="word-wrap: break-word; word-break: break-all;"><p>' . __( 'Parts of your post have been altered. Usually this happens due to filtering prohibited or insecure code such as embedded scripts from your content.' ) . '</p><p>' . __( 'See the changes below :' ) . '</p>' . $diff_txt . '</div>';
}

/**
 * Initialize filters and actions.
 */
function init_admin_post_diff() {
	add_filter( 'post_admin_message', 'print_post_diff', 10 );
	add_action( 'pre_post_redirect', 'check_post_diff', 10, 1);

	add_filter( 'page_admin_message', 'print_post_diff', 10 );
	add_action( 'pre_page_redirect', 'check_post_diff', 10, 1);
}

add_action( 'init', 'init_admin_post_diff' );

?>
