PageRenderTime 25ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/core/Diff.php

http://github.com/silverstripe/sapphire
PHP | 878 lines | 498 code | 110 blank | 270 comment | 163 complexity | c5aeab21744b60431d234842cc28afb4 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, CC-BY-3.0, GPL-2.0, AGPL-1.0, LGPL-2.1
  1. <?php
  2. /**
  3. * @package framework
  4. * @subpackage core
  5. * A PHP diff engine
  6. */
  7. // difflib.php
  8. //
  9. // A PHP diff engine for phpwiki.
  10. //
  11. // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
  12. // You may copy this code freely under the conditions of the GPL.
  13. //
  14. define('USE_ASSERTS', true);
  15. /**
  16. * @package framework
  17. * @subpackage core
  18. * @access private
  19. */
  20. class _DiffOp {
  21. var $type;
  22. var $orig;
  23. var $final;
  24. public function reverse() {
  25. trigger_error("pure virtual", E_USER_ERROR);
  26. }
  27. public function norig() {
  28. return $this->orig ? sizeof($this->orig) : 0;
  29. }
  30. public function nfinal() {
  31. return $this->final ? sizeof($this->final) : 0;
  32. }
  33. }
  34. /**
  35. * @package framework
  36. * @subpackage core
  37. * @access private
  38. */
  39. class _DiffOp_Copy extends _DiffOp {
  40. var $type = 'copy';
  41. public function __construct ($orig, $final = false) {
  42. if (!is_array($final))
  43. $final = $orig;
  44. $this->orig = $orig;
  45. $this->final = $final;
  46. }
  47. public function reverse() {
  48. return new _DiffOp_Copy($this->final, $this->orig);
  49. }
  50. }
  51. /**
  52. * @package framework
  53. * @subpackage core
  54. * @access private
  55. */
  56. class _DiffOp_Delete extends _DiffOp {
  57. var $type = 'delete';
  58. public function __construct ($lines) {
  59. $this->orig = $lines;
  60. $this->final = false;
  61. }
  62. public function reverse() {
  63. return new _DiffOp_Add($this->orig);
  64. }
  65. }
  66. /**
  67. * @package framework
  68. * @subpackage core
  69. * @access private
  70. */
  71. class _DiffOp_Add extends _DiffOp {
  72. var $type = 'add';
  73. public function __construct ($lines) {
  74. $this->final = $lines;
  75. $this->orig = false;
  76. }
  77. public function reverse() {
  78. return new _DiffOp_Delete($this->final);
  79. }
  80. }
  81. /**
  82. * @package framework
  83. * @subpackage core
  84. * @access private
  85. */
  86. class _DiffOp_Change extends _DiffOp {
  87. var $type = 'change';
  88. public function __construct ($orig, $final) {
  89. $this->orig = $orig;
  90. $this->final = $final;
  91. }
  92. public function reverse() {
  93. return new _DiffOp_Change($this->final, $this->orig);
  94. }
  95. }
  96. /**
  97. * Class used internally by Diff to actually compute the diffs.
  98. *
  99. * The algorithm used here is mostly lifted from the perl module
  100. * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
  101. * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
  102. *
  103. * More ideas are taken from:
  104. * http://www.ics.uci.edu/~eppstein/161/960229.html
  105. *
  106. * Some ideas are (and a bit of code) are from from analyze.c, from GNU
  107. * diffutils-2.7, which can be found at:
  108. * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
  109. *
  110. * Finally, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
  111. * are my own.
  112. *
  113. * @author Geoffrey T. Dairiki
  114. * @access private
  115. * @package framework
  116. * @subpackage core
  117. */
  118. class _DiffEngine
  119. {
  120. public function diff ($from_lines, $to_lines) {
  121. $n_from = sizeof($from_lines);
  122. $n_to = sizeof($to_lines);
  123. $this->xchanged = $this->ychanged = array();
  124. $this->xv = $this->yv = array();
  125. $this->xind = $this->yind = array();
  126. unset($this->seq);
  127. unset($this->in_seq);
  128. unset($this->lcs);
  129. // Skip leading common lines.
  130. for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
  131. if ($from_lines[$skip] != $to_lines[$skip])
  132. break;
  133. $this->xchanged[$skip] = $this->ychanged[$skip] = false;
  134. }
  135. // Skip trailing common lines.
  136. $xi = $n_from; $yi = $n_to;
  137. for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
  138. if ($from_lines[$xi] != $to_lines[$yi])
  139. break;
  140. $this->xchanged[$xi] = $this->ychanged[$yi] = false;
  141. }
  142. // Ignore lines which do not exist in both files.
  143. for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
  144. $xhash[$from_lines[$xi]] = 1;
  145. for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
  146. $line = $to_lines[$yi];
  147. if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
  148. continue;
  149. $yhash[$line] = 1;
  150. $this->yv[] = $line;
  151. $this->yind[] = $yi;
  152. }
  153. for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
  154. $line = $from_lines[$xi];
  155. if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
  156. continue;
  157. $this->xv[] = $line;
  158. $this->xind[] = $xi;
  159. }
  160. // Find the LCS.
  161. $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
  162. // Merge edits when possible
  163. $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
  164. $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
  165. // Compute the edit operations.
  166. $edits = array();
  167. $xi = $yi = 0;
  168. while ($xi < $n_from || $yi < $n_to) {
  169. USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
  170. USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
  171. // Skip matching "snake".
  172. $copy = array();
  173. while ( $xi < $n_from && $yi < $n_to
  174. && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
  175. $copy[] = $from_lines[$xi++];
  176. ++$yi;
  177. }
  178. if ($copy)
  179. $edits[] = new _DiffOp_Copy($copy);
  180. // Find deletes & adds.
  181. $delete = array();
  182. while ($xi < $n_from && $this->xchanged[$xi])
  183. $delete[] = $from_lines[$xi++];
  184. $add = array();
  185. while ($yi < $n_to && $this->ychanged[$yi])
  186. $add[] = $to_lines[$yi++];
  187. if ($delete && $add)
  188. $edits[] = new _DiffOp_Change($delete, $add);
  189. elseif ($delete)
  190. $edits[] = new _DiffOp_Delete($delete);
  191. elseif ($add)
  192. $edits[] = new _DiffOp_Add($add);
  193. }
  194. return $edits;
  195. }
  196. /* Divide the Largest Common Subsequence (LCS) of the sequences
  197. * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
  198. * sized segments.
  199. *
  200. * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
  201. * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
  202. * sub sequences. The first sub-sequence is contained in [X0, X1),
  203. * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
  204. * that (X0, Y0) == (XOFF, YOFF) and
  205. * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
  206. *
  207. * This function assumes that the first lines of the specified portions
  208. * of the two files do not match, and likewise that the last lines do not
  209. * match. The caller must trim matching lines from the beginning and end
  210. * of the portions it is going to specify.
  211. */
  212. public function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
  213. $flip = false;
  214. if ($xlim - $xoff > $ylim - $yoff) {
  215. // Things seems faster (I'm not sure I understand why)
  216. // when the shortest sequence in X.
  217. $flip = true;
  218. list ($xoff, $xlim, $yoff, $ylim)
  219. = array( $yoff, $ylim, $xoff, $xlim);
  220. }
  221. if ($flip)
  222. for ($i = $ylim - 1; $i >= $yoff; $i--)
  223. $ymatches[$this->xv[$i]][] = $i;
  224. else
  225. for ($i = $ylim - 1; $i >= $yoff; $i--)
  226. $ymatches[$this->yv[$i]][] = $i;
  227. $this->lcs = 0;
  228. $this->seq[0]= $yoff - 1;
  229. $this->in_seq = array();
  230. $ymids[0] = array();
  231. $numer = $xlim - $xoff + $nchunks - 1;
  232. $x = $xoff;
  233. for ($chunk = 0; $chunk < $nchunks; $chunk++) {
  234. if ($chunk > 0)
  235. for ($i = 0; $i <= $this->lcs; $i++)
  236. $ymids[$i][$chunk-1] = $this->seq[$i];
  237. $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
  238. for ( ; $x < $x1; $x++) {
  239. $line = $flip ? $this->yv[$x] : $this->xv[$x];
  240. if (empty($ymatches[$line]))
  241. continue;
  242. $matches = $ymatches[$line];
  243. reset($matches);
  244. while (list ($junk, $y) = each($matches))
  245. if (empty($this->in_seq[$y])) {
  246. $k = $this->_lcs_pos($y);
  247. USE_ASSERTS && assert($k > 0);
  248. $ymids[$k] = $ymids[$k-1];
  249. break;
  250. }
  251. while (list ($junk, $y) = each($matches)) {
  252. if ($y > $this->seq[$k-1]) {
  253. USE_ASSERTS && assert($y < $this->seq[$k]);
  254. // Optimization: this is a common case:
  255. // next match is just replacing previous match.
  256. $this->in_seq[$this->seq[$k]] = false;
  257. $this->seq[$k] = $y;
  258. $this->in_seq[$y] = 1;
  259. }
  260. else if (empty($this->in_seq[$y])) {
  261. $k = $this->_lcs_pos($y);
  262. USE_ASSERTS && assert($k > 0);
  263. $ymids[$k] = $ymids[$k-1];
  264. }
  265. }
  266. }
  267. }
  268. $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
  269. $ymid = $ymids[$this->lcs];
  270. for ($n = 0; $n < $nchunks - 1; $n++) {
  271. $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
  272. $y1 = $ymid[$n] + 1;
  273. $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
  274. }
  275. $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
  276. return array($this->lcs, $seps);
  277. }
  278. public function _lcs_pos ($ypos) {
  279. $end = $this->lcs;
  280. if ($end == 0 || $ypos > $this->seq[$end]) {
  281. $this->seq[++$this->lcs] = $ypos;
  282. $this->in_seq[$ypos] = 1;
  283. return $this->lcs;
  284. }
  285. $beg = 1;
  286. while ($beg < $end) {
  287. $mid = (int)(($beg + $end) / 2);
  288. if ( $ypos > $this->seq[$mid] )
  289. $beg = $mid + 1;
  290. else
  291. $end = $mid;
  292. }
  293. USE_ASSERTS && assert($ypos != $this->seq[$end]);
  294. $this->in_seq[$this->seq[$end]] = false;
  295. $this->seq[$end] = $ypos;
  296. $this->in_seq[$ypos] = 1;
  297. return $end;
  298. }
  299. /* Find LCS of two sequences.
  300. *
  301. * The results are recorded in the vectors $this->{x,y}changed[], by
  302. * storing a 1 in the element for each line that is an insertion
  303. * or deletion (ie. is not in the LCS).
  304. *
  305. * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
  306. *
  307. * Note that XLIM, YLIM are exclusive bounds.
  308. * All line numbers are origin-0 and discarded lines are not counted.
  309. */
  310. public function _compareseq ($xoff, $xlim, $yoff, $ylim) {
  311. // Slide down the bottom initial diagonal.
  312. while ($xoff < $xlim && $yoff < $ylim
  313. && $this->xv[$xoff] == $this->yv[$yoff]) {
  314. ++$xoff;
  315. ++$yoff;
  316. }
  317. // Slide up the top initial diagonal.
  318. while ($xlim > $xoff && $ylim > $yoff
  319. && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
  320. --$xlim;
  321. --$ylim;
  322. }
  323. if ($xoff == $xlim || $yoff == $ylim)
  324. $lcs = 0;
  325. else {
  326. // This is ad hoc but seems to work well.
  327. //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
  328. //$nchunks = max(2,min(8,(int)$nchunks));
  329. $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
  330. list ($lcs, $seps)
  331. = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
  332. }
  333. if ($lcs == 0) {
  334. // X and Y sequences have no common subsequence:
  335. // mark all changed.
  336. while ($yoff < $ylim)
  337. $this->ychanged[$this->yind[$yoff++]] = 1;
  338. while ($xoff < $xlim)
  339. $this->xchanged[$this->xind[$xoff++]] = 1;
  340. }
  341. else {
  342. // Use the partitions to split this problem into subproblems.
  343. reset($seps);
  344. $pt1 = $seps[0];
  345. while ($pt2 = next($seps)) {
  346. $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
  347. $pt1 = $pt2;
  348. }
  349. }
  350. }
  351. /* Adjust inserts/deletes of identical lines to join changes
  352. * as much as possible.
  353. *
  354. * We do something when a run of changed lines include a
  355. * line at one end and has an excluded, identical line at the other.
  356. * We are free to choose which identical line is included.
  357. * 'compareseq' usually chooses the one at the beginning,
  358. * but usually it is cleaner to consider the following identical line
  359. * to be the "change".
  360. *
  361. * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
  362. */
  363. public function _shift_boundaries ($lines, &$changed, $other_changed) {
  364. $i = 0;
  365. $j = 0;
  366. USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
  367. $len = sizeof($lines);
  368. $other_len = sizeof($other_changed);
  369. while (1) {
  370. /*
  371. * Scan forwards to find beginning of another run of changes.
  372. * Also keep track of the corresponding point in the other file.
  373. *
  374. * Throughout this code, $i and $j are adjusted together so that
  375. * the first $i elements of $changed and the first $j elements
  376. * of $other_changed both contain the same number of zeros
  377. * (unchanged lines).
  378. * Furthermore, $j is always kept so that $j == $other_len or
  379. * $other_changed[$j] == false.
  380. */
  381. while ($j < $other_len && $other_changed[$j])
  382. $j++;
  383. while ($i < $len && ! $changed[$i]) {
  384. USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
  385. $i++; $j++;
  386. while ($j < $other_len && $other_changed[$j])
  387. $j++;
  388. }
  389. if ($i == $len)
  390. break;
  391. $start = $i;
  392. // Find the end of this run of changes.
  393. while (++$i < $len && $changed[$i])
  394. continue;
  395. do {
  396. /*
  397. * Record the length of this run of changes, so that
  398. * we can later determine whether the run has grown.
  399. */
  400. $runlength = $i - $start;
  401. /*
  402. * Move the changed region back, so long as the
  403. * previous unchanged line matches the last changed one.
  404. * This merges with previous changed regions.
  405. */
  406. while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
  407. $changed[--$start] = 1;
  408. $changed[--$i] = false;
  409. while ($start > 0 && $changed[$start - 1])
  410. $start--;
  411. USE_ASSERTS && assert('$j > 0');
  412. while ($other_changed[--$j])
  413. continue;
  414. USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
  415. }
  416. /*
  417. * Set CORRESPONDING to the end of the changed run, at the last
  418. * point where it corresponds to a changed run in the other file.
  419. * CORRESPONDING == LEN means no such point has been found.
  420. */
  421. $corresponding = $j < $other_len ? $i : $len;
  422. /*
  423. * Move the changed region forward, so long as the
  424. * first changed line matches the following unchanged one.
  425. * This merges with following changed regions.
  426. * Do this second, so that if there are no merges,
  427. * the changed region is moved forward as far as possible.
  428. */
  429. while ($i < $len && $lines[$start] == $lines[$i]) {
  430. $changed[$start++] = false;
  431. $changed[$i++] = 1;
  432. while ($i < $len && $changed[$i])
  433. $i++;
  434. USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
  435. $j++;
  436. if ($j < $other_len && $other_changed[$j]) {
  437. $corresponding = $i;
  438. while ($j < $other_len && $other_changed[$j])
  439. $j++;
  440. }
  441. }
  442. } while ($runlength != $i - $start);
  443. /*
  444. * If possible, move the fully-merged run of changes
  445. * back to a corresponding run in the other file.
  446. */
  447. while ($corresponding < $i) {
  448. $changed[--$start] = 1;
  449. $changed[--$i] = 0;
  450. USE_ASSERTS && assert('$j > 0');
  451. while ($other_changed[--$j])
  452. continue;
  453. USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
  454. }
  455. }
  456. }
  457. }
  458. /**
  459. * Class representing a 'diff' between two sequences of strings.
  460. * @package framework
  461. * @subpackage core
  462. */
  463. class Diff
  464. {
  465. public static $html_cleaner_class = null;
  466. var $edits;
  467. /**
  468. * Constructor.
  469. * Computes diff between sequences of strings.
  470. *
  471. * @param $from_lines array An array of strings.
  472. * (Typically these are lines from a file.)
  473. * @param $to_lines array An array of strings.
  474. */
  475. public function __construct($from_lines, $to_lines) {
  476. $eng = new _DiffEngine;
  477. $this->edits = $eng->diff($from_lines, $to_lines);
  478. //$this->_check($from_lines, $to_lines);
  479. }
  480. /**
  481. * Compute reversed Diff.
  482. *
  483. * SYNOPSIS:
  484. *
  485. * $diff = new Diff($lines1, $lines2);
  486. * $rev = $diff->reverse();
  487. * @return object A Diff object representing the inverse of the
  488. * original diff.
  489. */
  490. public function reverse () {
  491. $rev = $this;
  492. $rev->edits = array();
  493. foreach ($this->edits as $edit) {
  494. $rev->edits[] = $edit->reverse();
  495. }
  496. return $rev;
  497. }
  498. /**
  499. * Check for empty diff.
  500. *
  501. * @return bool True iff two sequences were identical.
  502. */
  503. public function isEmpty () {
  504. foreach ($this->edits as $edit) {
  505. if ($edit->type != 'copy')
  506. return false;
  507. }
  508. return true;
  509. }
  510. /**
  511. * Compute the length of the Longest Common Subsequence (LCS).
  512. *
  513. * This is mostly for diagnostic purposed.
  514. *
  515. * @return int The length of the LCS.
  516. */
  517. public function lcs () {
  518. $lcs = 0;
  519. foreach ($this->edits as $edit) {
  520. if ($edit->type == 'copy')
  521. $lcs += sizeof($edit->orig);
  522. }
  523. return $lcs;
  524. }
  525. /**
  526. * Get the original set of lines.
  527. *
  528. * This reconstructs the $from_lines parameter passed to the
  529. * constructor.
  530. *
  531. * @return array The original sequence of strings.
  532. */
  533. public function orig() {
  534. $lines = array();
  535. foreach ($this->edits as $edit) {
  536. if ($edit->orig)
  537. array_splice($lines, sizeof($lines), 0, $edit->orig);
  538. }
  539. return $lines;
  540. }
  541. /**
  542. * Get the final set of lines.
  543. *
  544. * This reconstructs the $to_lines parameter passed to the
  545. * constructor.
  546. *
  547. * @return array The sequence of strings.
  548. */
  549. public function finaltext() {
  550. $lines = array();
  551. foreach ($this->edits as $edit) {
  552. if ($edit->final)
  553. array_splice($lines, sizeof($lines), 0, $edit->final);
  554. }
  555. return $lines;
  556. }
  557. /**
  558. * Check a Diff for validity.
  559. *
  560. * This is here only for debugging purposes.
  561. */
  562. public function _check ($from_lines, $to_lines) {
  563. if (serialize($from_lines) != serialize($this->orig()))
  564. trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
  565. if (serialize($to_lines) != serialize($this->finaltext()))
  566. trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
  567. $rev = $this->reverse();
  568. if (serialize($to_lines) != serialize($rev->orig()))
  569. trigger_error("Reversed original doesn't match", E_USER_ERROR);
  570. if (serialize($from_lines) != serialize($rev->finaltext()))
  571. trigger_error("Reversed final doesn't match", E_USER_ERROR);
  572. $prevtype = 'none';
  573. foreach ($this->edits as $edit) {
  574. if ( $prevtype == $edit->type )
  575. trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
  576. $prevtype = $edit->type;
  577. }
  578. $lcs = $this->lcs();
  579. trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
  580. }
  581. /**
  582. * Attempt to clean invalid HTML, which messes up diffs.
  583. * This cleans code if possible, using an instance of HTMLCleaner
  584. *
  585. * NB: By default, only extremely simple tidying is performed,
  586. * by passing through DomDocument::loadHTML and saveXML
  587. *
  588. * @param string $content HTML content
  589. * @param object $cleaner Optional instance of a HTMLCleaner class to
  590. * use, overriding self::$html_cleaner_class
  591. */
  592. public static function cleanHTML($content, $cleaner=null) {
  593. if (!$cleaner) {
  594. if (class_exists(self::$html_cleaner_class)) {
  595. $cleaner = new self::$html_cleaner_class;
  596. } else {
  597. $cleaner = HTMLCleaner::inst(); //load cleaner if the dependent class is available
  598. }
  599. }
  600. if ($cleaner) {
  601. $content = $cleaner->cleanHTML($content);
  602. } else {
  603. // At most basic level of cleaning, use DOMDocument to save valid XML.
  604. $doc = Injector::inst()->create('HTMLValue', $content);
  605. $content = $doc->getContent();
  606. }
  607. // Remove empty <ins /> and <del /> tags because browsers hate them
  608. $content = preg_replace('/<(ins|del)[^>]*\/>/','', $content);
  609. return $content;
  610. }
  611. /**
  612. * @param String
  613. * @param String
  614. * @param Boolean
  615. * @return String
  616. */
  617. public static function compareHTML($from, $to, $escape = false) {
  618. // First split up the content into words and tags
  619. $set1 = self::getHTMLChunks($from);
  620. $set2 = self::getHTMLChunks($to);
  621. // Diff that
  622. $diff = new Diff($set1, $set2);
  623. $tagStack[1] = $tagStack[2] = 0;
  624. $rechunked[1] = $rechunked[2] = array();
  625. // Go through everything, converting edited tags (and their content) into single chunks. Otherwise
  626. // the generated HTML gets crusty
  627. foreach($diff->edits as $edit) {
  628. switch($edit->type) {
  629. case 'copy':
  630. $lookForTag = false;
  631. $stuffFor[1] = $edit->orig;
  632. $stuffFor[2] = $edit->orig;
  633. break;
  634. case 'change':
  635. $lookForTag = true;
  636. $stuffFor[1] = $edit->orig;
  637. $stuffFor[2] = $edit->final;
  638. break;
  639. case 'add':
  640. $lookForTag = true;
  641. $stuffFor[1] = null;
  642. $stuffFor[2] = $edit->final;
  643. break;
  644. case 'delete':
  645. $lookForTag = true;
  646. $stuffFor[1] = $edit->orig;
  647. $stuffFor[2] = null;
  648. break;
  649. }
  650. foreach($stuffFor as $listName => $chunks) {
  651. if($chunks) {
  652. foreach($chunks as $item) {
  653. // $tagStack > 0 indicates that we should be tag-building
  654. if($tagStack[$listName]) $rechunked[$listName][sizeof($rechunked[$listName])-1] .= ' ' . $item;
  655. else $rechunked[$listName][] = $item;
  656. if($lookForTag && !$tagStack[$listName] && isset($item[0]) && $item[0] == "<"
  657. && substr($item,0,2) != "</") {
  658. $tagStack[$listName] = 1;
  659. } else if($tagStack[$listName]) {
  660. if(substr($item,0,2) == "</") $tagStack[$listName]--;
  661. else if(isset($item[0]) && $item[0] == "<") $tagStack[$listName]++;
  662. }
  663. }
  664. }
  665. }
  666. }
  667. // Diff the re-chunked data, turning it into maked up HTML
  668. $diff = new Diff($rechunked[1], $rechunked[2]);
  669. $content = '';
  670. foreach($diff->edits as $edit) {
  671. $orig = ($escape) ? Convert::raw2xml($edit->orig) : $edit->orig;
  672. $final = ($escape) ? Convert::raw2xml($edit->final) : $edit->final;
  673. switch($edit->type) {
  674. case 'copy':
  675. $content .= " " . implode(" ", $orig) . " ";
  676. break;
  677. case 'change':
  678. $content .= " <ins>" . implode(" ", $final) . "</ins> ";
  679. $content .= " <del>" . implode(" ", $orig) . "</del> ";
  680. break;
  681. case 'add':
  682. $content .= " <ins>" . implode(" ", $final) . "</ins> ";
  683. break;
  684. case 'delete':
  685. $content .= " <del>" . implode(" ", $orig) . "</del> ";
  686. break;
  687. }
  688. }
  689. return self::cleanHTML($content);
  690. }
  691. /**
  692. * @param string|array If passed as an array, values will be concatenated with a comma.
  693. */
  694. public static function getHTMLChunks($content) {
  695. if($content && !is_string($content) && !is_array($content) && !is_numeric($content)) {
  696. throw new InvalidArgumentException('$content parameter needs to be a string or array');
  697. }
  698. if(is_array($content)) $content = implode(',', $content);
  699. $content = str_replace(array("&nbsp;","<", ">"),array(" "," <", "> "),$content);
  700. $candidateChunks = preg_split("/[\t\r\n ]+/", $content);
  701. while(list($i,$item) = each($candidateChunks)) {
  702. if(isset($item[0]) && $item[0] == "<") {
  703. $newChunk = $item;
  704. while($item[strlen($item)-1] != ">") {
  705. list($i,$item) = each($candidateChunks);
  706. $newChunk .= ' ' . $item;
  707. }
  708. $chunks[] = $newChunk;
  709. } else {
  710. $chunks[] = $item;
  711. }
  712. }
  713. return $chunks;
  714. }
  715. }
  716. /**
  717. * Computes diff between sequences of strings.
  718. * @package framework
  719. * @subpackage core
  720. */
  721. class MappedDiff
  722. extends Diff
  723. {
  724. /**
  725. * Constructor.
  726. *
  727. * Computes diff between sequences of strings.
  728. *
  729. * This can be used to compute things like
  730. * case-insensitve diffs, or diffs which ignore
  731. * changes in white-space.
  732. *
  733. * @param $from_lines array An array of strings.
  734. * (Typically these are lines from a file.)
  735. *
  736. * @param $to_lines array An array of strings.
  737. *
  738. * @param $mapped_from_lines array This array should
  739. * have the same size number of elements as $from_lines.
  740. * The elements in $mapped_from_lines and
  741. * $mapped_to_lines are what is actually compared
  742. * when computing the diff.
  743. *
  744. * @param $mapped_to_lines array This array should
  745. * have the same number of elements as $to_lines.
  746. */
  747. public function __construct($from_lines, $to_lines,
  748. $mapped_from_lines, $mapped_to_lines) {
  749. assert(sizeof($from_lines) == sizeof($mapped_from_lines));
  750. assert(sizeof($to_lines) == sizeof($mapped_to_lines));
  751. parent::__construct($mapped_from_lines, $mapped_to_lines);
  752. $xi = $yi = 0;
  753. // Optimizing loop invariants:
  754. // http://phplens.com/lens/php-book/optimizing-debugging-php.php
  755. for ($i = 0, $max = sizeof($this->edits); $i < $max; $i++) {
  756. $orig = &$this->edits[$i]->orig;
  757. if (is_array($orig)) {
  758. $orig = array_slice($from_lines, $xi, sizeof($orig));
  759. $xi += sizeof($orig);
  760. }
  761. $final = &$this->edits[$i]->final;
  762. if (is_array($final)) {
  763. $final = array_slice($to_lines, $yi, sizeof($final));
  764. $yi += sizeof($final);
  765. }
  766. }
  767. }
  768. }