DifferenceEngine.php 46 KB

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