PageRenderTime 62ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/mod/wiki/diff/diff_nwiki.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 1093 lines | 697 code | 154 blank | 242 comment | 166 complexity | b4223d34166dd209a61cf03fc02ce366 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  1. <?php
  2. # See diff.doc
  3. // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
  4. //
  5. // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
  6. // You may copy this code freely under the conditions of the GPL.
  7. //
  8. define('USE_ASSERTS_IN_WIKI', function_exists('assert'));
  9. class _WikiDiffOp {
  10. var $type;
  11. var $orig;
  12. var $closing;
  13. function reverse() {
  14. trigger_error("pure virtual", E_USER_ERROR);
  15. }
  16. function norig() {
  17. return $this->orig ? sizeof($this->orig) : 0;
  18. }
  19. function nclosing() {
  20. return $this->closing ? sizeof($this->closing) : 0;
  21. }
  22. }
  23. class _WikiDiffOp_Copy extends _WikiDiffOp {
  24. var $type = 'copy';
  25. function _WikiDiffOp_Copy ($orig, $closing = false) {
  26. if (!is_array($closing))
  27. $closing = $orig;
  28. $this->orig = $orig;
  29. $this->closing = $closing;
  30. }
  31. function reverse() {
  32. return new _WikiDiffOp_Copy($this->closing, $this->orig);
  33. }
  34. }
  35. class _WikiDiffOp_Delete extends _WikiDiffOp {
  36. var $type = 'delete';
  37. function _WikiDiffOp_Delete ($lines) {
  38. $this->orig = $lines;
  39. $this->closing = false;
  40. }
  41. function reverse() {
  42. return new _WikiDiffOp_Add($this->orig);
  43. }
  44. }
  45. class _WikiDiffOp_Add extends _WikiDiffOp {
  46. var $type = 'add';
  47. function _WikiDiffOp_Add ($lines) {
  48. $this->closing = $lines;
  49. $this->orig = false;
  50. }
  51. function reverse() {
  52. return new _WikiDiffOp_Delete($this->closing);
  53. }
  54. }
  55. class _WikiDiffOp_Change extends _WikiDiffOp {
  56. var $type = 'change';
  57. function _WikiDiffOp_Change ($orig, $closing) {
  58. $this->orig = $orig;
  59. $this->closing = $closing;
  60. }
  61. function reverse() {
  62. return new _WikiDiffOp_Change($this->closing, $this->orig);
  63. }
  64. }
  65. /**
  66. * Class used internally by Diff to actually compute the diffs.
  67. *
  68. * The algorithm used here is mostly lifted from the perl module
  69. * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
  70. * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
  71. *
  72. * More ideas are taken from:
  73. * http://www.ics.uci.edu/~eppstein/161/960229.html
  74. *
  75. * Some ideas are (and a bit of code) are from from analyze.c, from GNU
  76. * diffutils-2.7, which can be found at:
  77. * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
  78. *
  79. * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
  80. * are my own.
  81. *
  82. * @author Geoffrey T. Dairiki
  83. * @access private
  84. */
  85. class _WikiDiffEngine
  86. {
  87. function diff ($from_lines, $to_lines) {
  88. $n_from = sizeof($from_lines);
  89. $n_to = sizeof($to_lines);
  90. $this->xchanged = $this->ychanged = array();
  91. $this->xv = $this->yv = array();
  92. $this->xind = $this->yind = array();
  93. unset($this->seq);
  94. unset($this->in_seq);
  95. unset($this->lcs);
  96. // Skip leading common lines.
  97. for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
  98. if ($from_lines[$skip] != $to_lines[$skip])
  99. break;
  100. $this->xchanged[$skip] = $this->ychanged[$skip] = false;
  101. }
  102. // Skip trailing common lines.
  103. $xi = $n_from; $yi = $n_to;
  104. for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
  105. if ($from_lines[$xi] != $to_lines[$yi])
  106. break;
  107. $this->xchanged[$xi] = $this->ychanged[$yi] = false;
  108. }
  109. // Ignore lines which do not exist in both files.
  110. for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
  111. $xhash[$from_lines[$xi]] = 1;
  112. for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
  113. $line = $to_lines[$yi];
  114. if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
  115. continue;
  116. $yhash[$line] = 1;
  117. $this->yv[] = $line;
  118. $this->yind[] = $yi;
  119. }
  120. for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
  121. $line = $from_lines[$xi];
  122. if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
  123. continue;
  124. $this->xv[] = $line;
  125. $this->xind[] = $xi;
  126. }
  127. // Find the LCS.
  128. $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
  129. // Merge edits when possible
  130. $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
  131. $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
  132. // Compute the edit operations.
  133. $edits = array();
  134. $xi = $yi = 0;
  135. while ($xi < $n_from || $yi < $n_to) {
  136. USE_ASSERTS_IN_WIKI && assert($yi < $n_to || $this->xchanged[$xi]);
  137. USE_ASSERTS_IN_WIKI && assert($xi < $n_from || $this->ychanged[$yi]);
  138. // Skip matching "snake".
  139. $copy = array();
  140. while ( $xi < $n_from && $yi < $n_to
  141. && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
  142. $copy[] = $from_lines[$xi++];
  143. ++$yi;
  144. }
  145. if ($copy)
  146. $edits[] = new _WikiDiffOp_Copy($copy);
  147. // Find deletes & adds.
  148. $delete = array();
  149. while ($xi < $n_from && $this->xchanged[$xi])
  150. $delete[] = $from_lines[$xi++];
  151. $add = array();
  152. while ($yi < $n_to && $this->ychanged[$yi])
  153. $add[] = $to_lines[$yi++];
  154. if ($delete && $add)
  155. $edits[] = new _WikiDiffOp_Change($delete, $add);
  156. elseif ($delete)
  157. $edits[] = new _WikiDiffOp_Delete($delete);
  158. elseif ($add)
  159. $edits[] = new _WikiDiffOp_Add($add);
  160. }
  161. return $edits;
  162. }
  163. /* Divide the Largest Common Subsequence (LCS) of the sequences
  164. * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
  165. * sized segments.
  166. *
  167. * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
  168. * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
  169. * sub sequences. The first sub-sequence is contained in [X0, X1),
  170. * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
  171. * that (X0, Y0) == (XOFF, YOFF) and
  172. * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
  173. *
  174. * This function assumes that the first lines of the specified portions
  175. * of the two files do not match, and likewise that the last lines do not
  176. * match. The caller must trim matching lines from the beginning and end
  177. * of the portions it is going to specify.
  178. */
  179. function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
  180. $flip = false;
  181. if ($xlim - $xoff > $ylim - $yoff) {
  182. // Things seems faster (I'm not sure I understand why)
  183. // when the shortest sequence in X.
  184. $flip = true;
  185. list ($xoff, $xlim, $yoff, $ylim)
  186. = array( $yoff, $ylim, $xoff, $xlim);
  187. }
  188. if ($flip)
  189. for ($i = $ylim - 1; $i >= $yoff; $i--)
  190. $ymatches[$this->xv[$i]][] = $i;
  191. else
  192. for ($i = $ylim - 1; $i >= $yoff; $i--)
  193. $ymatches[$this->yv[$i]][] = $i;
  194. $this->lcs = 0;
  195. $this->seq[0]= $yoff - 1;
  196. $this->in_seq = array();
  197. $ymids[0] = array();
  198. $numer = $xlim - $xoff + $nchunks - 1;
  199. $x = $xoff;
  200. for ($chunk = 0; $chunk < $nchunks; $chunk++) {
  201. if ($chunk > 0)
  202. for ($i = 0; $i <= $this->lcs; $i++)
  203. $ymids[$i][$chunk-1] = $this->seq[$i];
  204. $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
  205. for ( ; $x < $x1; $x++) {
  206. $line = $flip ? $this->yv[$x] : $this->xv[$x];
  207. if (empty($ymatches[$line]))
  208. continue;
  209. $matches = $ymatches[$line];
  210. reset($matches);
  211. while (list ($junk, $y) = each($matches))
  212. if (empty($this->in_seq[$y])) {
  213. $k = $this->_lcs_pos($y);
  214. USE_ASSERTS_IN_WIKI && assert($k > 0);
  215. $ymids[$k] = $ymids[$k-1];
  216. break;
  217. }
  218. while (list ($junk, $y) = each($matches)) {
  219. if ($y > $this->seq[$k-1]) {
  220. USE_ASSERTS_IN_WIKI && assert($y < $this->seq[$k]);
  221. // Optimization: this is a common case:
  222. // next match is just replacing previous match.
  223. $this->in_seq[$this->seq[$k]] = false;
  224. $this->seq[$k] = $y;
  225. $this->in_seq[$y] = 1;
  226. }
  227. else if (empty($this->in_seq[$y])) {
  228. $k = $this->_lcs_pos($y);
  229. USE_ASSERTS_IN_WIKI && assert($k > 0);
  230. $ymids[$k] = $ymids[$k-1];
  231. }
  232. }
  233. }
  234. }
  235. $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
  236. $ymid = $ymids[$this->lcs];
  237. for ($n = 0; $n < $nchunks - 1; $n++) {
  238. $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
  239. $y1 = $ymid[$n] + 1;
  240. $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
  241. }
  242. $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
  243. return array($this->lcs, $seps);
  244. }
  245. function _lcs_pos ($ypos) {
  246. $end = $this->lcs;
  247. if ($end == 0 || $ypos > $this->seq[$end]) {
  248. $this->seq[++$this->lcs] = $ypos;
  249. $this->in_seq[$ypos] = 1;
  250. return $this->lcs;
  251. }
  252. $beg = 1;
  253. while ($beg < $end) {
  254. $mid = (int)(($beg + $end) / 2);
  255. if ( $ypos > $this->seq[$mid] )
  256. $beg = $mid + 1;
  257. else
  258. $end = $mid;
  259. }
  260. USE_ASSERTS_IN_WIKI && assert($ypos != $this->seq[$end]);
  261. $this->in_seq[$this->seq[$end]] = false;
  262. $this->seq[$end] = $ypos;
  263. $this->in_seq[$ypos] = 1;
  264. return $end;
  265. }
  266. /* Find LCS of two sequences.
  267. *
  268. * The results are recorded in the vectors $this->{x,y}changed[], by
  269. * storing a 1 in the element for each line that is an insertion
  270. * or deletion (ie. is not in the LCS).
  271. *
  272. * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
  273. *
  274. * Note that XLIM, YLIM are exclusive bounds.
  275. * All line numbers are origin-0 and discarded lines are not counted.
  276. */
  277. function _compareseq ($xoff, $xlim, $yoff, $ylim) {
  278. // Slide down the bottom initial diagonal.
  279. while ($xoff < $xlim && $yoff < $ylim
  280. && $this->xv[$xoff] == $this->yv[$yoff]) {
  281. ++$xoff;
  282. ++$yoff;
  283. }
  284. // Slide up the top initial diagonal.
  285. while ($xlim > $xoff && $ylim > $yoff
  286. && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
  287. --$xlim;
  288. --$ylim;
  289. }
  290. if ($xoff == $xlim || $yoff == $ylim)
  291. $lcs = 0;
  292. else {
  293. // This is ad hoc but seems to work well.
  294. //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
  295. //$nchunks = max(2,min(8,(int)$nchunks));
  296. $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
  297. list ($lcs, $seps)
  298. = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
  299. }
  300. if ($lcs == 0) {
  301. // X and Y sequences have no common subsequence:
  302. // mark all changed.
  303. while ($yoff < $ylim)
  304. $this->ychanged[$this->yind[$yoff++]] = 1;
  305. while ($xoff < $xlim)
  306. $this->xchanged[$this->xind[$xoff++]] = 1;
  307. }
  308. else {
  309. // Use the partitions to split this problem into subproblems.
  310. reset($seps);
  311. $pt1 = $seps[0];
  312. while ($pt2 = next($seps)) {
  313. $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
  314. $pt1 = $pt2;
  315. }
  316. }
  317. }
  318. /* Adjust inserts/deletes of identical lines to join changes
  319. * as much as possible.
  320. *
  321. * We do something when a run of changed lines include a
  322. * line at one end and has an excluded, identical line at the other.
  323. * We are free to choose which identical line is included.
  324. * `compareseq' usually chooses the one at the beginning,
  325. * but usually it is cleaner to consider the following identical line
  326. * to be the "change".
  327. *
  328. * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
  329. */
  330. function _shift_boundaries ($lines, &$changed, $other_changed) {
  331. $i = 0;
  332. $j = 0;
  333. USE_ASSERTS_IN_WIKI && assert('sizeof($lines) == sizeof($changed)');
  334. $len = sizeof($lines);
  335. $other_len = sizeof($other_changed);
  336. while (1) {
  337. /*
  338. * Scan forwards to find beginning of another run of changes.
  339. * Also keep track of the corresponding point in the other file.
  340. *
  341. * Throughout this code, $i and $j are adjusted together so that
  342. * the first $i elements of $changed and the first $j elements
  343. * of $other_changed both contain the same number of zeros
  344. * (unchanged lines).
  345. * Furthermore, $j is always kept so that $j == $other_len or
  346. * $other_changed[$j] == false.
  347. */
  348. while ($j < $other_len && $other_changed[$j])
  349. $j++;
  350. while ($i < $len && ! $changed[$i]) {
  351. USE_ASSERTS_IN_WIKI && assert('$j < $other_len && ! $other_changed[$j]');
  352. $i++; $j++;
  353. while ($j < $other_len && $other_changed[$j])
  354. $j++;
  355. }
  356. if ($i == $len)
  357. break;
  358. $start = $i;
  359. // Find the end of this run of changes.
  360. while (++$i < $len && $changed[$i])
  361. continue;
  362. do {
  363. /*
  364. * Record the length of this run of changes, so that
  365. * we can later determine whether the run has grown.
  366. */
  367. $runlength = $i - $start;
  368. /*
  369. * Move the changed region back, so long as the
  370. * previous unchanged line matches the last changed one.
  371. * This merges with previous changed regions.
  372. */
  373. while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
  374. $changed[--$start] = 1;
  375. $changed[--$i] = false;
  376. while ($start > 0 && $changed[$start - 1])
  377. $start--;
  378. USE_ASSERTS_IN_WIKI && assert('$j > 0');
  379. while ($other_changed[--$j])
  380. continue;
  381. USE_ASSERTS_IN_WIKI && assert('$j >= 0 && !$other_changed[$j]');
  382. }
  383. /*
  384. * Set CORRESPONDING to the end of the changed run, at the last
  385. * point where it corresponds to a changed run in the other file.
  386. * CORRESPONDING == LEN means no such point has been found.
  387. */
  388. $corresponding = $j < $other_len ? $i : $len;
  389. /*
  390. * Move the changed region forward, so long as the
  391. * first changed line matches the following unchanged one.
  392. * This merges with following changed regions.
  393. * Do this second, so that if there are no merges,
  394. * the changed region is moved forward as far as possible.
  395. */
  396. while ($i < $len && $lines[$start] == $lines[$i]) {
  397. $changed[$start++] = false;
  398. $changed[$i++] = 1;
  399. while ($i < $len && $changed[$i])
  400. $i++;
  401. USE_ASSERTS_IN_WIKI && assert('$j < $other_len && ! $other_changed[$j]');
  402. $j++;
  403. if ($j < $other_len && $other_changed[$j]) {
  404. $corresponding = $i;
  405. while ($j < $other_len && $other_changed[$j])
  406. $j++;
  407. }
  408. }
  409. } while ($runlength != $i - $start);
  410. /*
  411. * If possible, move the fully-merged run of changes
  412. * back to a corresponding run in the other file.
  413. */
  414. while ($corresponding < $i) {
  415. $changed[--$start] = 1;
  416. $changed[--$i] = 0;
  417. USE_ASSERTS_IN_WIKI && assert('$j > 0');
  418. while ($other_changed[--$j])
  419. continue;
  420. USE_ASSERTS_IN_WIKI && assert('$j >= 0 && !$other_changed[$j]');
  421. }
  422. }
  423. }
  424. }
  425. /**
  426. * Class representing a 'diff' between two sequences of strings.
  427. */
  428. class WikiDiff
  429. {
  430. var $edits;
  431. /**
  432. * Constructor.
  433. * Computes diff between sequences of strings.
  434. *
  435. * @param $from_lines array An array of strings.
  436. * (Typically these are lines from a file.)
  437. * @param $to_lines array An array of strings.
  438. */
  439. function WikiDiff($from_lines, $to_lines) {
  440. $eng = new _WikiDiffEngine;
  441. $this->edits = $eng->diff($from_lines, $to_lines);
  442. //$this->_check($from_lines, $to_lines);
  443. }
  444. /**
  445. * Compute reversed WikiDiff.
  446. *
  447. * SYNOPSIS:
  448. *
  449. * $diff = new WikiDiff($lines1, $lines2);
  450. * $rev = $diff->reverse();
  451. * @return object A WikiDiff object representing the inverse of the
  452. * original diff.
  453. */
  454. function reverse () {
  455. $rev = $this;
  456. $rev->edits = array();
  457. foreach ($this->edits as $edit) {
  458. $rev->edits[] = $edit->reverse();
  459. }
  460. return $rev;
  461. }
  462. /**
  463. * Check for empty diff.
  464. *
  465. * @return bool True iff two sequences were identical.
  466. */
  467. function isEmpty () {
  468. foreach ($this->edits as $edit) {
  469. if ($edit->type != 'copy')
  470. return false;
  471. }
  472. return true;
  473. }
  474. /**
  475. * Compute the length of the Longest Common Subsequence (LCS).
  476. *
  477. * This is mostly for diagnostic purposed.
  478. *
  479. * @return int The length of the LCS.
  480. */
  481. function lcs () {
  482. $lcs = 0;
  483. foreach ($this->edits as $edit) {
  484. if ($edit->type == 'copy')
  485. $lcs += sizeof($edit->orig);
  486. }
  487. return $lcs;
  488. }
  489. /**
  490. * Get the original set of lines.
  491. *
  492. * This reconstructs the $from_lines parameter passed to the
  493. * constructor.
  494. *
  495. * @return array The original sequence of strings.
  496. */
  497. function orig() {
  498. $lines = array();
  499. foreach ($this->edits as $edit) {
  500. if ($edit->orig)
  501. array_splice($lines, sizeof($lines), 0, $edit->orig);
  502. }
  503. return $lines;
  504. }
  505. /**
  506. * Get the closing set of lines.
  507. *
  508. * This reconstructs the $to_lines parameter passed to the
  509. * constructor.
  510. *
  511. * @return array The sequence of strings.
  512. */
  513. function closing() {
  514. $lines = array();
  515. foreach ($this->edits as $edit) {
  516. if ($edit->closing)
  517. array_splice($lines, sizeof($lines), 0, $edit->closing);
  518. }
  519. return $lines;
  520. }
  521. /**
  522. * Check a WikiDiff for validity.
  523. *
  524. * This is here only for debugging purposes.
  525. */
  526. function _check ($from_lines, $to_lines) {
  527. if (serialize($from_lines) != serialize($this->orig()))
  528. trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
  529. if (serialize($to_lines) != serialize($this->closing()))
  530. trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
  531. $rev = $this->reverse();
  532. if (serialize($to_lines) != serialize($rev->orig()))
  533. trigger_error("Reversed original doesn't match", E_USER_ERROR);
  534. if (serialize($from_lines) != serialize($rev->closing()))
  535. trigger_error("Reversed closing doesn't match", E_USER_ERROR);
  536. $prevtype = 'none';
  537. foreach ($this->edits as $edit) {
  538. if ( $prevtype == $edit->type )
  539. trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
  540. $prevtype = $edit->type;
  541. }
  542. $lcs = $this->lcs();
  543. trigger_error("WikiDiff okay: LCS = $lcs", E_USER_NOTICE);
  544. }
  545. }
  546. /**
  547. * FIXME: bad name.
  548. */
  549. class MappedWikiDiff
  550. extends WikiDiff
  551. {
  552. /**
  553. * Constructor.
  554. *
  555. * Computes diff between sequences of strings.
  556. *
  557. * This can be used to compute things like
  558. * case-insensitve diffs, or diffs which ignore
  559. * changes in white-space.
  560. *
  561. * @param $from_lines array An array of strings.
  562. * (Typically these are lines from a file.)
  563. *
  564. * @param $to_lines array An array of strings.
  565. *
  566. * @param $mapped_from_lines array This array should
  567. * have the same size number of elements as $from_lines.
  568. * The elements in $mapped_from_lines and
  569. * $mapped_to_lines are what is actually compared
  570. * when computing the diff.
  571. *
  572. * @param $mapped_to_lines array This array should
  573. * have the same number of elements as $to_lines.
  574. */
  575. function MappedWikiDiff($from_lines, $to_lines,
  576. $mapped_from_lines, $mapped_to_lines) {
  577. assert(sizeof($from_lines) == sizeof($mapped_from_lines));
  578. assert(sizeof($to_lines) == sizeof($mapped_to_lines));
  579. $this->WikiDiff($mapped_from_lines, $mapped_to_lines);
  580. $xi = $yi = 0;
  581. for ($i = 0; $i < sizeof($this->edits); $i++) {
  582. $orig = &$this->edits[$i]->orig;
  583. if (is_array($orig)) {
  584. $orig = array_slice($from_lines, $xi, sizeof($orig));
  585. $xi += sizeof($orig);
  586. }
  587. $closing = &$this->edits[$i]->closing;
  588. if (is_array($closing)) {
  589. $closing = array_slice($to_lines, $yi, sizeof($closing));
  590. $yi += sizeof($closing);
  591. }
  592. }
  593. }
  594. }
  595. /**
  596. * A class to format WikiDiffs
  597. *
  598. * This class formats the diff in classic diff format.
  599. * It is intended that this class be customized via inheritance,
  600. * to obtain fancier outputs.
  601. */
  602. class WikiDiffFormatter
  603. {
  604. /**
  605. * Number of leading context "lines" to preserve.
  606. *
  607. * This should be left at zero for this class, but subclasses
  608. * may want to set this to other values.
  609. */
  610. var $leading_context_lines = 0;
  611. /**
  612. * Number of trailing context "lines" to preserve.
  613. *
  614. * This should be left at zero for this class, but subclasses
  615. * may want to set this to other values.
  616. */
  617. var $trailing_context_lines = 0;
  618. /**
  619. * Format a diff.
  620. *
  621. * @param $diff object A WikiDiff object.
  622. * @return string The formatted output.
  623. */
  624. function format($diff) {
  625. $xi = $yi = 1;
  626. $block = false;
  627. $context = array();
  628. $nlead = $this->leading_context_lines;
  629. $ntrail = $this->trailing_context_lines;
  630. $this->_start_diff();
  631. foreach ($diff->edits as $edit) {
  632. if ($edit->type == 'copy') {
  633. if (is_array($block)) {
  634. if (sizeof($edit->orig) <= $nlead + $ntrail) {
  635. $block[] = $edit;
  636. }
  637. else{
  638. if ($ntrail) {
  639. $context = array_slice($edit->orig, 0, $ntrail);
  640. $block[] = new _WikiWikiDiffOp_Copy($context);
  641. }
  642. $this->_block($x0, $ntrail + $xi - $x0,
  643. $y0, $ntrail + $yi - $y0,
  644. $block);
  645. $block = false;
  646. }
  647. }
  648. $context = $edit->orig;
  649. }
  650. else {
  651. if (! is_array($block)) {
  652. $context = array_slice($context, sizeof($context) - $nlead);
  653. $x0 = $xi - sizeof($context);
  654. $y0 = $yi - sizeof($context);
  655. $block = array();
  656. if ($context)
  657. $block[] = new _WikiWikiDiffOp_Copy($context);
  658. }
  659. $block[] = $edit;
  660. }
  661. if ($edit->orig)
  662. $xi += sizeof($edit->orig);
  663. if ($edit->closing)
  664. $yi += sizeof($edit->closing);
  665. }
  666. if (is_array($block))
  667. $this->_block($x0, $xi - $x0,
  668. $y0, $yi - $y0,
  669. $block);
  670. return $this->_end_diff();
  671. }
  672. function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
  673. $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
  674. foreach ($edits as $edit) {
  675. if ($edit->type == 'copy')
  676. $this->_context($edit->orig);
  677. elseif ($edit->type == 'add')
  678. $this->_added($edit->closing);
  679. elseif ($edit->type == 'delete')
  680. $this->_deleted($edit->orig);
  681. elseif ($edit->type == 'change')
  682. $this->_changed($edit->orig, $edit->closing);
  683. else
  684. trigger_error("Unknown edit type", E_USER_ERROR);
  685. }
  686. $this->_end_block();
  687. }
  688. function _start_diff() {
  689. ob_start();
  690. }
  691. function _end_diff() {
  692. $val = ob_get_contents();
  693. ob_end_clean();
  694. return $val;
  695. }
  696. function _block_header($xbeg, $xlen, $ybeg, $ylen) {
  697. if ($xlen > 1)
  698. $xbeg .= "," . ($xbeg + $xlen - 1);
  699. if ($ylen > 1)
  700. $ybeg .= "," . ($ybeg + $ylen - 1);
  701. return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
  702. }
  703. function _start_block($header) {
  704. echo $header;
  705. }
  706. function _end_block() {
  707. }
  708. function _lines($lines, $prefix = ' ') {
  709. foreach ($lines as $line)
  710. echo "$prefix $line\n";
  711. }
  712. function _context($lines) {
  713. $this->_lines($lines);
  714. }
  715. function _added($lines) {
  716. $this->_lines($lines, ">");
  717. }
  718. function _deleted($lines) {
  719. $this->_lines($lines, "<");
  720. }
  721. function _changed($orig, $closing) {
  722. $this->_deleted($orig);
  723. echo "---\n";
  724. $this->_added($closing);
  725. }
  726. }
  727. /**
  728. * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
  729. *
  730. */
  731. define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
  732. class _WikiHWLDF_WordAccumulator {
  733. function _WikiHWLDF_WordAccumulator () {
  734. $this->_lines = array();
  735. $this->_line = '';
  736. $this->_group = '';
  737. $this->_tag = '';
  738. }
  739. function _flushGroup ($new_tag) {
  740. if ($this->_group !== '') {
  741. if ($this->_tag == 'mark')
  742. $this->_line .= '<span class="diffchange">'.$this->_group.'</span>';
  743. else
  744. $this->_line .= $this->_group;
  745. }
  746. $this->_group = '';
  747. $this->_tag = $new_tag;
  748. }
  749. function _flushLine ($new_tag) {
  750. $this->_flushGroup($new_tag);
  751. if ($this->_line != '')
  752. $this->_lines[] = $this->_line;
  753. $this->_line = '';
  754. }
  755. function addWords ($words, $tag = '') {
  756. if ($tag != $this->_tag)
  757. $this->_flushGroup($tag);
  758. foreach ($words as $word) {
  759. // new-line should only come as first char of word.
  760. if ($word == '')
  761. continue;
  762. if ($word[0] == "\n") {
  763. $this->_group .= NBSP;
  764. $this->_flushLine($tag);
  765. $word = substr($word, 1);
  766. }
  767. assert(!strstr($word, "\n"));
  768. $this->_group .= $word;
  769. }
  770. }
  771. function getLines() {
  772. $this->_flushLine('~done');
  773. return $this->_lines;
  774. }
  775. }
  776. class WordLevelWikiDiff extends MappedWikiDiff
  777. {
  778. function WordLevelWikiDiff ($orig_lines, $closing_lines) {
  779. list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
  780. list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
  781. $this->MappedWikiDiff($orig_words, $closing_words,
  782. $orig_stripped, $closing_stripped);
  783. }
  784. function _split($lines) {
  785. // FIXME: fix POSIX char class.
  786. # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
  787. if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
  788. implode("\n", $lines),
  789. $m)) {
  790. return array(array(''), array(''));
  791. }
  792. return array($m[0], $m[1]);
  793. }
  794. function orig () {
  795. $orig = new _WikiHWLDF_WordAccumulator;
  796. foreach ($this->edits as $edit) {
  797. if ($edit->type == 'copy')
  798. $orig->addWords($edit->orig);
  799. elseif ($edit->orig)
  800. $orig->addWords($edit->orig, 'mark');
  801. }
  802. return $orig->getLines();
  803. }
  804. function closing () {
  805. $closing = new _WikiHWLDF_WordAccumulator;
  806. foreach ($this->edits as $edit) {
  807. if ($edit->type == 'copy')
  808. $closing->addWords($edit->closing);
  809. elseif ($edit->closing)
  810. $closing->addWords($edit->closing, 'mark');
  811. }
  812. return $closing->getLines();
  813. }
  814. }
  815. /**
  816. * @TODO: Doc this class
  817. */
  818. class TableWikiDiffFormatter extends WikiDiffFormatter
  819. {
  820. var $htmltable = array();
  821. function TableWikiDiffFormatter() {
  822. $this->leading_context_lines = 2;
  823. $this->trailing_context_lines = 2;
  824. }
  825. function _block_header( $xbeg, $xlen, $ybeg, $ylen) {
  826. }
  827. function _start_block ($header) {
  828. }
  829. function _end_block() {
  830. }
  831. function _lines($lines, $prefix=' ', $color="white") {
  832. }
  833. function _added($lines) {
  834. global $htmltable;
  835. foreach ($lines as $line) {
  836. $htmltable[] = array('','+','<div class="wiki_diffadd">'.$line.'</div>');
  837. }
  838. }
  839. function _deleted($lines) {
  840. global $htmltable;
  841. foreach ($lines as $line) {
  842. $htmltable[] = array('<div class="wiki_diffdel">'.$line.'</div>','-','');
  843. }
  844. }
  845. function _context($lines) {
  846. global $htmltable;
  847. foreach ($lines as $line) {
  848. $htmltable[] = array($line,'',$line);
  849. }
  850. }
  851. function _changed( $orig, $closing ) {
  852. global $htmltable;
  853. $diff = new WordLevelWikiDiff( $orig, $closing );
  854. $del = $diff->orig();
  855. $add = $diff->closing();
  856. while ( $line = array_shift( $del ) ) {
  857. $aline = array_shift( $add );
  858. $htmltable[] = array('<div class="wiki_diffdel">'.$line.'</div>','-','<div class="wiki_diffadd">'.$aline.'</div>');
  859. }
  860. $this->_added( $add ); # If any leftovers
  861. }
  862. function get_result() {
  863. global $htmltable;
  864. return $htmltable;
  865. }
  866. }
  867. /**
  868. * Wikipedia Table style diff formatter.
  869. *
  870. */
  871. class TableWikiDiffFormatterOld extends WikiDiffFormatter
  872. {
  873. function TableWikiDiffFormatter() {
  874. $this->leading_context_lines = 2;
  875. $this->trailing_context_lines = 2;
  876. }
  877. function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
  878. $l1 = wfMsg( "lineno", $xbeg );
  879. $l2 = wfMsg( "lineno", $ybeg );
  880. $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
  881. '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
  882. return $r;
  883. }
  884. function _start_block( $header ) {
  885. global $wgOut;
  886. $wgOut->addHTML( $header );
  887. }
  888. function _end_block() {
  889. }
  890. function _lines( $lines, $prefix=' ', $color="white" ) {
  891. }
  892. function addedLine( $line ) {
  893. return '<td>+</td><td class="diff-addedline">' .
  894. $line.'</td>';
  895. }
  896. function deletedLine( $line ) {
  897. return '<td>-</td><td class="diff-deletedline">' .
  898. $line.'</td>';
  899. }
  900. function emptyLine() {
  901. return '<td colspan="2">&nbsp;</td>';
  902. }
  903. function contextLine( $line ) {
  904. return '<td> </td><td class="diff-context">'.$line.'</td>';
  905. }
  906. function _added($lines) {
  907. global $wgOut;
  908. foreach ($lines as $line) {
  909. $wgOut->addHTML( '<tr>' . $this->emptyLine() .
  910. $this->addedLine( $line ) . "</tr>\n" );
  911. }
  912. }
  913. function _deleted($lines) {
  914. global $wgOut;
  915. foreach ($lines as $line) {
  916. $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
  917. $this->emptyLine() . "</tr>\n" );
  918. }
  919. }
  920. function _context( $lines ) {
  921. global $wgOut;
  922. foreach ($lines as $line) {
  923. $wgOut->addHTML( '<tr>' . $this->contextLine( $line ) .
  924. $this->contextLine( $line ) . "</tr>\n" );
  925. }
  926. }
  927. function _changed( $orig, $closing ) {
  928. global $wgOut;
  929. $diff = new WordLevelWikiDiff( $orig, $closing );
  930. $del = $diff->orig();
  931. $add = $diff->closing();
  932. while ( $line = array_shift( $del ) ) {
  933. $aline = array_shift( $add );
  934. $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
  935. $this->addedLine( $aline ) . "</tr>\n" );
  936. }
  937. $this->_added( $add ); # If any leftovers
  938. }
  939. }