Post revisions from mdawaffe. see #6775

git-svn-id: http://svn.automattic.com/wordpress/trunk@7747 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
ryan 2008-04-18 23:38:21 +00:00
parent 17deb910aa
commit 35086b850f
22 changed files with 2698 additions and 9 deletions

View File

@ -460,6 +460,8 @@ case 'add-user' :
$x->send();
break;
case 'autosave' : // The name of this action is hardcoded in edit_post()
define( 'DOING_AUTOSAVE', true );
$nonce_age = check_ajax_referer( 'autosave', 'autosavenonce');
global $current_user;

View File

@ -2,7 +2,7 @@ a.page-numbers:hover {
border-color: #999;
}
body {
body, .form-table pre {
background-color: #fff;
color: #333;
}
@ -713,3 +713,18 @@ div#media-upload-error, .file-error, abbr.required, .widget-control-remove:hover
background-color: #ddd;
color: #333;
}
/* Diff */
table.diff .diff-deletedline {
background-color: #ffdddd;
}
table.diff .diff-deletedline del {
background-color: #ff9999;
}
table.diff .diff-addedline {
background-color: #ddffdd;
}
table.diff .diff-addedline ins {
background-color: #99ff99;
}

View File

@ -2,7 +2,7 @@ a.page-numbers:hover {
border-color: #999;
}
body {
body, .form-table pre {
background-color: #fff;
color: #333;
}
@ -684,3 +684,18 @@ div#media-upload-error, .file-error, abbr.required, .widget-control-remove:hover
background-color: #ddd;
color: #333;
}
/* Diff */
table.diff .diff-deletedline {
background-color: #ffdddd;
}
table.diff .diff-deletedline del {
background-color: #ff9999;
}
table.diff .diff-addedline {
background-color: #ddffdd;
}
table.diff .diff-addedline ins {
background-color: #99ff99;
}

View File

@ -111,7 +111,10 @@ div#dashboard-widgets {
.tablenav-pages {
display: block;
margin-top: -3px;
}
table.ie-fixed {
table-layout: fixed;
}
#post-search .button, #widget-search .button {

View File

@ -6,6 +6,7 @@ $messages[1] = sprintf( __( 'Post updated. Continue editing below or <a href="%s
$messages[2] = __('Custom field updated.');
$messages[3] = __('Custom field deleted.');
$messages[4] = __('Post updated.');
$messages[5] = sprintf( __('Post restored to revision from %s'), wp_post_revision_time( $_GET['revision'] ) );
?>
<?php if (isset($_GET['message'])) : ?>
<div id="message" class="updated fade"><p><?php echo $messages[$_GET['message']]; ?></p></div>
@ -336,6 +337,15 @@ if ( $authors && count( $authors ) > 1 ) :
</div>
<?php endif; ?>
<?php if ( isset($post_ID) && 0 < $post_ID && wp_get_post_revisions( $post_ID ) ) : ?>
<div id="revisionsdiv" class="postbox <?php echo postbox_classes('revisionsdiv', 'post'); ?>">
<h3><?php _e('Post Revisions'); ?></h3>
<div class="inside">
<?php wp_list_post_revisions(); ?>
</div>
</div>
<?php endif; ?>
<?php do_meta_boxes('post', 'advanced', $post); ?>
<?php do_action('dbx_post_sidebar'); ?>

View File

@ -70,8 +70,8 @@ case 'edit':
if ( empty($post->ID) ) wp_die( __("You attempted to edit a page that doesn't exist. Perhaps it was deleted?") );
if ( 'post' == $post->post_type ) {
wp_redirect("post.php?action=edit&post=$post_ID");
if ( 'page' != $post->post_type ) {
wp_redirect( get_edit_post_link( $post_ID, 'url' ) );
exit();
}

View File

@ -77,8 +77,8 @@ case 'edit':
if ( empty($post->ID) ) wp_die( __("You attempted to edit a post that doesn't exist. Perhaps it was deleted?") );
if ( 'page' == $post->post_type ) {
wp_redirect("page.php?action=edit&post=$post_ID");
if ( 'post' != $post->post_type ) {
wp_redirect( get_edit_post_link( $post->ID, 'url' ) );
exit();
}

132
wp-admin/revision.php Normal file
View File

@ -0,0 +1,132 @@
<?php
require_once('admin.php');
$parent_file = 'edit.php';
$submenu_file = 'edit.php';
wp_reset_vars(array('revision', 'diff', 'restore'));
$revision_id = absint($revision);
$diff = absint($diff);
if ( $diff ) {
$restore = false;
$revision = get_post( $revision_id );
$post = 'revision' == $revision->post_type ? get_post( $revision->post_parent ) : get_post( $revision_id );
$left_revision = get_post( $diff );
// Don't allow reverse diffs?
if ( strtotime($revision->post_modified_gmt) < strtotime($left_revision->post_modified_gmt) ) {
wp_redirect( add_query_arg( array( 'diff' => $revision->ID, 'revision' => $diff ) ) );
exit;
}
$h2 = __( 'Compare Revisions of &#8220;%1$s&#8221;' );
$right = $revision->ID;
$left = $left_revision->ID;
if (
// They're the same
$left_revision->ID == $revision->ID
||
// They don't have a comment parent (and we're not comparing a revision to it's post)
( $left_revision->ID != $revision->post_parent && $left_revision->post_parent != $revision->ID && $left_revision->post_parent != $revision->post_parent )
||
// Neither is a revision
( !wp_get_revision( $left_revision->ID ) && !wp_get_revision( $revision->ID ) )
) {
wp_redirect( get_edit_post_link( $revision->ID, 'url' ) );
exit();
}
} else {
$revision = wp_get_revision( $revision_id );
$post = get_post( $revision->post_parent );
$h2 = __( 'Post Revision for &#8220;%1$s&#8221; created on %2$s' );
$right = $post->ID;
$left = $revision->ID;
}
if ( !$revision || !$post ) {
wp_redirect("edit.php");
exit();
}
if ( $restore && current_user_can( 'edit_post', $revision->post_parent ) ) {
check_admin_referer( "restore-post_$post->ID|$revision->ID" );
wp_restore_revision( $revision->ID );
wp_redirect( add_query_arg( array( 'message' => 5, 'revision' => $revision->ID ), get_edit_post_link( $post->ID, 'url' ) ) );
exit;
}
add_filter( '_wp_revision_field_post_author', 'get_author_name' );
$title = __( 'Post Revision' );
require_once( 'admin-header.php' );
$post_title = '<a href="' . get_edit_post_link() . '">' . get_the_title() . '</a>';
$revision_time = wp_post_revision_time( $revision );
?>
<div class="wrap">
<h2 style="padding-right: 0"><?php printf( $h2, $post_title, $revision_time ); ?></h2>
<table class="form-table ie-fixed">
<col class="th" />
<?php if ( $diff ) : ?>
<tr id="revision">
<th scope="row"></th>
<th scope="col" class="th-full"><?php printf( __('Older: %s'), wp_post_revision_time( $left_revision ) ); ?></td>
<th scope="col" class="th-full"><?php printf( __('Newer: %s'), wp_post_revision_time( $revision ) ); ?></td>
</tr>
<?php endif;
// use get_post_to_edit ?
$identical = true;
foreach ( _wp_revision_fields() as $field => $field_title ) :
if ( !$diff )
add_filter( "_wp_revision_field_$field", 'htmlspecialchars' );
$content = apply_filters( "_wp_revision_field_$field", $revision->$field, $field );
if ( $diff ) {
$left_content = apply_filters( "_wp_revision_field_$field", $left_revision->$field, $field );
if ( !$content = wp_text_diff( $left_content, $content ) )
continue;
}
$identical = false;
?>
<tr id="revision-field-<?php echo $field; ?>"?>
<th scope="row"><?php echo wp_specialchars( $field_title ); ?></th>
<td colspan="2"><pre><?php echo $content; ?></pre></td>
</tr>
<?php
endforeach;
if ( $diff && $identical ) :
?>
<tr><td colspan="3"><div class="updated"><p><?php _e( 'These revisions are identical' ); ?></p></div></td></tr>
<?php
endif;
?>
</table>
<br class="clear" />
<h2><?php _e( 'Post Revisions' ); ?></h2>
<?php
wp_list_post_revisions( $post, array( 'format' => 'form-table', 'exclude' => $revision->ID, 'parent' => true, 'right' => $right, 'left' => $left ) );
require_once( 'admin-footer.php' );

View File

@ -894,6 +894,21 @@ html, body {
margin-right: 5px
}
.form-table pre {
padding: 8px;
margin: 0;
/* http://www.longren.org/2006/09/27/wrapping-text-inside-pre-tags/ */
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
table.form-table td .updated {
font-size: 13px;
}
/* Post Screen */
#tagsdiv #newtag {
@ -1464,3 +1479,27 @@ td.action-links, th.action-links {
.hide-if-no-js {
display: none;
}
/* Diff */
table.diff {
width: 100%;
}
table.diff col.content {
width: 50%;
}
table.diff tr {
background-color: transparent;
}
table.diff td, table.diff th {
padding: .5em;
font-family: monospace;
border: none;
}
table.diff .diff-deletedline del, table.diff .diff-addedline ins {
text-decoration: none;
}

413
wp-includes/Text/Diff.php Normal file
View File

@ -0,0 +1,413 @@
<?php
/**
* General API for generating and formatting diffs - the differences between
* two sequences of strings.
*
* The original PHP version of this code was written by Geoffrey T. Dairiki
* <dairiki@dairiki.org>, and is used/adapted with his permission.
*
* $Horde: framework/Text_Diff/Diff.php,v 1.26 2008/01/04 10:07:49 jan Exp $
*
* Copyright 2004 Geoffrey T. Dairiki <dairiki@dairiki.org>
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*/
class Text_Diff {
/**
* Array of changes.
*
* @var array
*/
var $_edits;
/**
* Computes diffs between sequences of strings.
*
* @param string $engine Name of the diffing engine to use. 'auto'
* will automatically select the best.
* @param array $params Parameters to pass to the diffing engine.
* Normally an array of two arrays, each
* containing the lines from a file.
*/
function Text_Diff($engine, $params)
{
// Backward compatibility workaround.
if (!is_string($engine)) {
$params = array($engine, $params);
$engine = 'auto';
}
if ($engine == 'auto') {
$engine = extension_loaded('xdiff') ? 'xdiff' : 'native';
} else {
$engine = basename($engine);
}
require_once 'Text/Diff/Engine/' . $engine . '.php';
$class = 'Text_Diff_Engine_' . $engine;
$diff_engine = new $class();
$this->_edits = call_user_func_array(array($diff_engine, 'diff'), $params);
}
/**
* Returns the array of differences.
*/
function getDiff()
{
return $this->_edits;
}
/**
* Computes a reversed diff.
*
* Example:
* <code>
* $diff = new Text_Diff($lines1, $lines2);
* $rev = $diff->reverse();
* </code>
*
* @return Text_Diff A Diff object representing the inverse of the
* original diff. Note that we purposely don't return a
* reference here, since this essentially is a clone()
* method.
*/
function reverse()
{
if (version_compare(zend_version(), '2', '>')) {
$rev = clone($this);
} else {
$rev = $this;
}
$rev->_edits = array();
foreach ($this->_edits as $edit) {
$rev->_edits[] = $edit->reverse();
}
return $rev;
}
/**
* Checks for an empty diff.
*
* @return boolean True if two sequences were identical.
*/
function isEmpty()
{
foreach ($this->_edits as $edit) {
if (!is_a($edit, 'Text_Diff_Op_copy')) {
return false;
}
}
return true;
}
/**
* Computes the length of the Longest Common Subsequence (LCS).
*
* This is mostly for diagnostic purposes.
*
* @return integer The length of the LCS.
*/
function lcs()
{
$lcs = 0;
foreach ($this->_edits as $edit) {
if (is_a($edit, 'Text_Diff_Op_copy')) {
$lcs += count($edit->orig);
}
}
return $lcs;
}
/**
* Gets the original set of lines.
*
* This reconstructs the $from_lines parameter passed to the constructor.
*
* @return array The original sequence of strings.
*/
function getOriginal()
{
$lines = array();
foreach ($this->_edits as $edit) {
if ($edit->orig) {
array_splice($lines, count($lines), 0, $edit->orig);
}
}
return $lines;
}
/**
* Gets the final set of lines.
*
* This reconstructs the $to_lines parameter passed to the constructor.
*
* @return array The sequence of strings.
*/
function getFinal()
{
$lines = array();
foreach ($this->_edits as $edit) {
if ($edit->final) {
array_splice($lines, count($lines), 0, $edit->final);
}
}
return $lines;
}
/**
* Removes trailing newlines from a line of text. This is meant to be used
* with array_walk().
*
* @param string $line The line to trim.
* @param integer $key The index of the line in the array. Not used.
*/
function trimNewlines(&$line, $key)
{
$line = str_replace(array("\n", "\r"), '', $line);
}
/**
* Determines the location of the system temporary directory.
*
* @static
*
* @access protected
*
* @return string A directory name which can be used for temp files.
* Returns false if one could not be found.
*/
function _getTempDir()
{
$tmp_locations = array('/tmp', '/var/tmp', 'c:\WUTemp', 'c:\temp',
'c:\windows\temp', 'c:\winnt\temp');
/* Try PHP's upload_tmp_dir directive. */
$tmp = ini_get('upload_tmp_dir');
/* Otherwise, try to determine the TMPDIR environment variable. */
if (!strlen($tmp)) {
$tmp = getenv('TMPDIR');
}
/* If we still cannot determine a value, then cycle through a list of
* preset possibilities. */
while (!strlen($tmp) && count($tmp_locations)) {
$tmp_check = array_shift($tmp_locations);
if (@is_dir($tmp_check)) {
$tmp = $tmp_check;
}
}
/* If it is still empty, we have failed, so return false; otherwise
* return the directory determined. */
return strlen($tmp) ? $tmp : false;
}
/**
* Checks a diff for validity.
*
* This is here only for debugging purposes.
*/
function _check($from_lines, $to_lines)
{
if (serialize($from_lines) != serialize($this->getOriginal())) {
trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
}
if (serialize($to_lines) != serialize($this->getFinal())) {
trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
}
$rev = $this->reverse();
if (serialize($to_lines) != serialize($rev->getOriginal())) {
trigger_error("Reversed original doesn't match", E_USER_ERROR);
}
if (serialize($from_lines) != serialize($rev->getFinal())) {
trigger_error("Reversed final doesn't match", E_USER_ERROR);
}
$prevtype = null;
foreach ($this->_edits as $edit) {
if ($prevtype == get_class($edit)) {
trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
}
$prevtype = get_class($edit);
}
return true;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*/
class Text_MappedDiff extends Text_Diff {
/**
* Computes a diff between sequences of strings.
*
* This can be used to compute things like case-insensitve diffs, or diffs
* which ignore changes in white-space.
*
* @param array $from_lines An array of strings.
* @param array $to_lines An array of strings.
* @param array $mapped_from_lines This array should have the same size
* number of elements as $from_lines. The
* elements in $mapped_from_lines and
* $mapped_to_lines are what is actually
* compared when computing the diff.
* @param array $mapped_to_lines This array should have the same number
* of elements as $to_lines.
*/
function Text_MappedDiff($from_lines, $to_lines,
$mapped_from_lines, $mapped_to_lines)
{
assert(count($from_lines) == count($mapped_from_lines));
assert(count($to_lines) == count($mapped_to_lines));
parent::Text_Diff($mapped_from_lines, $mapped_to_lines);
$xi = $yi = 0;
for ($i = 0; $i < count($this->_edits); $i++) {
$orig = &$this->_edits[$i]->orig;
if (is_array($orig)) {
$orig = array_slice($from_lines, $xi, count($orig));
$xi += count($orig);
}
$final = &$this->_edits[$i]->final;
if (is_array($final)) {
$final = array_slice($to_lines, $yi, count($final));
$yi += count($final);
}
}
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_Op {
var $orig;
var $final;
function &reverse()
{
trigger_error('Abstract method', E_USER_ERROR);
}
function norig()
{
return $this->orig ? count($this->orig) : 0;
}
function nfinal()
{
return $this->final ? count($this->final) : 0;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_Op_copy extends Text_Diff_Op {
function Text_Diff_Op_copy($orig, $final = false)
{
if (!is_array($final)) {
$final = $orig;
}
$this->orig = $orig;
$this->final = $final;
}
function &reverse()
{
$reverse = &new Text_Diff_Op_copy($this->final, $this->orig);
return $reverse;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_Op_delete extends Text_Diff_Op {
function Text_Diff_Op_delete($lines)
{
$this->orig = $lines;
$this->final = false;
}
function &reverse()
{
$reverse = &new Text_Diff_Op_add($this->orig);
return $reverse;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_Op_add extends Text_Diff_Op {
function Text_Diff_Op_add($lines)
{
$this->final = $lines;
$this->orig = false;
}
function &reverse()
{
$reverse = &new Text_Diff_Op_delete($this->final);
return $reverse;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_Op_change extends Text_Diff_Op {
function Text_Diff_Op_change($orig, $final)
{
$this->orig = $orig;
$this->final = $final;
}
function &reverse()
{
$reverse = &new Text_Diff_Op_change($this->final, $this->orig);
return $reverse;
}
}

View File

@ -0,0 +1,437 @@
<?php
/**
* $Horde: framework/Text_Diff/Diff/Engine/native.php,v 1.10 2008/01/04 10:27:53 jan Exp $
*
* Class used internally by Text_Diff to actually compute the diffs. This
* class is implemented using native PHP code.
*
* The algorithm used here is mostly lifted from the perl module
* Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
* http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
*
* More ideas are taken from: http://www.ics.uci.edu/~eppstein/161/960229.html
*
* Some ideas (and a bit of code) are taken from analyze.c, of GNU
* diffutils-2.7, which can be found at:
* ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
*
* Some ideas (subdivision by NCHUNKS > 2, and some optimizations) are from
* Geoffrey T. Dairiki <dairiki@dairiki.org>. The original PHP version of this
* code was written by him, and is used/adapted with his permission.
*
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
* @package Text_Diff
*/
class Text_Diff_Engine_native {
function diff($from_lines, $to_lines)
{
array_walk($from_lines, array('Text_Diff', 'trimNewlines'));
array_walk($to_lines, array('Text_Diff', 'trimNewlines'));
$n_from = count($from_lines);
$n_to = count($to_lines);
$this->xchanged = $this->ychanged = array();
$this->xv = $this->yv = array();
$this->xind = $this->yind = array();
unset($this->seq);
unset($this->in_seq);
unset($this->lcs);
// Skip leading common lines.
for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
if ($from_lines[$skip] !== $to_lines[$skip]) {
break;
}
$this->xchanged[$skip] = $this->ychanged[$skip] = false;
}
// Skip trailing common lines.
$xi = $n_from; $yi = $n_to;
for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
if ($from_lines[$xi] !== $to_lines[$yi]) {
break;
}
$this->xchanged[$xi] = $this->ychanged[$yi] = false;
}
// Ignore lines which do not exist in both files.
for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
$xhash[$from_lines[$xi]] = 1;
}
for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
$line = $to_lines[$yi];
if (($this->ychanged[$yi] = empty($xhash[$line]))) {
continue;
}
$yhash[$line] = 1;
$this->yv[] = $line;
$this->yind[] = $yi;
}
for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
$line = $from_lines[$xi];
if (($this->xchanged[$xi] = empty($yhash[$line]))) {
continue;
}
$this->xv[] = $line;
$this->xind[] = $xi;
}
// Find the LCS.
$this->_compareseq(0, count($this->xv), 0, count($this->yv));
// Merge edits when possible.
$this->_shiftBoundaries($from_lines, $this->xchanged, $this->ychanged);
$this->_shiftBoundaries($to_lines, $this->ychanged, $this->xchanged);
// Compute the edit operations.
$edits = array();
$xi = $yi = 0;
while ($xi < $n_from || $yi < $n_to) {
assert($yi < $n_to || $this->xchanged[$xi]);
assert($xi < $n_from || $this->ychanged[$yi]);
// Skip matching "snake".
$copy = array();
while ($xi < $n_from && $yi < $n_to
&& !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
$copy[] = $from_lines[$xi++];
++$yi;
}
if ($copy) {
$edits[] = &new Text_Diff_Op_copy($copy);
}
// Find deletes & adds.
$delete = array();
while ($xi < $n_from && $this->xchanged[$xi]) {
$delete[] = $from_lines[$xi++];
}
$add = array();
while ($yi < $n_to && $this->ychanged[$yi]) {
$add[] = $to_lines[$yi++];
}
if ($delete && $add) {
$edits[] = &new Text_Diff_Op_change($delete, $add);
} elseif ($delete) {
$edits[] = &new Text_Diff_Op_delete($delete);
} elseif ($add) {
$edits[] = &new Text_Diff_Op_add($add);
}
}
return $edits;
}
/**
* Divides the Largest Common Subsequence (LCS) of the sequences (XOFF,
* XLIM) and (YOFF, YLIM) into NCHUNKS approximately equally sized
* segments.
*
* Returns (LCS, PTS). LCS is the length of the LCS. PTS is an array of
* NCHUNKS+1 (X, Y) indexes giving the diving points between sub
* sequences. The first sub-sequence is contained in (X0, X1), (Y0, Y1),
* the second in (X1, X2), (Y1, Y2) and so on. Note that (X0, Y0) ==
* (XOFF, YOFF) and (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
*
* This function assumes that the first lines of the specified portions of
* the two files do not match, and likewise that the last lines do not
* match. The caller must trim matching lines from the beginning and end
* of the portions it is going to specify.
*/
function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks)
{
$flip = false;
if ($xlim - $xoff > $ylim - $yoff) {
/* Things seems faster (I'm not sure I understand why) when the
* shortest sequence is in X. */
$flip = true;
list ($xoff, $xlim, $yoff, $ylim)
= array($yoff, $ylim, $xoff, $xlim);
}
if ($flip) {
for ($i = $ylim - 1; $i >= $yoff; $i--) {
$ymatches[$this->xv[$i]][] = $i;
}
} else {
for ($i = $ylim - 1; $i >= $yoff; $i--) {
$ymatches[$this->yv[$i]][] = $i;
}
}
$this->lcs = 0;
$this->seq[0]= $yoff - 1;
$this->in_seq = array();
$ymids[0] = array();
$numer = $xlim - $xoff + $nchunks - 1;
$x = $xoff;
for ($chunk = 0; $chunk < $nchunks; $chunk++) {
if ($chunk > 0) {
for ($i = 0; $i <= $this->lcs; $i++) {
$ymids[$i][$chunk - 1] = $this->seq[$i];
}
}
$x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $chunk) / $nchunks);
for (; $x < $x1; $x++) {
$line = $flip ? $this->yv[$x] : $this->xv[$x];
if (empty($ymatches[$line])) {
continue;
}
$matches = $ymatches[$line];
reset($matches);
while (list(, $y) = each($matches)) {
if (empty($this->in_seq[$y])) {
$k = $this->_lcsPos($y);
assert($k > 0);
$ymids[$k] = $ymids[$k - 1];
break;
}
}
while (list(, $y) = each($matches)) {
if ($y > $this->seq[$k - 1]) {
assert($y <= $this->seq[$k]);
/* Optimization: this is a common case: next match is
* just replacing previous match. */
$this->in_seq[$this->seq[$k]] = false;
$this->seq[$k] = $y;
$this->in_seq[$y] = 1;
} elseif (empty($this->in_seq[$y])) {
$k = $this->_lcsPos($y);
assert($k > 0);
$ymids[$k] = $ymids[$k - 1];
}
}
}
}
$seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
$ymid = $ymids[$this->lcs];
for ($n = 0; $n < $nchunks - 1; $n++) {
$x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
$y1 = $ymid[$n] + 1;
$seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
}
$seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
return array($this->lcs, $seps);
}
function _lcsPos($ypos)
{
$end = $this->lcs;
if ($end == 0 || $ypos > $this->seq[$end]) {
$this->seq[++$this->lcs] = $ypos;
$this->in_seq[$ypos] = 1;
return $this->lcs;
}
$beg = 1;
while ($beg < $end) {
$mid = (int)(($beg + $end) / 2);
if ($ypos > $this->seq[$mid]) {
$beg = $mid + 1;
} else {
$end = $mid;
}
}
assert($ypos != $this->seq[$end]);
$this->in_seq[$this->seq[$end]] = false;
$this->seq[$end] = $ypos;
$this->in_seq[$ypos] = 1;
return $end;
}
/**
* Finds LCS of two sequences.
*
* The results are recorded in the vectors $this->{x,y}changed[], by
* storing a 1 in the element for each line that is an insertion or
* deletion (ie. is not in the LCS).
*
* The subsequence of file 0 is (XOFF, XLIM) and likewise for file 1.
*
* Note that XLIM, YLIM are exclusive bounds. All line numbers are
* origin-0 and discarded lines are not counted.
*/
function _compareseq ($xoff, $xlim, $yoff, $ylim)
{
/* Slide down the bottom initial diagonal. */
while ($xoff < $xlim && $yoff < $ylim
&& $this->xv[$xoff] == $this->yv[$yoff]) {
++$xoff;
++$yoff;
}
/* Slide up the top initial diagonal. */
while ($xlim > $xoff && $ylim > $yoff
&& $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
--$xlim;
--$ylim;
}
if ($xoff == $xlim || $yoff == $ylim) {
$lcs = 0;
} else {
/* This is ad hoc but seems to work well. $nchunks =
* sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); $nchunks =
* max(2,min(8,(int)$nchunks)); */
$nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
list($lcs, $seps)
= $this->_diag($xoff, $xlim, $yoff, $ylim, $nchunks);
}
if ($lcs == 0) {
/* X and Y sequences have no common subsequence: mark all
* changed. */
while ($yoff < $ylim) {
$this->ychanged[$this->yind[$yoff++]] = 1;
}
while ($xoff < $xlim) {
$this->xchanged[$this->xind[$xoff++]] = 1;
}
} else {
/* Use the partitions to split this problem into subproblems. */
reset($seps);
$pt1 = $seps[0];
while ($pt2 = next($seps)) {
$this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
$pt1 = $pt2;
}
}
}
/**
* Adjusts inserts/deletes of identical lines to join changes as much as
* possible.
*
* We do something when a run of changed lines include a line at one end
* and has an excluded, identical line at the other. We are free to
* choose which identical line is included. `compareseq' usually chooses
* the one at the beginning, but usually it is cleaner to consider the
* following identical line to be the "change".
*
* This is extracted verbatim from analyze.c (GNU diffutils-2.7).
*/
function _shiftBoundaries($lines, &$changed, $other_changed)
{
$i = 0;
$j = 0;
assert('count($lines) == count($changed)');
$len = count($lines);
$other_len = count($other_changed);
while (1) {
/* Scan forward to find the beginning of another run of
* changes. Also keep track of the corresponding point in the
* other file.
*
* Throughout this code, $i and $j are adjusted together so that
* the first $i elements of $changed and the first $j elements of
* $other_changed both contain the same number of zeros (unchanged
* lines).
*
* Furthermore, $j is always kept so that $j == $other_len or
* $other_changed[$j] == false. */
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
while ($i < $len && ! $changed[$i]) {
assert('$j < $other_len && ! $other_changed[$j]');
$i++; $j++;
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
}
if ($i == $len) {
break;
}
$start = $i;
/* Find the end of this run of changes. */
while (++$i < $len && $changed[$i]) {
continue;
}
do {
/* Record the length of this run of changes, so that we can
* later determine whether the run has grown. */
$runlength = $i - $start;
/* Move the changed region back, so long as the previous
* unchanged line matches the last changed one. This merges
* with previous changed regions. */
while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
$changed[--$start] = 1;
$changed[--$i] = false;
while ($start > 0 && $changed[$start - 1]) {
$start--;
}
assert('$j > 0');
while ($other_changed[--$j]) {
continue;
}
assert('$j >= 0 && !$other_changed[$j]');
}
/* Set CORRESPONDING to the end of the changed run, at the
* last point where it corresponds to a changed run in the
* other file. CORRESPONDING == LEN means no such point has
* been found. */
$corresponding = $j < $other_len ? $i : $len;
/* Move the changed region forward, so long as the first
* changed line matches the following unchanged one. This
* merges with following changed regions. Do this second, so
* that if there are no merges, the changed region is moved
* forward as far as possible. */
while ($i < $len && $lines[$start] == $lines[$i]) {
$changed[$start++] = false;
$changed[$i++] = 1;
while ($i < $len && $changed[$i]) {
$i++;
}
assert('$j < $other_len && ! $other_changed[$j]');
$j++;
if ($j < $other_len && $other_changed[$j]) {
$corresponding = $i;
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
}
}
} while ($runlength != $i - $start);
/* If possible, move the fully-merged run of changes back to a
* corresponding run in the other file. */
while ($corresponding < $i) {
$changed[--$start] = 1;
$changed[--$i] = 0;
assert('$j > 0');
while ($other_changed[--$j]) {
continue;
}
assert('$j >= 0 && !$other_changed[$j]');
}
}
}
}

View File

@ -0,0 +1,164 @@
<?php
/**
* Class used internally by Diff to actually compute the diffs.
*
* This class uses the Unix `diff` program via shell_exec to compute the
* differences between the two input arrays.
*
* $Horde: framework/Text_Diff/Diff/Engine/shell.php,v 1.8 2008/01/04 10:07:50 jan Exp $
*
* Copyright 2007-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Milian Wolff <mail@milianw.de>
* @package Text_Diff
* @since 0.3.0
*/
class Text_Diff_Engine_shell {
/**
* Path to the diff executable
*
* @var string
*/
var $_diffCommand = 'diff';
/**
* Returns the array of differences.
*
* @param array $from_lines lines of text from old file
* @param array $to_lines lines of text from new file
*
* @return array all changes made (array with Text_Diff_Op_* objects)
*/
function diff($from_lines, $to_lines)
{
array_walk($from_lines, array('Text_Diff', 'trimNewlines'));
array_walk($to_lines, array('Text_Diff', 'trimNewlines'));
$temp_dir = Text_Diff::_getTempDir();
// Execute gnu diff or similar to get a standard diff file.
$from_file = tempnam($temp_dir, 'Text_Diff');
$to_file = tempnam($temp_dir, 'Text_Diff');
$fp = fopen($from_file, 'w');
fwrite($fp, implode("\n", $from_lines));
fclose($fp);
$fp = fopen($to_file, 'w');
fwrite($fp, implode("\n", $to_lines));
fclose($fp);
$diff = shell_exec($this->_diffCommand . ' ' . $from_file . ' ' . $to_file);
unlink($from_file);
unlink($to_file);
if (is_null($diff)) {
// No changes were made
return array(new Text_Diff_Op_copy($from_lines));
}
$from_line_no = 1;
$to_line_no = 1;
$edits = array();
// Get changed lines by parsing something like:
// 0a1,2
// 1,2c4,6
// 1,5d6
preg_match_all('#^(\d+)(?:,(\d+))?([adc])(\d+)(?:,(\d+))?$#m', $diff,
$matches, PREG_SET_ORDER);
foreach ($matches as $match) {
if (!isset($match[5])) {
// This paren is not set every time (see regex).
$match[5] = false;
}
if ($match[3] == 'a') {
$from_line_no--;
}
if ($match[3] == 'd') {
$to_line_no--;
}
if ($from_line_no < $match[1] || $to_line_no < $match[4]) {
// copied lines
assert('$match[1] - $from_line_no == $match[4] - $to_line_no');
array_push($edits,
new Text_Diff_Op_copy(
$this->_getLines($from_lines, $from_line_no, $match[1] - 1),
$this->_getLines($to_lines, $to_line_no, $match[4] - 1)));
}
switch ($match[3]) {
case 'd':
// deleted lines
array_push($edits,
new Text_Diff_Op_delete(
$this->_getLines($from_lines, $from_line_no, $match[2])));
$to_line_no++;
break;
case 'c':
// changed lines
array_push($edits,
new Text_Diff_Op_change(
$this->_getLines($from_lines, $from_line_no, $match[2]),
$this->_getLines($to_lines, $to_line_no, $match[5])));
break;
case 'a':
// added lines
array_push($edits,
new Text_Diff_Op_add(
$this->_getLines($to_lines, $to_line_no, $match[5])));
$from_line_no++;
break;
}
}
if (!empty($from_lines)) {
// Some lines might still be pending. Add them as copied
array_push($edits,
new Text_Diff_Op_copy(
$this->_getLines($from_lines, $from_line_no,
$from_line_no + count($from_lines) - 1),
$this->_getLines($to_lines, $to_line_no,
$to_line_no + count($to_lines) - 1)));
}
return $edits;
}
/**
* Get lines from either the old or new text
*
* @access private
*
* @param array &$text_lines Either $from_lines or $to_lines
* @param int &$line_no Current line number
* @param int $end Optional end line, when we want to chop more
* than one line.
*
* @return array The chopped lines
*/
function _getLines(&$text_lines, &$line_no, $end = false)
{
if (!empty($end)) {
$lines = array();
// We can shift even more
while ($line_no <= $end) {
array_push($lines, array_shift($text_lines));
$line_no++;
}
} else {
$lines = array(array_shift($text_lines));
$line_no++;
}
return $lines;
}
}

View File

@ -0,0 +1,234 @@
<?php
/**
* Parses unified or context diffs output from eg. the diff utility.
*
* Example:
* <code>
* $patch = file_get_contents('example.patch');
* $diff = new Text_Diff('string', array($patch));
* $renderer = new Text_Diff_Renderer_inline();
* echo $renderer->render($diff);
* </code>
*
* $Horde: framework/Text_Diff/Diff/Engine/string.php,v 1.7 2008/01/04 10:07:50 jan Exp $
*
* Copyright 2005 Örjan Persson <o@42mm.org>
* Copyright 2005-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Örjan Persson <o@42mm.org>
* @package Text_Diff
* @since 0.2.0
*/
class Text_Diff_Engine_string {
/**
* Parses a unified or context diff.
*
* First param contains the whole diff and the second can be used to force
* a specific diff type. If the second parameter is 'autodetect', the
* diff will be examined to find out which type of diff this is.
*
* @param string $diff The diff content.
* @param string $mode The diff mode of the content in $diff. One of
* 'context', 'unified', or 'autodetect'.
*
* @return array List of all diff operations.
*/
function diff($diff, $mode = 'autodetect')
{
if ($mode != 'autodetect' && $mode != 'context' && $mode != 'unified') {
return PEAR::raiseError('Type of diff is unsupported');
}
if ($mode == 'autodetect') {
$context = strpos($diff, '***');
$unified = strpos($diff, '---');
if ($context === $unified) {
return PEAR::raiseError('Type of diff could not be detected');
} elseif ($context === false || $context === false) {
$mode = $context !== false ? 'context' : 'unified';
} else {
$mode = $context < $unified ? 'context' : 'unified';
}
}
// split by new line and remove the diff header
$diff = explode("\n", $diff);
array_shift($diff);
array_shift($diff);
if ($mode == 'context') {
return $this->parseContextDiff($diff);
} else {
return $this->parseUnifiedDiff($diff);
}
}
/**
* Parses an array containing the unified diff.
*
* @param array $diff Array of lines.
*
* @return array List of all diff operations.
*/
function parseUnifiedDiff($diff)
{
$edits = array();
$end = count($diff) - 1;
for ($i = 0; $i < $end;) {
$diff1 = array();
switch (substr($diff[$i], 0, 1)) {
case ' ':
do {
$diff1[] = substr($diff[$i], 1);
} while (++$i < $end && substr($diff[$i], 0, 1) == ' ');
$edits[] = &new Text_Diff_Op_copy($diff1);
break;
case '+':
// get all new lines
do {
$diff1[] = substr($diff[$i], 1);
} while (++$i < $end && substr($diff[$i], 0, 1) == '+');
$edits[] = &new Text_Diff_Op_add($diff1);
break;
case '-':
// get changed or removed lines
$diff2 = array();
do {
$diff1[] = substr($diff[$i], 1);
} while (++$i < $end && substr($diff[$i], 0, 1) == '-');
while ($i < $end && substr($diff[$i], 0, 1) == '+') {
$diff2[] = substr($diff[$i++], 1);
}
if (count($diff2) == 0) {
$edits[] = &new Text_Diff_Op_delete($diff1);
} else {
$edits[] = &new Text_Diff_Op_change($diff1, $diff2);
}
break;
default:
$i++;
break;
}
}
return $edits;
}
/**
* Parses an array containing the context diff.
*
* @param array $diff Array of lines.
*
* @return array List of all diff operations.
*/
function parseContextDiff(&$diff)
{
$edits = array();
$i = $max_i = $j = $max_j = 0;
$end = count($diff) - 1;
while ($i < $end && $j < $end) {
while ($i >= $max_i && $j >= $max_j) {
// Find the boundaries of the diff output of the two files
for ($i = $j;
$i < $end && substr($diff[$i], 0, 3) == '***';
$i++);
for ($max_i = $i;
$max_i < $end && substr($diff[$max_i], 0, 3) != '---';
$max_i++);
for ($j = $max_i;
$j < $end && substr($diff[$j], 0, 3) == '---';
$j++);
for ($max_j = $j;
$max_j < $end && substr($diff[$max_j], 0, 3) != '***';
$max_j++);
}
// find what hasn't been changed
$array = array();
while ($i < $max_i &&
$j < $max_j &&
strcmp($diff[$i], $diff[$j]) == 0) {
$array[] = substr($diff[$i], 2);
$i++;
$j++;
}
while ($i < $max_i && ($max_j-$j) <= 1) {
if ($diff[$i] != '' && substr($diff[$i], 0, 1) != ' ') {
break;
}
$array[] = substr($diff[$i++], 2);
}
while ($j < $max_j && ($max_i-$i) <= 1) {
if ($diff[$j] != '' && substr($diff[$j], 0, 1) != ' ') {
break;
}
$array[] = substr($diff[$j++], 2);
}
if (count($array) > 0) {
$edits[] = &new Text_Diff_Op_copy($array);
}
if ($i < $max_i) {
$diff1 = array();
switch (substr($diff[$i], 0, 1)) {
case '!':
$diff2 = array();
do {
$diff1[] = substr($diff[$i], 2);
if ($j < $max_j && substr($diff[$j], 0, 1) == '!') {
$diff2[] = substr($diff[$j++], 2);
}
} while (++$i < $max_i && substr($diff[$i], 0, 1) == '!');
$edits[] = &new Text_Diff_Op_change($diff1, $diff2);
break;
case '+':
do {
$diff1[] = substr($diff[$i], 2);
} while (++$i < $max_i && substr($diff[$i], 0, 1) == '+');
$edits[] = &new Text_Diff_Op_add($diff1);
break;
case '-':
do {
$diff1[] = substr($diff[$i], 2);
} while (++$i < $max_i && substr($diff[$i], 0, 1) == '-');
$edits[] = &new Text_Diff_Op_delete($diff1);
break;
}
}
if ($j < $max_j) {
$diff2 = array();
switch (substr($diff[$j], 0, 1)) {
case '+':
do {
$diff2[] = substr($diff[$j++], 2);
} while ($j < $max_j && substr($diff[$j], 0, 1) == '+');
$edits[] = &new Text_Diff_Op_add($diff2);
break;
case '-':
do {
$diff2[] = substr($diff[$j++], 2);
} while ($j < $max_j && substr($diff[$j], 0, 1) == '-');
$edits[] = &new Text_Diff_Op_delete($diff2);
break;
}
}
}
return $edits;
}
}

View File

@ -0,0 +1,63 @@
<?php
/**
* Class used internally by Diff to actually compute the diffs.
*
* This class uses the xdiff PECL package (http://pecl.php.net/package/xdiff)
* to compute the differences between the two input arrays.
*
* $Horde: framework/Text_Diff/Diff/Engine/xdiff.php,v 1.6 2008/01/04 10:07:50 jan Exp $
*
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Jon Parise <jon@horde.org>
* @package Text_Diff
*/
class Text_Diff_Engine_xdiff {
/**
*/
function diff($from_lines, $to_lines)
{
array_walk($from_lines, array('Text_Diff', 'trimNewlines'));
array_walk($to_lines, array('Text_Diff', 'trimNewlines'));
/* Convert the two input arrays into strings for xdiff processing. */
$from_string = implode("\n", $from_lines);
$to_string = implode("\n", $to_lines);
/* Diff the two strings and convert the result to an array. */
$diff = xdiff_string_diff($from_string, $to_string, count($to_lines));
$diff = explode("\n", $diff);
/* Walk through the diff one line at a time. We build the $edits
* array of diff operations by reading the first character of the
* xdiff output (which is in the "unified diff" format).
*
* Note that we don't have enough information to detect "changed"
* lines using this approach, so we can't add Text_Diff_Op_changed
* instances to the $edits array. The result is still perfectly
* valid, albeit a little less descriptive and efficient. */
$edits = array();
foreach ($diff as $line) {
switch ($line[0]) {
case ' ':
$edits[] = &new Text_Diff_Op_copy(array(substr($line, 1)));
break;
case '+':
$edits[] = &new Text_Diff_Op_add(array(substr($line, 1)));
break;
case '-':
$edits[] = &new Text_Diff_Op_delete(array(substr($line, 1)));
break;
}
}
return $edits;
}
}

View File

@ -0,0 +1,237 @@
<?php
/**
* A class to render Diffs in different formats.
*
* This class renders the diff in classic diff format. It is intended that
* this class be customized via inheritance, to obtain fancier outputs.
*
* $Horde: framework/Text_Diff/Diff/Renderer.php,v 1.21 2008/01/04 10:07:50 jan Exp $
*
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @package Text_Diff
*/
class Text_Diff_Renderer {
/**
* Number of leading context "lines" to preserve.
*
* This should be left at zero for this class, but subclasses may want to
* set this to other values.
*/
var $_leading_context_lines = 0;
/**
* Number of trailing context "lines" to preserve.
*
* This should be left at zero for this class, but subclasses may want to
* set this to other values.
*/
var $_trailing_context_lines = 0;
/**
* Constructor.
*/
function Text_Diff_Renderer($params = array())
{
foreach ($params as $param => $value) {
$v = '_' . $param;
if (isset($this->$v)) {
$this->$v = $value;
}
}
}
/**
* Get any renderer parameters.
*
* @return array All parameters of this renderer object.
*/
function getParams()
{
$params = array();
foreach (get_object_vars($this) as $k => $v) {
if ($k[0] == '_') {
$params[substr($k, 1)] = $v;
}
}
return $params;
}
/**
* Renders a diff.
*
* @param Text_Diff $diff A Text_Diff object.
*
* @return string The formatted output.
*/
function render($diff)
{
$xi = $yi = 1;
$block = false;
$context = array();
$nlead = $this->_leading_context_lines;
$ntrail = $this->_trailing_context_lines;
$output = $this->_startDiff();
$diffs = $diff->getDiff();
foreach ($diffs as $i => $edit) {
/* If these are unchanged (copied) lines, and we want to keep
* leading or trailing context lines, extract them from the copy
* block. */
if (is_a($edit, 'Text_Diff_Op_copy')) {
/* Do we have any diff blocks yet? */
if (is_array($block)) {
/* How many lines to keep as context from the copy
* block. */
$keep = $i == count($diffs) - 1 ? $ntrail : $nlead + $ntrail;
if (count($edit->orig) <= $keep) {
/* We have less lines in the block than we want for
* context => keep the whole block. */
$block[] = $edit;
} else {
if ($ntrail) {
/* Create a new block with as many lines as we need
* for the trailing context. */
$context = array_slice($edit->orig, 0, $ntrail);
$block[] = &new Text_Diff_Op_copy($context);
}
/* @todo */
$output .= $this->_block($x0, $ntrail + $xi - $x0,
$y0, $ntrail + $yi - $y0,
$block);
$block = false;
}
}
/* Keep the copy block as the context for the next block. */
$context = $edit->orig;
} else {
/* Don't we have any diff blocks yet? */
if (!is_array($block)) {
/* Extract context lines from the preceding copy block. */
$context = array_slice($context, count($context) - $nlead);
$x0 = $xi - count($context);
$y0 = $yi - count($context);
$block = array();
if ($context) {
$block[] = &new Text_Diff_Op_copy($context);
}
}
$block[] = $edit;
}
if ($edit->orig) {
$xi += count($edit->orig);
}
if ($edit->final) {
$yi += count($edit->final);
}
}
if (is_array($block)) {
$output .= $this->_block($x0, $xi - $x0,
$y0, $yi - $y0,
$block);
}
return $output . $this->_endDiff();
}
function _block($xbeg, $xlen, $ybeg, $ylen, &$edits)
{
$output = $this->_startBlock($this->_blockHeader($xbeg, $xlen, $ybeg, $ylen));
foreach ($edits as $edit) {
switch (strtolower(get_class($edit))) {
case 'text_diff_op_copy':
$output .= $this->_context($edit->orig);
break;
case 'text_diff_op_add':
$output .= $this->_added($edit->final);
break;
case 'text_diff_op_delete':
$output .= $this->_deleted($edit->orig);
break;
case 'text_diff_op_change':
$output .= $this->_changed($edit->orig, $edit->final);
break;
}
}
return $output . $this->_endBlock();
}
function _startDiff()
{
return '';
}
function _endDiff()
{
return '';
}
function _blockHeader($xbeg, $xlen, $ybeg, $ylen)
{
if ($xlen > 1) {
$xbeg .= ',' . ($xbeg + $xlen - 1);
}
if ($ylen > 1) {
$ybeg .= ',' . ($ybeg + $ylen - 1);
}
// this matches the GNU Diff behaviour
if ($xlen && !$ylen) {
$ybeg--;
} elseif (!$xlen) {
$xbeg--;
}
return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
}
function _startBlock($header)
{
return $header . "\n";
}
function _endBlock()
{
return '';
}
function _lines($lines, $prefix = ' ')
{
return $prefix . implode("\n$prefix", $lines) . "\n";
}
function _context($lines)
{
return $this->_lines($lines, ' ');
}
function _added($lines)
{
return $this->_lines($lines, '> ');
}
function _deleted($lines)
{
return $this->_lines($lines, '< ');
}
function _changed($orig, $final)
{
return $this->_deleted($orig) . "---\n" . $this->_added($final);
}
}

View File

@ -0,0 +1,170 @@
<?php
/**
* "Inline" diff renderer.
*
* $Horde: framework/Text_Diff/Diff/Renderer/inline.php,v 1.21 2008/01/04 10:07:51 jan Exp $
*
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Ciprian Popovici
* @package Text_Diff
*/
/** Text_Diff_Renderer */
require_once 'Text/Diff/Renderer.php';
/**
* "Inline" diff renderer.
*
* This class renders diffs in the Wiki-style "inline" format.
*
* @author Ciprian Popovici
* @package Text_Diff
*/
class Text_Diff_Renderer_inline extends Text_Diff_Renderer {
/**
* Number of leading context "lines" to preserve.
*/
var $_leading_context_lines = 10000;
/**
* Number of trailing context "lines" to preserve.
*/
var $_trailing_context_lines = 10000;
/**
* Prefix for inserted text.
*/
var $_ins_prefix = '<ins>';
/**
* Suffix for inserted text.
*/
var $_ins_suffix = '</ins>';
/**
* Prefix for deleted text.
*/
var $_del_prefix = '<del>';
/**
* Suffix for deleted text.
*/
var $_del_suffix = '</del>';
/**
* Header for each change block.
*/
var $_block_header = '';
/**
* What are we currently splitting on? Used to recurse to show word-level
* changes.
*/
var $_split_level = 'lines';
function _blockHeader($xbeg, $xlen, $ybeg, $ylen)
{
return $this->_block_header;
}
function _startBlock($header)
{
return $header;
}
function _lines($lines, $prefix = ' ', $encode = true)
{
if ($encode) {
array_walk($lines, array(&$this, '_encode'));
}
if ($this->_split_level == 'words') {
return implode('', $lines);
} else {
return implode("\n", $lines) . "\n";
}
}
function _added($lines)
{
array_walk($lines, array(&$this, '_encode'));
$lines[0] = $this->_ins_prefix . $lines[0];
$lines[count($lines) - 1] .= $this->_ins_suffix;
return $this->_lines($lines, ' ', false);
}
function _deleted($lines, $words = false)
{
array_walk($lines, array(&$this, '_encode'));
$lines[0] = $this->_del_prefix . $lines[0];
$lines[count($lines) - 1] .= $this->_del_suffix;
return $this->_lines($lines, ' ', false);
}
function _changed($orig, $final)
{
/* If we've already split on words, don't try to do so again - just
* display. */
if ($this->_split_level == 'words') {
$prefix = '';
while ($orig[0] !== false && $final[0] !== false &&
substr($orig[0], 0, 1) == ' ' &&
substr($final[0], 0, 1) == ' ') {
$prefix .= substr($orig[0], 0, 1);
$orig[0] = substr($orig[0], 1);
$final[0] = substr($final[0], 1);
}
return $prefix . $this->_deleted($orig) . $this->_added($final);
}
$text1 = implode("\n", $orig);
$text2 = implode("\n", $final);
/* Non-printing newline marker. */
$nl = "\0";
/* We want to split on word boundaries, but we need to
* preserve whitespace as well. Therefore we split on words,
* but include all blocks of whitespace in the wordlist. */
$diff = new Text_Diff($this->_splitOnWords($text1, $nl),
$this->_splitOnWords($text2, $nl));
/* Get the diff in inline format. */
$renderer = new Text_Diff_Renderer_inline(array_merge($this->getParams(),
array('split_level' => 'words')));
/* Run the diff and get the output. */
return str_replace($nl, "\n", $renderer->render($diff)) . "\n";
}
function _splitOnWords($string, $newlineEscape = "\n")
{
// Ignore \0; otherwise the while loop will never finish.
$string = str_replace("\0", '', $string);
$words = array();
$length = strlen($string);
$pos = 0;
while ($pos < $length) {
// Eat a word with any preceding whitespace.
$spaces = strspn(substr($string, $pos), " \n");
$nextpos = strcspn(substr($string, $pos + $spaces), " \n");
$words[] = str_replace("\n", $newlineEscape, substr($string, $pos, $spaces + $nextpos));
$pos += $spaces + $nextpos;
}
return $words;
}
function _encode(&$string)
{
$string = htmlspecialchars($string);
}
}

View File

@ -178,6 +178,7 @@ add_action('admin_print_scripts', 'wp_print_scripts', 20);
add_action('init', 'smilies_init', 5);
add_action( 'plugins_loaded', 'wp_maybe_load_widgets', 0 );
add_action( 'shutdown', 'wp_ob_end_flush_all', 1);
add_action( 'pre_post_update', 'wp_save_revision' );
add_action('publish_post', '_publish_post_hook', 5, 1);
add_action('future_post', '_future_post_hook', 5, 2);
add_action('future_page', '_future_post_hook', 5, 2);

View File

@ -442,10 +442,15 @@ function get_search_comments_feed_link($search_query = '', $feed = '') {
return $link;
}
function get_edit_post_link( $id = 0 ) {
function get_edit_post_link( $id = 0, $context = 'display' ) {
if ( !$post = &get_post( $id ) )
return;
if ( 'display' == $context )
$action = 'action=edit&amp;';
else
$action = 'action=edit&';
switch ( $post->post_type ) :
case 'page' :
if ( !current_user_can( 'edit_page', $post->ID ) )
@ -459,6 +464,13 @@ function get_edit_post_link( $id = 0 ) {
$file = 'media';
$var = 'attachment_id';
break;
case 'revision' :
if ( !current_user_can( 'edit_post', $post->ID ) )
return;
$file = 'revision';
$var = 'revision';
$action = '';
break;
default :
if ( !current_user_can( 'edit_post', $post->ID ) )
return;
@ -467,7 +479,7 @@ function get_edit_post_link( $id = 0 ) {
break;
endswitch;
return apply_filters( 'get_edit_post_link', get_bloginfo( 'wpurl' ) . "/wp-admin/$file.php?action=edit&amp;$var=$post->ID", $post->ID );
return apply_filters( 'get_edit_post_link', get_bloginfo( 'wpurl' ) . "/wp-admin/$file.php?{$action}$var=$post->ID", $post->ID );
}
function edit_post_link( $link = 'Edit This', $before = '', $after = '' ) {

View File

@ -1350,4 +1350,68 @@ function wp_login($username, $password, $deprecated = '') {
}
endif;
if ( !function_exists( 'wp_text_diff' ) ) :
/**
* wp_text_diff() - compares two strings and outputs a human readable HTML representation of their difference
*
* Basically a wrapper for man diff(1)
*
* Must accept an optional third parameter, $args @see wp_parse_args()
* (string) title: optional. If present, titles the diff in a manner compatible with the output
*
* Must return the empty string if the two compared strings are found to be equivalent according to whatever metric
*
* @since 2.6
* @uses Text_Diff
* @uses WP_Text_Diff_Renderer_Table
*
* @param string $left_string "old" (left) version of string
* @param string $right_string "new" (right) version of string
* @param string|array $args @see wp_parse_args()
* @return string human readable HTML of string differences. Empty string if strings are equivalent
*/
function wp_text_diff( $left_string, $right_string, $args = null ) {
$defaults = array( 'title' => '' );
$args = wp_parse_args( $args, $defaults );
// PEAR Text_Diff is lame; it includes things from include_path rather than it's own path.
// Not sure of the ramifications of disttributing modified code.
ini_set('include_path', '.' . PATH_SEPARATOR . ABSPATH . WPINC );
if ( !class_exists( 'WP_Text_Diff_Renderer_Table' ) )
require( ABSPATH . WPINC . '/wp-diff.php' );
// Normalize whitespace
$left_string = trim($left_string);
$right_string = trim($right_string);
$left_string = str_replace("\r", "\n", $left_string);
$right_string = str_replace("\r", "\n", $right_string);
$left_string = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $left_string );
$right_string = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $right_string );
$left_lines = split("\n", $left_string);
$right_lines = split("\n", $right_string);
$text_diff = new Text_Diff($left_lines, $right_lines);
$renderer = new WP_Text_Diff_Renderer_Table();
$diff = $renderer->render($text_diff);
ini_restore('include_path');
if ( !$diff )
return '';
$r = "<table class='diff'>\n";
$r .= "<col class='ltype' /><col class='content' /><col class='ltype' /><col class='content' />";
if ( $args['title'] )
$r .= "<thead><tr><th colspan='4'>$args[title]</th></tr></thead>\n";
$r .= "<tbody>\n$diff\n</tbody>\n";
$r .= "</table>";
return $r;
}
endif;
?>

View File

@ -564,4 +564,136 @@ function is_page_template($template = '') {
return false;
}
?>
/**
* wp_post_revision_time() - returns formatted datetimestamp of a revision
*
* @package WordPress
* @subpackage Post Revisions
* @since 2.6
*
* @uses wp_get_revision()
* @uses date_i18n()
*
* @param int|object $revision revision ID or revision object
* @return string i18n formatted datetimestamp or localized 'Corrent Revision'
*/
function wp_post_revision_time( $revision ) {
if ( !$revision = wp_get_revision( $revision ) ) {
if ( $revision = get_post( $revision ) )
return __( 'Current Revision' );
return $revision;
}
$datef = _c( 'j F, Y @ G:i|revision date format');
return date_i18n( $datef, strtotime( $revision->post_date_gmt . ' +0000' ) );
}
/**
* wp_list_post_revisions() - echoes list of a post's revisions
*
* Can output either a UL with edit links or a TABLE with diff interface, and restore action links
*
* Second argument controls parameters:
* (bool) parent : include the parent (the "Current Revision") in the list
* (string) format : 'list' or 'form-table'. 'list' outputs UL, 'form-table' outputs TABLE with UI
* (int) right : what revision is currently being viewed - used in form-table format
* (int) left : what revision is currently being diffed against right - used in form-table format
*
* @package WordPress
* @subpackage Post Revisions
* @since 2.6
*
* @uses wp_get_post_revisions()
* @uses wp_post_revision_time()
* @uses get_edit_post_link()
* @uses get_author_name()
*
* @param int|object $post_id post ID or post object
* @param string|array $args see description @see wp_parse_args()
*/
function wp_list_post_revisions( $post_id = 0, $args = null ) { // TODO? split into two functions (list, form-table) ?
if ( !$post = get_post( $post_id ) )
return;
if ( !$revisions = wp_get_post_revisions( $post->ID ) )
return;
$defaults = array( 'parent' => false, 'right' => false, 'left' => false, 'format' => 'list' );
extract( wp_parse_args( $args, $defaults ), EXTR_SKIP );
$titlef = _c( '%1$s by %2$s|post revision 1:datetime, 2:name' );
if ( $parent )
array_unshift( $revisions, $post );
$rows = '';
$class = false;
foreach ( $revisions as $revision ) {
$date = wp_post_revision_time( $revision );
if ( $link = get_edit_post_link( $revision->ID ) )
$date = "<a href='$link'>$date</a>";
$name = get_author_name( $revision->post_author );
if ( 'form-table' == $format ) {
if ( $left )
$old_checked = $left == $revision->ID ? ' checked="checked"' : '';
else
$old_checked = $new_checked ? ' checked="checked"' : '';
$new_checked = $right == $revision->ID ? ' checked="checked"' : '';
$class = $class ? '' : " class='alternate'";
if ( $post->ID != $revision->ID && current_user_can( 'edit_post', $post->ID ) )
$actions = '<a href="' . wp_nonce_url( add_query_arg( array( 'revision' => $revision->ID, 'diff' => false, 'restore' => 'restore' ) ), "restore-post_$post->ID|$revision->ID" ) . '">' . __( 'Restore' ) . '</a>';
else
$actions = '';
$rows .= "<tr$class>\n";
$rows .= "\t<th style='white-space: nowrap' scope='row'><input type='radio' name='diff' value='$revision->ID'$old_checked /><input type='radio' name='revision' value='$revision->ID'$new_checked />\n";
$rows .= "\t<td>$date</td>\n";
$rows .= "\t<td>$name</td>\n";
$rows .= "\t<td class='action-links'>$actions</td>\n";
$rows .= "</tr>\n";
} else {
$rows .= "\t<li>" . sprintf( $titlef, $date, $name ). "</li>\n";
}
}
if ( 'form-table' == $format ) : ?>
<form action="revision.php" method="get">
<div class="tablenav">
<div class="alignleft">
<input type="submit" class="button-secondary" value="<?php _e( 'Compare Revisions' ); ?>" />
</div>
</div>
<br class="clear" />
<table class="widefat post-revisions">
<col />
<col style="width: 33%" />
<col style="width: 33%" />
<col style="width: 33%" />
<thead>
<th scope="col"></th>
<th scope="col"><?php _e( 'Date Created' ); ?></th>
<th scope="col"><?php _e( 'Author' ); ?></th>
<th scope="col" class="action-links"><?php _e( 'Actions' ); ?></th>
</thead>
<tbody>
<?php echo $rows; ?>
</tbody>
</table>
<?php
else :
echo "<ul class='post-revisions'>\n";
echo $rows;
echo "</ul>";
endif;
}

View File

@ -2990,4 +2990,232 @@ function _get_post_ancestors(&$_post) {
}
}
/* Post Revisions */
/**
* _wp_revision_fields() - determines which fields of posts are to be saved in revisions
*
* Does two things. If passed a postn *array*, it will return a post array ready to be
* insterted into the posts table as a post revision.
* Otherwise, returns an array whose keys are the post fields to be saved post revisions.
*
* @package WordPress
* @subpackage Post Revisions
* @since 2.6
*
* @param array $post optional a post array to be processed for insertion as a post revision
* @return array post array ready to be inserted as a post revision or array of fields that can be versioned
*/
function _wp_revision_fields( $post = null ) {
static $fields = false;
if ( !$fields ) {
// Allow these to be versioned
$fields = array(
'post_title' => __( 'Title' ),
'post_author' => __( 'Author' ),
'post_content' => __( 'Content' ),
'post_excerpt' => __( 'Excerpt' ),
);
// WP uses these internally either in versioning or elsewhere - they cannot be versioned
foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count' ) as $protect )
unset( $fields[$protect] );
}
if ( !is_array($post) )
return $fields;
$return = array();
foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field )
$return[$field] = $post[$field];
$return['post_parent'] = $post['ID'];
$return['post_status'] = 'inherit';
$return['post_type'] = 'revision';
$return['post_name'] = "$post[ID]-revision";
$return['post_date'] = $post['post_modified'];
$return['post_date_gmt'] = $post['post_modified_gmt'];
return $return;
}
/**
* wp_save_revision() - Saves an already existing post as a post revision. Typically used immediately prior to post updates.
*
* @package WordPress
* @subpackage Post Revisions
* @since 2.6
*
* @uses _wp_put_revision()
*
* @param int $post_id The ID of the post to save as a revision
* @return mixed null or 0 if error, new revision ID if success
*/
function wp_save_revision( $post_id ) {
// TODO: rework autosave to use special type of post revision
if ( @constant( 'DOING_AUTOSAVE' ) )
return;
if ( !$post = get_post( $post_id, ARRAY_A ) )
return;
// TODO: open this up for pages also
if ( 'post' != $post->post_type )
retun;
return _wp_put_revision( $post );
}
/**
* _wp_put_revision() - Inserts post data into the posts table as a post revision
*
* @package WordPress
* @subpackage Post Revisions
* @since 2.6
*
* @uses wp_insert_post()
*
* @param int|object|array $post post ID, post object OR post array
* @return mixed null or 0 if error, new revision ID if success
*/
function _wp_put_revision( $post = null ) {
if ( is_object($post) )
$post = get_object_vars( $post );
elseif ( !is_array($post) )
$post = get_post($post, ARRAY_A);
if ( !$post || empty($post['ID']) )
return;
if ( isset($post['post_type']) && 'revision' == $post_post['type'] )
return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
$post = _wp_revision_fields( $post );
if ( $revision_id = wp_insert_post( $post ) )
do_action( '_wp_put_revision', $revision_id );
return $revision_id;
}
/**
* wp_get_revision() - Gets a post revision
*
* @package WordPress
* @subpackage Post Revisions
* @since 2.6
*
* @uses get_post()
*
* @param int|object $post post ID or post object
* @param $output optional OBJECT, ARRAY_A, or ARRAY_N
* @param string $filter optional sanitation filter. @see sanitize_post()
* @return mixed null if error or post object if success
*/
function &wp_get_revision(&$post, $output = OBJECT, $filter = 'raw') {
$null = null;
if ( !$revision = get_post( $post, OBJECT, $filter ) )
return $revision;
if ( 'revision' !== $revision->post_type )
return $null;
if ( $output == OBJECT ) {
return $revision;
} elseif ( $output == ARRAY_A ) {
$_revision = get_object_vars($revision);
return $_revision;
} elseif ( $output == ARRAY_N ) {
$_revision = array_values(get_object_vars($revision));
return $_revision;
}
return $revision;
}
/**
* wp_restore_revision() - Restores a post to the specified revision
*
* Can restore a past using all fields of the post revision, or only selected fields.
*
* @package WordPress
* @subpackage Post Revisions
* @since 2.6
*
* @uses wp_get_revision()
* @uses wp_update_post()
*
* @param int|object $revision_id revision ID or revision object
* @param array $fields optional What fields to restore from. Defaults to all.
* @return mixed null if error, false if no fields to restore, (int) post ID if success
*/
function wp_restore_revision( $revision_id, $fields = null ) {
if ( !$revision = wp_get_revision( $revision_id, ARRAY_A ) )
return $revision;
if ( !is_array( $fields ) )
$fields = array_keys( _wp_revision_fields() );
$update = array();
foreach( array_intersect( array_keys( $revision ), $fields ) as $field )
$update[$field] = $revision[$field];
if ( !$update )
return false;
$update['ID'] = $revision['post_parent'];
if ( $post_id = wp_update_post( $update ) )
do_action( 'wp_restore_revision', $post_id, $revision['ID'] );
return $post_id;
}
/**
* wp_delete_revision() - Deletes a revision.
*
* Deletes the row from the posts table corresponding to the specified revision
*
* @package WordPress
* @subpackage Post Revisions
* @since 2.6
*
* @uses wp_get_revision()
* @uses wp_delete_post()
*
* @param int|object $revision_id revision ID or revision object
* @param array $fields optional What fields to restore from. Defaults to all.
* @return mixed null if error, false if no fields to restore, (int) post ID if success
*/
function wp_delete_revision( $revision_id ) {
if ( !$revision = wp_get_revision( $revision_id ) )
return $revision;
if ( $delete = wp_delete_post( $revision->ID ) )
do_action( 'wp_delete_revision', $revision->ID, $revision );
return $delete;
}
/**
* wp_get_post_revisions() - Returns all revisions of specified post
*
* @package WordPress
* @subpackage Post Revisions
* @since 2.6
*
* @uses get_children()
*
* @param int|object $post_id post ID or post object
* @return array empty if no revisions
*/
function wp_get_post_revisions( $post_id = 0 ) {
if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) )
return array();
if ( !$revisions = get_children( array( 'post_parent' => $post->ID, 'post_type' => 'revision' ) ) )
return array();
return $revisions;
}
?>

318
wp-includes/wp-diff.php Normal file
View File

@ -0,0 +1,318 @@
<?php
if ( !class_exists( 'Text_Diff' ) ) {
require( 'Text/Diff.php' );
require( 'Text/Diff/Renderer.php' );
require( 'Text/Diff/Renderer/inline.php' );
}
/* Descendent of a bastard child of piece of an old MediaWiki Diff Formatter
*
* Basically all that remains is the table structure and some method names.
*/
class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
var $_leading_context_lines = 10000;
var $_trailing_context_lines = 10000;
var $_diff_threshold = 0.6;
var $inline_diff_renderer = 'WP_Text_Diff_Renderer_inline';
function Text_Diff_Renderer_Table( $params = array() ) {
$parent = get_parent_class($this);
$this->$parent( $params );
}
function _startBlock( $header ) {
return '';
}
function _lines( $lines, $prefix=' ' ) {
}
// HTML-escape parameter before calling this
function addedLine( $line ) {
return "<td>+</td><td class='diff-addedline'>{$line}</td>";
}
// HTML-escape parameter before calling this
function deletedLine( $line ) {
return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
}
// HTML-escape parameter before calling this
function contextLine( $line ) {
return "<td> </td><td class='diff-context'>{$line}</td>";
}
function emptyLine() {
return '<td colspan="2">&nbsp;</td>';
}
function _added( $lines, $encode = true ) {
$r = '';
foreach ($lines as $line) {
if ( $encode )
$line = htmlspecialchars( $line );
$r .= '<tr>' . $this->emptyLine() . $this->addedLine( $line ) . "</tr>\n";
}
return $r;
}
function _deleted( $lines, $encode = true ) {
$r = '';
foreach ($lines as $line) {
if ( $encode )
$line = htmlspecialchars( $line );
$r .= '<tr>' . $this->deletedLine( $line ) . $this->emptyLine() . "</tr>\n";
}
return $r;
}
function _context( $lines, $encode = true ) {
$r = '';
foreach ($lines as $line) {
if ( $encode )
$line = htmlspecialchars( $line );
$r .= '<tr>' .
$this->contextLine( $line ) . $this->contextLine( $line ) . "</tr>\n";
}
return $r;
}
// Process changed lines to do word-by-word diffs for extra highlighting (TRAC style)
// sometimes these lines can actually be deleted or added rows - we do additional processing
// to figure that out
function _changed( $orig, $final ) {
$r = '';
// Does the aforementioned additional processing
// *_matches tell what rows are "the same" in orig and final. Those pairs will be diffed to get word changes
// match is numeric: an index in other column
// match is 'X': no match. It is a new row
// *_rows are column vectors for the orig column and the final column.
// row >= 0: an indix of the $orig or $final array
// row < 0: a blank row for that column
list($orig_matches, $final_matches, $orig_rows, $final_rows) = $this->interleave_changed_lines( $orig, $final );
// These will hold the word changes as determined by an inline diff
$orig_diffs = array();
$final_diffs = array();
// Compute word diffs for each matched pair using the inline diff
foreach ( $orig_matches as $o => $f ) {
if ( is_numeric($o) && is_numeric($f) ) {
$text_diff = new Text_Diff( 'auto', array( array($orig[$o]), array($final[$f]) ) );
$renderer = new $this->inline_diff_renderer;
$diff = $renderer->render( $text_diff );
// If they're too different, don't include any <ins> or <dels>
if ( $diff_count = preg_match_all( '!(<ins>.*?</ins>|<del>.*?</del>)!', $diff, $diff_matches ) ) {
// length of all text between <ins> or <del>
$stripped_matches = strlen(strip_tags( join(' ', $diff_matches[0]) ));
// since we count lengith of text between <ins> or <del> (instead of picking just one),
// we double the length of chars not in those tags.
$stripped_diff = strlen(strip_tags( $diff )) * 2 - $stripped_matches;
$diff_ratio = $stripped_matches / $stripped_diff;
if ( $diff_ratio > $this->_diff_threshold )
continue; // Too different. Don't save diffs.
}
// Un-inline the diffs by removing del or ins
$orig_diffs[$o] = preg_replace( '|<ins>.*?</ins>|', '', $diff );
$final_diffs[$f] = preg_replace( '|<del>.*?</del>|', '', $diff );
}
}
foreach ( array_keys($orig_rows) as $row ) {
// Both columns have blanks. Ignore them.
if ( $orig_rows[$row] < 0 && $final_rows[$row] < 0 )
continue;
// If we have a word based diff, use it. Otherwise, use the normal line.
$orig_line = isset($orig_diffs[$orig_rows[$row]])
? $orig_diffs[$orig_rows[$row]]
: htmlspecialchars($orig[$orig_rows[$row]]);
$final_line = isset($final_diffs[$final_rows[$row]])
? $final_diffs[$final_rows[$row]]
: htmlspecialchars($final[$final_rows[$row]]);
if ( $orig_rows[$row] < 0 ) { // Orig is blank. This is really an added row.
$r .= $this->_added( array($final_line), false );
} elseif ( $final_rows[$row] < 0 ) { // Final is blank. This is really a deleted row.
$r .= $this->_deleted( array($orig_line), false );
} else { // A true changed row.
$r .= '<tr>' . $this->deletedLine( $orig_line ) . $this->addedLine( $final_line ) . "</tr>\n";
}
}
return $r;
}
// Takes changed blocks and matches which rows in orig turned into which rows in final.
// Returns
// *_matches ( which rows match with which )
// *_rows ( order of rows in each column interleaved with blank rows as necessary )
function interleave_changed_lines( $orig, $final ) {
// Contains all pairwise string comparisons. Keys are such that this need only be a one dimensional array.
$matches = array();
foreach ( array_keys($orig) as $o ) {
foreach ( array_keys($final) as $f ) {
$matches["$o,$f"] = $this->compute_string_distance( $orig[$o], $final[$f] );
}
}
asort($matches); // Order by string distance.
$orig_matches = array();
$final_matches = array();
foreach ( $matches as $keys => $difference ) {
list($o, $f) = explode(',', $keys);
$o = (int) $o;
$f = (int) $f;
// Already have better matches for these guys
if ( isset($orig_matches[$o]) && isset($final_matches[$f]) )
continue;
// First match for these guys. Must be best match
if ( !isset($orig_matches[$o]) && !isset($final_matches[$f]) ) {
$orig_matches[$o] = $f;
$final_matches[$f] = $o;
continue;
}
// Best match of this final is already taken? Must mean this final is a new row.
if ( isset($orig_matches[$o]) )
$final_matches[$f] = 'x';
// Best match of this orig is already taken? Must mean this orig is a deleted row.
elseif ( isset($final_matches[$f]) )
$orig_matches[$o] = 'x';
}
// We read the text in this order
ksort($orig_matches);
ksort($final_matches);
// Stores rows and blanks for each column.
$orig_rows = $orig_rows_copy = array_keys($orig_matches);
$final_rows = array_keys($final_matches);
// Interleaves rows with blanks to keep matches aligned.
// We may end up with some extraneous blank rows, but we'll just ignore them later.
foreach ( $orig_rows_copy as $orig_row ) {
$final_pos = array_search($orig_matches[$orig_row], $final_rows, true);
$orig_pos = (int) array_search($orig_row, $orig_rows, true);
if ( false === $final_pos ) { // This orig is paired with a blank final.
array_splice( $final_rows, $orig_pos, 0, -1 );
} elseif ( $final_pos < $orig_pos ) { // This orig's match is up a ways. Pad final with blank rows.
$diff_pos = $final_pos - $orig_pos;
while ( $diff_pos < 0 )
array_splice( $final_rows, $orig_pos, 0, $diff_pos++ );
} elseif ( $final_pos > $orig_pos ) { // This orig's match is down a ways. Pad orig with blank rows.
$diff_pos = $orig_pos - $final_pos;
while ( $diff_pos < 0 )
array_splice( $orig_rows, $orig_pos, 0, $diff_pos++ );
}
}
// Pad the ends with blank rows if the columns aren't the same length
$diff_count = count($orig_rows) - count($final_rows);
if ( $diff_count < 0 ) {
while ( $diff_count < 0 )
array_push($orig_rows, $diff_count++);
} elseif ( $diff_count > 0 ) {
$diff_count = -1 * $diff_count;
while ( $diff_count < 0 )
array_push($final_rows, $diff_count++);
}
return array($orig_matches, $final_matches, $orig_rows, $final_rows);
/*
// Debug
echo "\n\n\n\n\n";
echo "-- DEBUG Matches: Orig -> Final --";
foreach ( $orig_matches as $o => $f ) {
echo "\n\n\n\n\n";
echo "ORIG: $o, FINAL: $f\n";
var_dump($orig[$o],$final[$f]);
}
echo "\n\n\n\n\n";
echo "-- DEBUG Matches: Final -> Orig --";
foreach ( $final_matches as $f => $o ) {
echo "\n\n\n\n\n";
echo "FINAL: $f, ORIG: $o\n";
var_dump($final[$f],$orig[$o]);
}
echo "\n\n\n\n\n";
echo "-- DEBUG Rows: Orig -- Final --";
echo "\n\n\n\n\n";
foreach ( $orig_rows as $row => $o ) {
if ( $o < 0 )
$o = 'X';
$f = $final_rows[$row];
if ( $f < 0 )
$f = 'X';
echo "$o -- $f\n";
}
echo "\n\n\n\n\n";
echo "-- END DEBUG --";
echo "\n\n\n\n\n";
return array($orig_matches, $final_matches, $orig_rows, $final_rows);
*/
}
// Computes a number that is intended to reflect the "distance" between two strings.
function compute_string_distance( $string1, $string2 ) {
// Vectors containing character frequency for all chars in each string
$chars1 = count_chars($string1);
$chars2 = count_chars($string2);
// L1-norm of difference vector.
$difference = array_sum( array_map( array(&$this, 'difference'), $chars1, $chars2 ) );
// $string1 has zero length? Odd. Give huge penalty by not dividing.
if ( !$string1 )
return $difference;
// Return distance per charcter (of string1)
return $difference / strlen($string1);
}
function difference( $a, $b ) {
return abs( $a - $b );
}
}
// Better word splitting than the PEAR package provides
class WP_Text_Diff_Renderer_inline extends Text_Diff_Renderer_inline {
function _splitOnWords($string, $newlineEscape = "\n") {
$string = str_replace("\0", '', $string);
$words = preg_split( '/([^\w])/', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
$words = str_replace( "\n", $newlineEscape, $words );
return $words;
}
}
?>