b2evolution PHP Cross Reference Blogging Systems

Source: /inc/_core/model/_diff.class.php - 1376 lines - 34645 bytes - Summary - Text - Print

Description: A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3) Copyright © 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org> You may copy this code freely under the conditions of the GPL.

   1  <?php
   2  /**
   3   * A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
   4   *
   5   * Copyright © 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
   6   * You may copy this code freely under the conditions of the GPL.
   7   *
   8   * @file
   9   * @ingroup DifferenceEngine
  10   * @defgroup DifferenceEngine DifferenceEngine
  11   */
  12  if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' );
  13  
  14  /**
  15   * @todo document
  16   * @private
  17   * @ingroup DifferenceEngine
  18   */
  19  class _DiffOp {
  20      var $type;
  21      var $orig;
  22      var $closing;
  23  
  24  	function reverse() {
  25          trigger_error( 'pure virtual', E_USER_ERROR );
  26      }
  27  
  28  	function norig() {
  29          return $this->orig ? sizeof( $this->orig ) : 0;
  30      }
  31  
  32  	function nclosing() {
  33          return $this->closing ? sizeof( $this->closing ) : 0;
  34      }
  35  }
  36  
  37  /**
  38   * @todo document
  39   * @private
  40   * @ingroup DifferenceEngine
  41   */
  42  class _DiffOp_Copy extends _DiffOp {
  43      var $type = 'copy';
  44  
  45  	function __construct( $orig, $closing = false ) {
  46          if ( !is_array( $closing ) ) {
  47              $closing = $orig;
  48          }
  49          $this->orig = $orig;
  50          $this->closing = $closing;
  51      }
  52  
  53  	function reverse() {
  54          return new _DiffOp_Copy( $this->closing, $this->orig );
  55      }
  56  }
  57  
  58  /**
  59   * @todo document
  60   * @private
  61   * @ingroup DifferenceEngine
  62   */
  63  class _DiffOp_Delete extends _DiffOp {
  64      var $type = 'delete';
  65  
  66  	function __construct( $lines ) {
  67          $this->orig = $lines;
  68          $this->closing = false;
  69      }
  70  
  71  	function reverse() {
  72          return new _DiffOp_Add( $this->orig );
  73      }
  74  }
  75  
  76  /**
  77   * @todo document
  78   * @private
  79   * @ingroup DifferenceEngine
  80   */
  81  class _DiffOp_Add extends _DiffOp {
  82      var $type = 'add';
  83  
  84  	function __construct( $lines ) {
  85          $this->closing = $lines;
  86          $this->orig = false;
  87      }
  88  
  89  	function reverse() {
  90          return new _DiffOp_Delete( $this->closing );
  91      }
  92  }
  93  
  94  /**
  95   * @todo document
  96   * @private
  97   * @ingroup DifferenceEngine
  98   */
  99  class _DiffOp_Change extends _DiffOp {
 100      var $type = 'change';
 101  
 102  	function __construct( $orig, $closing ) {
 103          $this->orig = $orig;
 104          $this->closing = $closing;
 105      }
 106  
 107  	function reverse() {
 108          return new _DiffOp_Change( $this->closing, $this->orig );
 109      }
 110  }
 111  
 112  /**
 113   * Class used internally by Diff to actually compute the diffs.
 114   *
 115   * The algorithm used here is mostly lifted from the perl module
 116   * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
 117   *     http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
 118   *
 119   * More ideas are taken from:
 120   *     http://www.ics.uci.edu/~eppstein/161/960229.html
 121   *
 122   * Some ideas are (and a bit of code) are from from analyze.c, from GNU
 123   * diffutils-2.7, which can be found at:
 124   *     ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
 125   *
 126   * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
 127   * are my own.
 128   *
 129   * Line length limits for robustness added by Tim Starling, 2005-08-31
 130   * Alternative implementation added by Guy Van den Broeck, 2008-07-30
 131   *
 132   * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
 133   * @private
 134   * @ingroup DifferenceEngine
 135   */
 136  class _DiffEngine {
 137  
 138      const MAX_XREF_LENGTH =  10000;
 139  
 140      protected $xchanged, $ychanged;
 141  
 142      protected $xv = array(), $yv = array();
 143      protected $xind = array(), $yind = array();
 144  
 145      protected $seq = array(), $in_seq = array();
 146  
 147      protected $lcs = 0;
 148  
 149  	function diff ( $from_lines, $to_lines ) {
 150  
 151          // Diff and store locally
 152          $this->diff_local( $from_lines, $to_lines );
 153  
 154          // Merge edits when possible
 155          $this->_shift_boundaries( $from_lines, $this->xchanged, $this->ychanged );
 156          $this->_shift_boundaries( $to_lines, $this->ychanged, $this->xchanged );
 157  
 158          // Compute the edit operations.
 159          $n_from = sizeof( $from_lines );
 160          $n_to = sizeof( $to_lines );
 161  
 162          $edits = array();
 163          $xi = $yi = 0;
 164          while ( $xi < $n_from || $yi < $n_to ) {
 165              assert( $yi < $n_to || $this->xchanged[$xi] );
 166              assert( $xi < $n_from || $this->ychanged[$yi] );
 167  
 168              // Skip matching "snake".
 169              $copy = array();
 170              while ( $xi < $n_from && $yi < $n_to
 171              && !$this->xchanged[$xi] && !$this->ychanged[$yi] ) {
 172                  $copy[] = $from_lines[$xi++];
 173                  ++$yi;
 174              }
 175              if ( $copy ) {
 176                  $edits[] = new _DiffOp_Copy( $copy );
 177              }
 178  
 179              // Find deletes & adds.
 180              $delete = array();
 181              while ( $xi < $n_from && $this->xchanged[$xi] ) {
 182                  $delete[] = $from_lines[$xi++];
 183              }
 184  
 185              $add = array();
 186              while ( $yi < $n_to && $this->ychanged[$yi] )  {
 187                  $add[] = $to_lines[$yi++];
 188              }
 189  
 190              if ( $delete && $add ) {
 191                  $edits[] = new _DiffOp_Change( $delete, $add );
 192              } elseif ( $delete ) {
 193                  $edits[] = new _DiffOp_Delete( $delete );
 194              } elseif ( $add ) {
 195                  $edits[] = new _DiffOp_Add( $add );
 196              }
 197          }
 198          return $edits;
 199      }
 200  
 201  	function diff_local ( $from_lines, $to_lines ) {
 202          global $wgExternalDiffEngine;
 203  
 204          if ( $wgExternalDiffEngine == 'wikidiff3' ) {
 205              // wikidiff3
 206              $wikidiff3 = new WikiDiff3();
 207              $wikidiff3->diff( $from_lines, $to_lines );
 208              $this->xchanged = $wikidiff3->removed;
 209              $this->ychanged = $wikidiff3->added;
 210              unset( $wikidiff3 );
 211          } else {
 212              // old diff
 213              $n_from = sizeof( $from_lines );
 214              $n_to = sizeof( $to_lines );
 215              $this->xchanged = $this->ychanged = array();
 216              $this->xv = $this->yv = array();
 217              $this->xind = $this->yind = array();
 218              unset( $this->seq );
 219              unset( $this->in_seq );
 220              unset( $this->lcs );
 221  
 222              // Skip leading common lines.
 223              for ( $skip = 0; $skip < $n_from && $skip < $n_to; $skip++ ) {
 224                  if ( $from_lines[$skip] !== $to_lines[$skip] ) {
 225                      break;
 226                  }
 227                  $this->xchanged[$skip] = $this->ychanged[$skip] = false;
 228              }
 229              // Skip trailing common lines.
 230              $xi = $n_from; $yi = $n_to;
 231              for ( $endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++ ) {
 232                  if ( $from_lines[$xi] !== $to_lines[$yi] ) {
 233                      break;
 234                  }
 235                  $this->xchanged[$xi] = $this->ychanged[$yi] = false;
 236              }
 237  
 238              // Ignore lines which do not exist in both files.
 239              for ( $xi = $skip; $xi < $n_from - $endskip; $xi++ ) {
 240                  $xhash[$this->_line_hash( $from_lines[$xi] )] = 1;
 241              }
 242  
 243              for ( $yi = $skip; $yi < $n_to - $endskip; $yi++ ) {
 244                  $line = $to_lines[$yi];
 245                  if ( ( $this->ychanged[$yi] = empty( $xhash[$this->_line_hash( $line )] ) ) ) {
 246                      continue;
 247                  }
 248                  $yhash[$this->_line_hash( $line )] = 1;
 249                  $this->yv[] = $line;
 250                  $this->yind[] = $yi;
 251              }
 252              for ( $xi = $skip; $xi < $n_from - $endskip; $xi++ ) {
 253                  $line = $from_lines[$xi];
 254                  if ( ( $this->xchanged[$xi] = empty( $yhash[$this->_line_hash( $line )] ) ) ) {
 255                      continue;
 256                  }
 257                  $this->xv[] = $line;
 258                  $this->xind[] = $xi;
 259              }
 260  
 261              // Find the LCS.
 262              $this->_compareseq( 0, sizeof( $this->xv ), 0, sizeof( $this->yv ) );
 263          }
 264      }
 265  
 266      /**
 267       * Returns the whole line if it's small enough, or the MD5 hash otherwise
 268       */
 269  	function _line_hash( $line ) {
 270          if ( strlen( $line ) > self::MAX_XREF_LENGTH ) {
 271              return md5( $line );
 272          } else {
 273              return $line;
 274          }
 275      }
 276  
 277      /**
 278       * Divide the Largest Common Subsequence (LCS) of the sequences
 279       * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
 280       * sized segments.
 281       *
 282       * Returns (LCS, PTS).    LCS is the length of the LCS. PTS is an
 283       * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
 284       * sub sequences.  The first sub-sequence is contained in [X0, X1),
 285       * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on.  Note
 286       * that (X0, Y0) == (XOFF, YOFF) and
 287       * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
 288       *
 289       * This function assumes that the first lines of the specified portions
 290       * of the two files do not match, and likewise that the last lines do not
 291       * match.  The caller must trim matching lines from the beginning and end
 292       * of the portions it is going to specify.
 293       */
 294  	function _diag( $xoff, $xlim, $yoff, $ylim, $nchunks ) {
 295          $flip = false;
 296  
 297          if ( $xlim - $xoff > $ylim - $yoff ) {
 298              // Things seems faster (I'm not sure I understand why)
 299              // when the shortest sequence in X.
 300              $flip = true;
 301              list( $xoff, $xlim, $yoff, $ylim ) = array( $yoff, $ylim, $xoff, $xlim );
 302          }
 303  
 304          if ( $flip ) {
 305              for ( $i = $ylim - 1; $i >= $yoff; $i-- ) {
 306                  $ymatches[$this->xv[$i]][] = $i;
 307              }
 308          } else {
 309              for ( $i = $ylim - 1; $i >= $yoff; $i-- ) {
 310                  $ymatches[$this->yv[$i]][] = $i;
 311              }
 312          }
 313  
 314          $this->lcs = 0;
 315          $this->seq[0] = $yoff - 1;
 316          $this->in_seq = array();
 317          $ymids[0] = array();
 318  
 319          $numer = $xlim - $xoff + $nchunks - 1;
 320          $x = $xoff;
 321          for ( $chunk = 0; $chunk < $nchunks; $chunk++ ) {
 322              if ( $chunk > 0 ) {
 323                  for ( $i = 0; $i <= $this->lcs; $i++ ) {
 324                      $ymids[$i][$chunk -1] = $this->seq[$i];
 325                  }
 326              }
 327  
 328              $x1 = $xoff + (int)( ( $numer + ( $xlim -$xoff ) * $chunk ) / $nchunks );
 329              for ( ; $x < $x1; $x++ ) {
 330                  $line = $flip ? $this->yv[$x] : $this->xv[$x];
 331                  if ( empty( $ymatches[$line] ) ) {
 332                      continue;
 333                  }
 334                  $matches = $ymatches[$line];
 335                  reset( $matches );
 336                  while ( list( , $y ) = each( $matches ) ) {
 337                      if ( empty( $this->in_seq[$y] ) ) {
 338                          $k = $this->_lcs_pos( $y );
 339                          assert( $k > 0 );
 340                          $ymids[$k] = $ymids[$k -1];
 341                          break;
 342                      }
 343                  }
 344                  while ( list ( , $y ) = each( $matches ) ) {
 345                      if ( $y > $this->seq[$k -1] ) {
 346                          assert( $y < $this->seq[$k] );
 347                          // Optimization: this is a common case:
 348                          //    next match is just replacing previous match.
 349                          $this->in_seq[$this->seq[$k]] = false;
 350                          $this->seq[$k] = $y;
 351                          $this->in_seq[$y] = 1;
 352                      } elseif ( empty( $this->in_seq[$y] ) ) {
 353                          $k = $this->_lcs_pos( $y );
 354                          assert( $k > 0 );
 355                          $ymids[$k] = $ymids[$k -1];
 356                      }
 357                  }
 358              }
 359          }
 360  
 361          $seps[] = $flip ? array( $yoff, $xoff ) : array( $xoff, $yoff );
 362          $ymid = $ymids[$this->lcs];
 363          for ( $n = 0; $n < $nchunks - 1; $n++ ) {
 364              $x1 = $xoff + (int)( ( $numer + ( $xlim - $xoff ) * $n ) / $nchunks );
 365              $y1 = $ymid[$n] + 1;
 366              $seps[] = $flip ? array( $y1, $x1 ) : array( $x1, $y1 );
 367          }
 368          $seps[] = $flip ? array( $ylim, $xlim ) : array( $xlim, $ylim );
 369  
 370          return array( $this->lcs, $seps );
 371      }
 372  
 373  	function _lcs_pos( $ypos ) {
 374          $end = $this->lcs;
 375          if ( $end == 0 || $ypos > $this->seq[$end] ) {
 376              $this->seq[++$this->lcs] = $ypos;
 377              $this->in_seq[$ypos] = 1;
 378              return $this->lcs;
 379          }
 380  
 381          $beg = 1;
 382          while ( $beg < $end ) {
 383              $mid = (int)( ( $beg + $end ) / 2 );
 384              if ( $ypos > $this->seq[$mid] ) {
 385                  $beg = $mid + 1;
 386              } else {
 387                  $end = $mid;
 388              }
 389          }
 390  
 391          assert( $ypos != $this->seq[$end] );
 392  
 393          $this->in_seq[$this->seq[$end]] = false;
 394          $this->seq[$end] = $ypos;
 395          $this->in_seq[$ypos] = 1;
 396          return $end;
 397      }
 398  
 399      /**
 400       * Find LCS of two sequences.
 401       *
 402       * The results are recorded in the vectors $this->{x,y}changed[], by
 403       * storing a 1 in the element for each line that is an insertion
 404       * or deletion (ie. is not in the LCS).
 405       *
 406       * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
 407       *
 408       * Note that XLIM, YLIM are exclusive bounds.
 409       * All line numbers are origin-0 and discarded lines are not counted.
 410       */
 411  	function _compareseq ( $xoff, $xlim, $yoff, $ylim ) {
 412          // Slide down the bottom initial diagonal.
 413          while ( $xoff < $xlim && $yoff < $ylim
 414          && $this->xv[$xoff] == $this->yv[$yoff] ) {
 415              ++$xoff;
 416              ++$yoff;
 417          }
 418  
 419          // Slide up the top initial diagonal.
 420          while ( $xlim > $xoff && $ylim > $yoff
 421          && $this->xv[$xlim - 1] == $this->yv[$ylim - 1] ) {
 422              --$xlim;
 423              --$ylim;
 424          }
 425  
 426          if ( $xoff == $xlim || $yoff == $ylim ) {
 427              $lcs = 0;
 428          } else {
 429              // This is ad hoc but seems to work well.
 430              // $nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
 431              // $nchunks = max(2,min(8,(int)$nchunks));
 432              $nchunks = min( 7, $xlim - $xoff, $ylim - $yoff ) + 1;
 433              list ( $lcs, $seps )
 434              = $this->_diag( $xoff, $xlim, $yoff, $ylim, $nchunks );
 435          }
 436  
 437          if ( $lcs == 0 ) {
 438              // X and Y sequences have no common subsequence:
 439              // mark all changed.
 440              while ( $yoff < $ylim ) {
 441                  $this->ychanged[$this->yind[$yoff++]] = 1;
 442              }
 443              while ( $xoff < $xlim ) {
 444                  $this->xchanged[$this->xind[$xoff++]] = 1;
 445              }
 446          } else {
 447              // Use the partitions to split this problem into subproblems.
 448              reset( $seps );
 449              $pt1 = $seps[0];
 450              while ( $pt2 = next( $seps ) ) {
 451                  $this->_compareseq ( $pt1[0], $pt2[0], $pt1[1], $pt2[1] );
 452                  $pt1 = $pt2;
 453              }
 454          }
 455      }
 456  
 457      /**
 458       * Adjust inserts/deletes of identical lines to join changes
 459       * as much as possible.
 460       *
 461       * We do something when a run of changed lines include a
 462       * line at one end and has an excluded, identical line at the other.
 463       * We are free to choose which identical line is included.
 464       * `compareseq' usually chooses the one at the beginning,
 465       * but usually it is cleaner to consider the following identical line
 466       * to be the "change".
 467       *
 468       * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
 469       */
 470  	function _shift_boundaries( $lines, &$changed, $other_changed ) {
 471          $i = 0;
 472          $j = 0;
 473  
 474          assert( 'sizeof($lines) == sizeof($changed)' );
 475          $len = sizeof( $lines );
 476          $other_len = sizeof( $other_changed );
 477  
 478          while ( 1 ) {
 479              /*
 480               * Scan forwards to find beginning of another run of changes.
 481               * Also keep track of the corresponding point in the other file.
 482               *
 483               * Throughout this code, $i and $j are adjusted together so that
 484               * the first $i elements of $changed and the first $j elements
 485               * of $other_changed both contain the same number of zeros
 486               * (unchanged lines).
 487               * Furthermore, $j is always kept so that $j == $other_len or
 488               * $other_changed[$j] == false.
 489               */
 490              while ( $j < $other_len && $other_changed[$j] ) {
 491                  $j++;
 492              }
 493  
 494              while ( $i < $len && ! $changed[$i] ) {
 495                  assert( '$j < $other_len && ! $other_changed[$j]' );
 496                  $i++; $j++;
 497                  while ( $j < $other_len && $other_changed[$j] )
 498                  $j++;
 499              }
 500  
 501              if ( $i == $len ) {
 502                  break;
 503              }
 504  
 505              $start = $i;
 506  
 507              // Find the end of this run of changes.
 508              while ( ++$i < $len && $changed[$i] ) {
 509                  continue;
 510              }
 511  
 512              do {
 513                  /*
 514                   * Record the length of this run of changes, so that
 515                   * we can later determine whether the run has grown.
 516                   */
 517                  $runlength = $i - $start;
 518  
 519                  /*
 520                   * Move the changed region back, so long as the
 521                   * previous unchanged line matches the last changed one.
 522                   * This merges with previous changed regions.
 523                   */
 524                  while ( $start > 0 && $lines[$start - 1] == $lines[$i - 1] ) {
 525                      $changed[--$start] = 1;
 526                      $changed[--$i] = false;
 527                      while ( $start > 0 && $changed[$start - 1] ) {
 528                          $start--;
 529                      }
 530                      assert( '$j > 0' );
 531                      while ( $other_changed[--$j] ) {
 532                          continue;
 533                      }
 534                      assert( '$j >= 0 && !$other_changed[$j]' );
 535                  }
 536  
 537                  /*
 538                   * Set CORRESPONDING to the end of the changed run, at the last
 539                   * point where it corresponds to a changed run in the other file.
 540                   * CORRESPONDING == LEN means no such point has been found.
 541                   */
 542                  $corresponding = $j < $other_len ? $i : $len;
 543  
 544                  /*
 545                   * Move the changed region forward, so long as the
 546                   * first changed line matches the following unchanged one.
 547                   * This merges with following changed regions.
 548                   * Do this second, so that if there are no merges,
 549                   * the changed region is moved forward as far as possible.
 550                   */
 551                  while ( $i < $len && $lines[$start] == $lines[$i] ) {
 552                      $changed[$start++] = false;
 553                      $changed[$i++] = 1;
 554                      while ( $i < $len && $changed[$i] ) {
 555                          $i++;
 556                      }
 557  
 558                      assert( '$j < $other_len && ! $other_changed[$j]' );
 559                      $j++;
 560                      if ( $j < $other_len && $other_changed[$j] ) {
 561                          $corresponding = $i;
 562                          while ( $j < $other_len && $other_changed[$j] ) {
 563                              $j++;
 564                          }
 565                      }
 566                  }
 567              } while ( $runlength != $i - $start );
 568  
 569              /*
 570               * If possible, move the fully-merged run of changes
 571               * back to a corresponding run in the other file.
 572               */
 573              while ( $corresponding < $i ) {
 574                  $changed[--$start] = 1;
 575                  $changed[--$i] = 0;
 576                  assert( '$j > 0' );
 577                  while ( $other_changed[--$j] ) {
 578                      continue;
 579                  }
 580                  assert( '$j >= 0 && !$other_changed[$j]' );
 581              }
 582          }
 583      }
 584  }
 585  
 586  /**
 587   * Class representing a 'diff' between two sequences of strings.
 588   * @todo document
 589   * @private
 590   * @ingroup DifferenceEngine
 591   */
 592  class Diff {
 593      var $edits;
 594  
 595      /**
 596       * Constructor.
 597       * Computes diff between sequences of strings.
 598       *
 599       * @param $from_lines array An array of strings.
 600       *          (Typically these are lines from a file.)
 601       * @param $to_lines array An array of strings.
 602       */
 603  	function __construct( $from_lines, $to_lines ) {
 604          $eng = new _DiffEngine;
 605          $this->edits = $eng->diff( $from_lines, $to_lines );
 606          // $this->_check($from_lines, $to_lines);
 607      }
 608  
 609      /**
 610       * Compute reversed Diff.
 611       *
 612       * SYNOPSIS:
 613       *
 614       *    $diff = new Diff($lines1, $lines2);
 615       *    $rev = $diff->reverse();
 616       * @return object A Diff object representing the inverse of the
 617       *                  original diff.
 618       */
 619  	function reverse() {
 620          $rev = $this;
 621          $rev->edits = array();
 622          foreach ( $this->edits as $edit ) {
 623              $rev->edits[] = $edit->reverse();
 624          }
 625          return $rev;
 626      }
 627  
 628      /**
 629       * Check for empty diff.
 630       *
 631       * @return bool True iff two sequences were identical.
 632       */
 633  	function isEmpty() {
 634          foreach ( $this->edits as $edit ) {
 635              if ( $edit->type != 'copy' ) {
 636                  return false;
 637              }
 638          }
 639          return true;
 640      }
 641  
 642      /**
 643       * Compute the length of the Longest Common Subsequence (LCS).
 644       *
 645       * This is mostly for diagnostic purposed.
 646       *
 647       * @return int The length of the LCS.
 648       */
 649  	function lcs() {
 650          $lcs = 0;
 651          foreach ( $this->edits as $edit ) {
 652              if ( $edit->type == 'copy' ) {
 653                  $lcs += sizeof( $edit->orig );
 654              }
 655          }
 656          return $lcs;
 657      }
 658  
 659      /**
 660       * Get the original set of lines.
 661       *
 662       * This reconstructs the $from_lines parameter passed to the
 663       * constructor.
 664       *
 665       * @return array The original sequence of strings.
 666       */
 667  	function orig() {
 668          $lines = array();
 669  
 670          foreach ( $this->edits as $edit ) {
 671              if ( $edit->orig ) {
 672                  array_splice( $lines, sizeof( $lines ), 0, $edit->orig );
 673              }
 674          }
 675          return $lines;
 676      }
 677  
 678      /**
 679       * Get the closing set of lines.
 680       *
 681       * This reconstructs the $to_lines parameter passed to the
 682       * constructor.
 683       *
 684       * @return array The sequence of strings.
 685       */
 686  	function closing() {
 687          $lines = array();
 688  
 689          foreach ( $this->edits as $edit ) {
 690              if ( $edit->closing ) {
 691                  array_splice( $lines, sizeof( $lines ), 0, $edit->closing );
 692              }
 693          }
 694          return $lines;
 695      }
 696  
 697      /**
 698       * Check a Diff for validity.
 699       *
 700       * This is here only for debugging purposes.
 701       */
 702  	function _check( $from_lines, $to_lines ) {
 703          if ( serialize( $from_lines ) != serialize( $this->orig() ) ) {
 704              trigger_error( "Reconstructed original doesn't match", E_USER_ERROR );
 705          }
 706          if ( serialize( $to_lines ) != serialize( $this->closing() ) ) {
 707              trigger_error( "Reconstructed closing doesn't match", E_USER_ERROR );
 708          }
 709  
 710          $rev = $this->reverse();
 711          if ( serialize( $to_lines ) != serialize( $rev->orig() ) ) {
 712              trigger_error( "Reversed original doesn't match", E_USER_ERROR );
 713          }
 714          if ( serialize( $from_lines ) != serialize( $rev->closing() ) ) {
 715              trigger_error( "Reversed closing doesn't match", E_USER_ERROR );
 716          }
 717  
 718  
 719          $prevtype = 'none';
 720          foreach ( $this->edits as $edit ) {
 721              if ( $prevtype == $edit->type ) {
 722                  trigger_error( 'Edit sequence is non-optimal', E_USER_ERROR );
 723              }
 724              $prevtype = $edit->type;
 725          }
 726  
 727          $lcs = $this->lcs();
 728          trigger_error( 'Diff okay: LCS = ' . $lcs, E_USER_NOTICE );
 729      }
 730  }
 731  
 732  /**
 733   * @todo document, bad name.
 734   * @private
 735   * @ingroup DifferenceEngine
 736   */
 737  class MappedDiff extends Diff {
 738      /**
 739       * Constructor.
 740       *
 741       * Computes diff between sequences of strings.
 742       *
 743       * This can be used to compute things like
 744       * case-insensitve diffs, or diffs which ignore
 745       * changes in white-space.
 746       *
 747       * @param $from_lines array An array of strings.
 748       *    (Typically these are lines from a file.)
 749       *
 750       * @param $to_lines array An array of strings.
 751       *
 752       * @param $mapped_from_lines array This array should
 753       *    have the same size number of elements as $from_lines.
 754       *    The elements in $mapped_from_lines and
 755       *    $mapped_to_lines are what is actually compared
 756       *    when computing the diff.
 757       *
 758       * @param $mapped_to_lines array This array should
 759       *    have the same number of elements as $to_lines.
 760       */
 761  	function __construct( $from_lines, $to_lines,
 762          $mapped_from_lines, $mapped_to_lines ) {
 763  
 764          assert( sizeof( $from_lines ) == sizeof( $mapped_from_lines ) );
 765          assert( sizeof( $to_lines ) == sizeof( $mapped_to_lines ) );
 766  
 767          parent::__construct( $mapped_from_lines, $mapped_to_lines );
 768  
 769          $xi = $yi = 0;
 770          for ( $i = 0; $i < sizeof( $this->edits ); $i++ ) {
 771              $orig = &$this->edits[$i]->orig;
 772              if ( is_array( $orig ) ) {
 773                  $orig = array_slice( $from_lines, $xi, sizeof( $orig ) );
 774                  $xi += sizeof( $orig );
 775              }
 776  
 777              $closing = &$this->edits[$i]->closing;
 778              if ( is_array( $closing ) ) {
 779                  $closing = array_slice( $to_lines, $yi, sizeof( $closing ) );
 780                  $yi += sizeof( $closing );
 781              }
 782          }
 783      }
 784  }
 785  
 786  /**
 787   * A class to format Diffs
 788   *
 789   * This class formats the diff in classic diff format.
 790   * It is intended that this class be customized via inheritance,
 791   * to obtain fancier outputs.
 792   * @todo document
 793   * @private
 794   * @ingroup DifferenceEngine
 795   */
 796  class DiffFormatter {
 797      /**
 798       * Number of leading context "lines" to preserve.
 799       *
 800       * This should be left at zero for this class, but subclasses
 801       * may want to set this to other values.
 802       */
 803      var $leading_context_lines = 0;
 804  
 805      /**
 806       * Number of trailing context "lines" to preserve.
 807       *
 808       * This should be left at zero for this class, but subclasses
 809       * may want to set this to other values.
 810       */
 811      var $trailing_context_lines = 0;
 812  
 813      /**
 814       * Format a diff.
 815       *
 816       * @param $diff Diff A Diff object.
 817       * @return string The formatted output.
 818       */
 819  	function format( $diff ) {
 820  
 821          $xi = $yi = 1;
 822          $block = false;
 823          $context = array();
 824  
 825          $nlead = $this->leading_context_lines;
 826          $ntrail = $this->trailing_context_lines;
 827  
 828          $this->_start_diff();
 829  
 830          foreach ( $diff->edits as $edit ) {
 831              if ( $edit->type == 'copy' ) {
 832                  if ( is_array( $block ) ) {
 833                      if ( sizeof( $edit->orig ) <= $nlead + $ntrail ) {
 834                          $block[] = $edit;
 835                      } else {
 836                          if ( $ntrail ) {
 837                              $context = array_slice( $edit->orig, 0, $ntrail );
 838                              $block[] = new _DiffOp_Copy( $context );
 839                          }
 840                          $this->_block( $x0, $ntrail + $xi - $x0,
 841                              $y0, $ntrail + $yi - $y0,
 842                              $block );
 843                          $block = false;
 844                      }
 845                  }
 846                  $context = $edit->orig;
 847              } else {
 848                  if ( !is_array( $block ) ) {
 849                      $context = array_slice( $context, sizeof( $context ) - $nlead );
 850                      $x0 = $xi - sizeof( $context );
 851                      $y0 = $yi - sizeof( $context );
 852                      $block = array();
 853                      if ( $context ) {
 854                          $block[] = new _DiffOp_Copy( $context );
 855                      }
 856                  }
 857                  $block[] = $edit;
 858              }
 859  
 860              if ( $edit->orig ) {
 861                  $xi += sizeof( $edit->orig );
 862              }
 863              if ( $edit->closing ) {
 864                  $yi += sizeof( $edit->closing );
 865              }
 866          }
 867  
 868          if ( is_array( $block ) ) {
 869              $this->_block( $x0, $xi - $x0,
 870                  $y0, $yi - $y0,
 871                  $block );
 872          }
 873  
 874          $end = $this->_end_diff();
 875          return $end;
 876      }
 877  
 878  	function _block( $xbeg, $xlen, $ybeg, $ylen, &$edits ) {
 879          $this->_start_block( $this->_block_header( $xbeg, $xlen, $ybeg, $ylen ) );
 880          foreach ( $edits as $edit ) {
 881              if ( $edit->type == 'copy' ) {
 882                  $this->_context( $edit->orig );
 883              } elseif ( $edit->type == 'add' ) {
 884                  $this->_added( $edit->closing );
 885              } elseif ( $edit->type == 'delete' ) {
 886                  $this->_deleted( $edit->orig );
 887              } elseif ( $edit->type == 'change' ) {
 888                  $this->_changed( $edit->orig, $edit->closing );
 889              } else {
 890                  trigger_error( 'Unknown edit type', E_USER_ERROR );
 891              }
 892          }
 893          $this->_end_block();
 894      }
 895  
 896  	function _start_diff() {
 897          ob_start();
 898      }
 899  
 900  	function _end_diff() {
 901          $val = ob_get_contents();
 902          ob_end_clean();
 903          return $val;
 904      }
 905  
 906  	function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
 907          if ( $xlen > 1 ) {
 908              $xbeg .= ',' . ( $xbeg + $xlen - 1 );
 909          }
 910          if ( $ylen > 1 ) {
 911              $ybeg .= ',' . ( $ybeg + $ylen - 1 );
 912          }
 913  
 914          return $xbeg . ( $xlen ? ( $ylen ? 'c' : 'd' ) : 'a' ) . $ybeg;
 915      }
 916  
 917  	function _start_block( $header ) {
 918          echo $header . "\n";
 919      }
 920  
 921  	function _end_block() {
 922      }
 923  
 924  	function _lines( $lines, $prefix = ' ' ) {
 925          foreach ( $lines as $line ) {
 926              echo "$prefix $line\n";
 927          }
 928      }
 929  
 930  	function _context( $lines ) {
 931          $this->_lines( $lines );
 932      }
 933  
 934  	function _added( $lines ) {
 935          $this->_lines( $lines, '>' );
 936      }
 937  	function _deleted( $lines ) {
 938          $this->_lines( $lines, '<' );
 939      }
 940  
 941  	function _changed( $orig, $closing ) {
 942          $this->_deleted( $orig );
 943          echo "---\n";
 944          $this->_added( $closing );
 945      }
 946  }
 947  
 948  /**
 949   * A formatter that outputs unified diffs
 950   * @ingroup DifferenceEngine
 951   */
 952  class UnifiedDiffFormatter extends DiffFormatter {
 953      var $leading_context_lines = 2;
 954      var $trailing_context_lines = 2;
 955  
 956  	function _added( $lines ) {
 957          $this->_lines( $lines, '+' );
 958      }
 959  	function _deleted( $lines ) {
 960          $this->_lines( $lines, '-' );
 961      }
 962  	function _changed( $orig, $closing ) {
 963          $this->_deleted( $orig );
 964          $this->_added( $closing );
 965      }
 966  	function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
 967          return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
 968      }
 969  }
 970  
 971  /**
 972   * A pseudo-formatter that just passes along the Diff::$edits array
 973   * @ingroup DifferenceEngine
 974   */
 975  class ArrayDiffFormatter extends DiffFormatter {
 976  	function format( $diff ) {
 977          $oldline = 1;
 978          $newline = 1;
 979          $retval = array();
 980          foreach ( $diff->edits as $edit ) {
 981              switch( $edit->type ) {
 982                  case 'add':
 983                      foreach ( $edit->closing as $l ) {
 984                          $retval[] = array(
 985                              'action' => 'add',
 986                              'new' => $l,
 987                              'newline' => $newline++
 988                          );
 989                      }
 990                      break;
 991                  case 'delete':
 992                      foreach ( $edit->orig as $l ) {
 993                          $retval[] = array(
 994                              'action' => 'delete',
 995                              'old' => $l,
 996                              'oldline' => $oldline++,
 997                          );
 998                      }
 999                      break;
1000                  case 'change':
1001                      foreach ( $edit->orig as $i => $l ) {
1002                          $retval[] = array(
1003                              'action' => 'change',
1004                              'old' => $l,
1005                              'new' => isset( $edit->closing[$i] ) ? $edit->closing[$i] : null,
1006                              'oldline' => $oldline++,
1007                              'newline' => $newline++,
1008                          );
1009                      }
1010                      break;
1011                  case 'copy':
1012                      $oldline += count( $edit->orig );
1013                      $newline += count( $edit->orig );
1014              }
1015          }
1016          return $retval;
1017      }
1018  }
1019  
1020  /**
1021   * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1022   */
1023  
1024  define( 'NBSP', '&#160;' ); // iso-8859-x non-breaking space.
1025  
1026  /**
1027   * @todo document
1028   * @private
1029   * @ingroup DifferenceEngine
1030   */
1031  class _HWLDF_WordAccumulator {
1032  	function __construct() {
1033          $this->_lines = array();
1034          $this->_line = '';
1035          $this->_group = '';
1036          $this->_tag = '';
1037      }
1038  
1039  	function _flushGroup( $new_tag ) {
1040          if ( $this->_group !== '' ) {
1041              if ( $this->_tag == 'ins' ) {
1042                  $this->_line .= '<ins class="diffchange diffchange-inline">' .
1043                          htmlspecialchars( $this->_group ) . '</ins>';
1044              } elseif ( $this->_tag == 'del' ) {
1045                  $this->_line .= '<del class="diffchange diffchange-inline">' .
1046                          htmlspecialchars( $this->_group ) . '</del>';
1047              } else {
1048                  $this->_line .= htmlspecialchars( $this->_group );
1049              }
1050          }
1051          $this->_group = '';
1052          $this->_tag = $new_tag;
1053      }
1054  
1055  	function _flushLine( $new_tag ) {
1056          $this->_flushGroup( $new_tag );
1057          if ( $this->_line != '' ) {
1058              array_push( $this->_lines, $this->_line );
1059          } else {
1060              # make empty lines visible by inserting an NBSP
1061              array_push( $this->_lines, NBSP );
1062          }
1063          $this->_line = '';
1064      }
1065  
1066  	function addWords ( $words, $tag = '' ) {
1067          if ( $tag != $this->_tag ) {
1068              $this->_flushGroup( $tag );
1069          }
1070  
1071          foreach ( $words as $word ) {
1072              // new-line should only come as first char of word.
1073              if ( $word == '' ) {
1074                  continue;
1075              }
1076              if ( $word[0] == "\n" ) {
1077                  $this->_flushLine( $tag );
1078                  $word = substr( $word, 1 );
1079              }
1080              assert( !strstr( $word, "\n" ) );
1081              $this->_group .= $word;
1082          }
1083      }
1084  
1085  	function getLines() {
1086          $this->_flushLine( '~done' );
1087          return $this->_lines;
1088      }
1089  }
1090  
1091  /**
1092   * @todo document
1093   * @private
1094   * @ingroup DifferenceEngine
1095   */
1096  class WordLevelDiff extends MappedDiff {
1097      const MAX_LINE_LENGTH = 10000;
1098  
1099  	function __construct ( $orig_lines, $closing_lines ) {
1100  
1101          list( $orig_words, $orig_stripped ) = $this->_split( $orig_lines );
1102          list( $closing_words, $closing_stripped ) = $this->_split( $closing_lines );
1103  
1104          parent::__construct( $orig_words, $closing_words,
1105          $orig_stripped, $closing_stripped );
1106      }
1107  
1108  	function _split( $lines ) {
1109  
1110          $words = array();
1111          $stripped = array();
1112          $first = true;
1113          foreach ( $lines as $line ) {
1114              # If the line is too long, just pretend the entire line is one big word
1115              # This prevents resource exhaustion problems
1116              if ( $first ) {
1117                  $first = false;
1118              } else {
1119                  $words[] = "\n";
1120                  $stripped[] = "\n";
1121              }
1122              if ( strlen( $line ) > self::MAX_LINE_LENGTH ) {
1123                  $words[] = $line;
1124                  $stripped[] = $line;
1125              } else {
1126                  $m = array();
1127                  if ( preg_match_all( '/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1128                      $line, $m ) )
1129                  {
1130                      $words = array_merge( $words, $m[0] );
1131                      $stripped = array_merge( $stripped, $m[1] );
1132                  }
1133              }
1134          }
1135          return array( $words, $stripped );
1136      }
1137  
1138  	function orig() {
1139          $orig = new _HWLDF_WordAccumulator;
1140  
1141          foreach ( $this->edits as $edit ) {
1142              if ( $edit->type == 'copy' ) {
1143                  $orig->addWords( $edit->orig );
1144              } elseif ( $edit->orig ) {
1145                  $orig->addWords( $edit->orig, 'del' );
1146              }
1147          }
1148          $lines = $orig->getLines();
1149          return $lines;
1150      }
1151  
1152  	function closing() {
1153          $closing = new _HWLDF_WordAccumulator;
1154  
1155          foreach ( $this->edits as $edit ) {
1156              if ( $edit->type == 'copy' ) {
1157                  $closing->addWords( $edit->closing );
1158              } elseif ( $edit->closing ) {
1159                  $closing->addWords( $edit->closing, 'ins' );
1160              }
1161          }
1162          $lines = $closing->getLines();
1163          return $lines;
1164      }
1165  }
1166  
1167  /**
1168   * Wikipedia Table style diff formatter.
1169   * @todo document
1170   * @private
1171   * @ingroup DifferenceEngine
1172   */
1173  class TableDiffFormatter extends DiffFormatter {
1174  	function __construct() {
1175          $this->leading_context_lines = 2;
1176          $this->trailing_context_lines = 2;
1177      }
1178  
1179  	public static function escapeWhiteSpace( $msg ) {
1180          $msg = preg_replace( '/^ /m', '&#160; ', $msg );
1181          $msg = preg_replace( '/ $/m', ' &#160;', $msg );
1182          $msg = preg_replace( '/  /', '&#160; ', $msg );
1183          return $msg;
1184      }
1185  
1186  	function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1187          $r = '<tr><td colspan="2" class="diff-lineno">'.sprintf( T_('Line %s'), $xbeg ). ":</td>\n" .
1188            '<td colspan="2" class="diff-lineno">'.sprintf( T_('Line %s'), $ybeg ). ":</td></tr>\n";
1189          return $r;
1190      }
1191  
1192  	function _start_block( $header ) {
1193          echo $header;
1194      }
1195  
1196  	function _end_block() {
1197      }
1198  
1199  	function _lines( $lines, $prefix = ' ', $color = 'white' ) {
1200      }
1201  
1202      # HTML-escape parameter before calling this
1203  	function addedLine( $line ) {
1204          return $this->wrapLine( '+', 'diff-addedline', $line );
1205      }
1206  
1207      # HTML-escape parameter before calling this
1208  	function deletedLine( $line ) {
1209          return $this->wrapLine( '&#8722;', 'diff-deletedline', $line );
1210      }
1211  
1212      # HTML-escape parameter before calling this
1213  	function contextLine( $line ) {
1214          return $this->wrapLine( '&#160;', 'diff-context', $line );
1215      }
1216  
1217  	private function wrapLine( $marker, $class, $line ) {
1218          if ( $line !== '' ) {
1219              // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1220              $line = '<div>'.$this->escapeWhiteSpace( $line ).'</div>';
1221          }
1222          return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1223      }
1224  
1225  	function emptyLine() {
1226          return '<td colspan="2">&#160;</td>';
1227      }
1228  
1229  	function _added( $lines ) {
1230          foreach ( $lines as $line ) {
1231              echo '<tr>' . $this->emptyLine() .
1232              $this->addedLine( '<ins class="diffchange">' .
1233              htmlspecialchars( $line ) . '</ins>' ) . "</tr>\n";
1234          }
1235      }
1236  
1237  	function _deleted( $lines ) {
1238          foreach ( $lines as $line ) {
1239              echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1240              htmlspecialchars( $line ) . '</del>' ) .
1241              $this->emptyLine() . "</tr>\n";
1242          }
1243      }
1244  
1245  	function _context( $lines ) {
1246          foreach ( $lines as $line ) {
1247              echo '<tr>' .
1248              $this->contextLine( htmlspecialchars( $line ) ) .
1249              $this->contextLine( htmlspecialchars( $line ) ) . "</tr>\n";
1250          }
1251      }
1252  
1253  	function _changed( $orig, $closing ) {
1254          $diff = new WordLevelDiff( $orig, $closing );
1255          $del = $diff->orig();
1256          $add = $diff->closing();
1257  
1258          # Notice that WordLevelDiff returns HTML-escaped output.
1259          # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1260  
1261          while ( $line = array_shift( $del ) ) {
1262              $aline = array_shift( $add );
1263              echo '<tr>' . $this->deletedLine( $line ) .
1264              $this->addedLine( $aline ) . "</tr>\n";
1265          }
1266          foreach ( $add as $line ) {    # If any leftovers
1267              echo '<tr>' . $this->emptyLine() .
1268              $this->addedLine( $line ) . "</tr>\n";
1269          }
1270      }
1271  }
1272  
1273  /**
1274   * Wikipedia Title style diff formatter.
1275   * @todo document
1276   * @private
1277   * @ingroup DifferenceEngine
1278   */
1279  class TitleDiffFormatter extends DiffFormatter {
1280  	function __construct() {
1281          $this->leading_context_lines = 2;
1282          $this->trailing_context_lines = 2;
1283      }
1284  
1285  	public static function escapeWhiteSpace( $msg ) {
1286          $msg = preg_replace( '/^ /m', '&#160; ', $msg );
1287          $msg = preg_replace( '/ $/m', ' &#160;', $msg );
1288          $msg = preg_replace( '/  /', '&#160; ', $msg );
1289          return $msg;
1290      }
1291  
1292  	function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1293      }
1294  
1295  	function _start_block( $header ) {
1296      }
1297  
1298  	function _end_block() {
1299      }
1300  
1301  	function _lines( $lines, $prefix = ' ', $color = 'white' ) {
1302      }
1303  
1304      # HTML-escape parameter before calling this
1305  	function addedLine( $line ) {
1306          return $this->wrapLine( 'diff-title-addedline', $line );
1307      }
1308  
1309      # HTML-escape parameter before calling this
1310  	function deletedLine( $line ) {
1311          return $this->wrapLine( 'diff-title-deletedline', $line );
1312      }
1313  
1314      # HTML-escape parameter before calling this
1315  	function contextLine( $line ) {
1316          return $this->wrapLine( 'diff-context', $line );
1317      }
1318  
1319  	private function wrapLine( $class, $line ) {
1320          if ( $line !== '' ) {
1321              // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1322              $line = '<div>'.$this->escapeWhiteSpace( $line ).'</div>';
1323          }
1324          return "<td colspan='2' class='$class'>$line</td>";
1325      }
1326  
1327  	function emptyLine() {
1328          return '<td colspan="2">&#160;</td>';
1329      }
1330  
1331  	function _added( $lines ) {
1332          foreach ( $lines as $line ) {
1333              echo '<tr>' . $this->emptyLine() .
1334              $this->addedLine( '<ins class="diffchange">' .
1335              htmlspecialchars( $line ) . '</ins>' ) . "</tr>\n";
1336          }
1337      }
1338  
1339  	function _deleted( $lines ) {
1340          foreach ( $lines as $line ) {
1341              echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1342              htmlspecialchars( $line ) . '</del>' ) .
1343              $this->emptyLine() . "</tr>\n";
1344          }
1345      }
1346  
1347  	function _context( $lines ) {
1348          foreach ( $lines as $line ) {
1349              echo '<tr>' .
1350              $this->contextLine( htmlspecialchars( $line ) ) .
1351              $this->contextLine( htmlspecialchars( $line ) ) . "</tr>\n";
1352          }
1353      }
1354  
1355  	function _changed( $orig, $closing ) {
1356          $diff = new WordLevelDiff( $orig, $closing );
1357          $del = $diff->orig();
1358          $add = $diff->closing();
1359  
1360  
1361          # Notice that WordLevelDiff returns HTML-escaped output.
1362          # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1363  
1364          while ( $line = array_shift( $del ) ) {
1365              $aline = array_shift( $add );
1366              echo '<tr>' . $this->deletedLine( $line ) .
1367              $this->addedLine( $aline ) . "</tr>\n";
1368          }
1369          foreach ( $add as $line ) {    # If any leftovers
1370              echo '<tr>' . $this->emptyLine() .
1371              $this->addedLine( $line ) . "</tr>\n";
1372          }
1373      }
1374  }
1375  
1376  ?>

title

Description

title

Description

title

Description

title

title

Body