forked from nuxodin/diff_match_patch-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff_match_patch.php
2117 lines (2006 loc) · 69.5 KB
/
diff_match_patch.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* php port by Tobias Buschor shwups.ch
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Computes the difference between two texts to create a patch.
* Applies the patch onto another text, allowing for errors.
* @author [email protected] (Neil Fraser)
*/
/**
* Class containing the diff, match and patch methods.
* @constructor
*/
class diff_match_patch {
// Defaults.
// Redefine these in your program to override the defaults.
// Number of seconds to map a diff before giving up (0 for infinity).
public $Diff_Timeout = 1.0;
// Cost of an empty edit operation in terms of edit characters.
public $Diff_EditCost = 4;
// The size beyond which the double-ended diff activates.
// Double-ending is twice as fast, but less accurate.
public $Diff_DualThreshold = 32;
// At what point is no match declared (0.0 = perfection, 1.0 = very loose).
public $Match_Threshold = 0.5;
// How far to search for a match (0 = exact location, 1000+ = broad match).
// A match this many characters away from the expected location will add
// 1.0 to the score (0.0 is a perfect match).
public $Match_Distance = 1000;
// When deleting a large block of text (over ~64 characters), how close does
// the contents have to match the expected contents. (0.0 = perfection,
// 1.0 = very loose). Note that Match_Threshold controls how closely the
// end points of a delete need to match.
public $Patch_DeleteThreshold = 0.5;
// Chunk size for context length.
public $Patch_Margin = 4;
/**
* Compute the number of bits in an int.
* The normal answer for JavaScript is 32.
* @return {number} Max bits
function getMaxBits() {
var maxbits = 0;
var oldi = 1;
var newi = 2;
while (oldi != newi) {
maxbits++;
oldi = newi;
newi = newi << 1;
}
return maxbits;
}
// How many bits in a number?
this.Match_MaxBits = getMaxBits();
*/
// DIFF FUNCTIONS
/**
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} opt_checklines Optional speedup flag. If present and false,
* then don't run a line-level diff first to identify the changed areas.
* Defaults to true, which does a faster, slightly less optimal diff
* @return {Array.<Array.<number|string>>} Array of diff tuples.
*/
function diff_main($text1, $text2, $checklines = true) {
// Check for equality (speedup)
if ($text1 === $text2) {
return array ( array ( DIFF_EQUAL, $text1) );
}
// Trim off common prefix (speedup)
$commonlength = $this->diff_commonPrefix($text1, $text2);
$commonprefix = mb_substr($text1, 0, $commonlength);
$text1 = mb_substr($text1, $commonlength);
$text2 = mb_substr($text2, $commonlength);
// Trim off common suffix (speedup)
$commonlength = $this->diff_commonSuffix($text1, $text2);
$commonsuffix = mb_substr($text1, mb_strlen($text1) - $commonlength);
$text1 = mb_substr($text1, 0, mb_strlen($text1) - $commonlength);
$text2 = mb_substr($text2, 0, mb_strlen($text2) - $commonlength);
// Compute the diff on the middle block
$diffs = $this->diff_compute($text1, $text2, $checklines);
// Restore the prefix and suffix
if ($commonprefix !== '') {
array_unshift($diffs, array ( DIFF_EQUAL, $commonprefix ));
}
if ($commonsuffix !== '') {
array_push($diffs, array ( DIFF_EQUAL, $commonsuffix ));
}
$this->diff_cleanupMerge($diffs);
return $diffs;
}
/**
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster, slightly less optimal diff
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
*/
function diff_compute($text1, $text2, $checklines) {
if ($text1 === '') {
// Just add some text (speedup)
return array ( array ( DIFF_INSERT, $text2 ) );
}
if ($text2 === '') {
// Just delete some text (speedup)
return array ( array ( DIFF_DELETE, $text1 ) );
}
$longtext = mb_strlen($text1) > mb_strlen($text2) ? $text1 : $text2;
$shorttext = mb_strlen($text1) > mb_strlen($text2) ? $text2 : $text1;
$i = mb_strpos($longtext, $shorttext);
if ($i !== false) {
// Shorter text is inside the longer text (speedup)
$diffs = array (
array ( DIFF_INSERT, mb_substr($longtext, 0, $i) ),
array ( DIFF_EQUAL, $shorttext ),
array ( DIFF_INSERT, mb_substr($longtext, $i +mb_strlen($shorttext)) )
);
// Swap insertions for deletions if diff is reversed.
if (mb_strlen($text1) > mb_strlen($text2)) {
$diffs[0][0] = $diffs[2][0] = DIFF_DELETE;
}
return $diffs;
}
$longtext = $shorttext = null; // Garbage collect
// Check to see if the problem can be split in two.
$hm = $this->diff_halfMatch($text1, $text2);
if ($hm) {
// A half-match was found, sort out the return data.
$text1_a = $hm[0];
$text1_b = $hm[1];
$text2_a = $hm[2];
$text2_b = $hm[3];
$mid_common = $hm[4];
// Send both pairs off for separate processing.
$diffs_a = $this->diff_main($text1_a, $text2_a, $checklines);
$diffs_b = $this->diff_main($text1_b, $text2_b, $checklines);
// Merge the results.
return array_merge($diffs_a, array (
array (
DIFF_EQUAL,
$mid_common
)
), $diffs_b);
}
// Perform a real diff.
if ($checklines && (mb_strlen($text1) < 100 || mb_strlen($text2) < 100)) {
// Too trivial for the overhead.
$checklines = false;
}
$linearray = null;
if ($checklines) {
// Scan the text on a line-by-line basis first.
$a = $this->diff_linesToChars($text1, $text2);
$text1 = $a[0];
$text2 = $a[1];
$linearray = $a[2];
}
$diffs = $this->diff_map($text1, $text2);
if (!$diffs) {
// No acceptable result.
$diffs = array (
array (
DIFF_DELETE,
$text1
),
array (
DIFF_INSERT,
$text2
)
);
}
if ($checklines) {
// Convert the diff back to original text.
$this->diff_charsToLines($diffs, $linearray);
// Eliminate freak matches (e.g. blank lines)
$this->diff_cleanupSemantic($diffs);
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
array_push($diffs, array (
DIFF_EQUAL,
''
));
$pointer = 0;
$count_delete = 0;
$count_insert = 0;
$text_delete = '';
$text_insert = '';
while ($pointer < count($diffs)) {
switch ($diffs[$pointer][0]) {
case DIFF_INSERT :
$count_insert++;
$text_insert .= $diffs[$pointer][1];
break;
case DIFF_DELETE :
$count_delete++;
$text_delete .= $diffs[$pointer][1];
break;
case DIFF_EQUAL :
// Upon reaching an equality, check for prior redundancies.
if ($count_delete >= 1 && $count_insert >= 1) {
// Delete the offending records and add the merged ones.
$a = $this->diff_main($text_delete, $text_insert, false);
array_splice($diffs, $pointer - $count_delete - $count_insert, $count_delete + $count_insert);
$pointer = $pointer - $count_delete - $count_insert;
for ($j = count($a) - 1; $j >= 0; $j--) {
array_splice($diffs, $pointer, 0, array($a[$j]));
}
$pointer = $pointer +count($a);
}
$count_insert = 0;
$count_delete = 0;
$text_delete = '';
$text_insert = '';
break;
}
$pointer++;
}
array_pop($diffs); // Remove the dummy entry at the end.
}
return $diffs;
}
/**
* Split two texts into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {Array.<string|Array.<string>>} Three element Array, containing the
* encoded text1, the encoded text2 and the array of unique strings. The
* zeroth element of the array of unique strings is intentionally blank.
* @private
*/
function diff_linesToChars($text1, $text2) {
$lineArray = array(); // e.g. lineArray[4] == 'Hello\n'
$lineHash = array(); // e.g. lineHash['Hello\n'] == 4
// '\x00' is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a null character.
$lineArray[0] = '';
$chars1 = $this->diff_linesToCharsMunge($text1, $lineArray, $lineHash);
$chars2 = $this->diff_linesToCharsMunge($text2, $lineArray, $lineHash);
return array (
$chars1,
$chars2,
$lineArray
);
}
/**
* Split a text into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* Modifies linearray and linehash through being a closure.
* @param {string} text String to encode
* @return {string} Encoded string
* @private
*/
function diff_linesToCharsMunge($text, &$lineArray, &$lineHash) {
$chars = '';
// Walk the text, pulling out a mb_substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
$lineStart = 0;
$lineEnd = -1;
// Keeping our own length variable is faster than looking it up.
$lineArrayLength = count($lineArray);
while ($lineEnd < mb_strlen($text) - 1) {
$lineEnd = mb_strpos($text, "\n", $lineStart);
if ($lineEnd === false) {
$lineEnd = mb_strlen($text) - 1;
}
$line = mb_substr($text, $lineStart, $lineEnd +1 -$lineStart);
$lineStart = $lineEnd +1;
if ( isset($lineHash[$line]) ) {
$chars .= mb_chr($lineHash[$line]);
} else {
$chars .= mb_chr($lineArrayLength);
$lineHash[$line] = $lineArrayLength;
$lineArray[$lineArrayLength++] = $line;
}
}
return $chars;
}
/**
* Rehydrate the text in a diff from a string of line hashes to real lines of
* text.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @param {Array.<string>} lineArray Array of unique strings.
* @private
*/
function diff_charsToLines(&$diffs, $lineArray) {
for ($x = 0; $x < count($diffs); $x++) {
$chars = $diffs[$x][1];
$text = array ();
for ($y = 0; $y < mb_strlen($chars); $y++) {
$text[$y] = $lineArray[charCodeAt($chars, $y)];
}
$diffs[$x][1] = implode('',$text);
}
}
/**
* Explore the intersection points between the two texts.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @return {Array.<Array.<number|string>>?} Array of diff tuples or null if no
* diff available.
* @private
*/
function diff_map($text1, $text2) {
// Don't run for too long.
$ms_end = microtime(true) + $this->Diff_Timeout;
// Cache the text lengths to prevent multiple calls.
$text1_length = mb_strlen($text1);
$text2_length = mb_strlen($text2);
$max_d = $text1_length + $text2_length -1;
$doubleEnd = $this->Diff_DualThreshold * 2 < $max_d;
$v_map1 = array();
$v_map2 = array();
$v1 = array();
$v2 = array();
$v1[1] = 0;
$v2[1] = 0;
$x = null;
$y = null;
$footstep = null; // Used to track overlapping paths.
$footsteps = array();
$done = false;
// Safari 1.x doesn't have hasOwnProperty
//? $hasOwnProperty = !!(footsteps.hasOwnProperty);
// If the total number of characters is odd, then the front path will collide
// with the reverse path.
$front = ($text1_length + $text2_length) % 2;
for ($d = 0; $d < $max_d; $d++) {
// Bail out if timeout reached.
if ($this->Diff_Timeout > 0 && microtime(true) > $ms_end) {
return null; // zzz
}
// Walk the front path one step.
$v_map1[$d] = array ();
for ($k = -$d; $k <= $d; $k += 2) {
if ($k == -$d || $k != $d && $v1[$k -1] < $v1[$k +1]) {
$x = $v1[$k +1];
} else {
$x = $v1[$k -1] + 1;
}
$y = $x - $k;
if ($doubleEnd) {
$footstep = $x . ',' . $y;
if ($front && isset ($footsteps[$footstep])) {
$done = true;
}
if (!$front) {
$footsteps[$footstep] = $d;
}
}
while (!$done && ($x < $text1_length) && ($y < $text2_length) && (mb_substr($text1, $x, 1) == mb_substr($text2, $y, 1)) ) {
$x++;
$y++;
if ($doubleEnd) {
$footstep = $x . ',' . $y;
if ($front && isset ($footsteps[$footstep])) {
$done = true;
}
if (!$front) {
$footsteps[$footstep] = $d;
}
}
}
$v1[$k] = $x;
$v_map1[$d][$x . ',' . $y] = true;
if ($x == $text1_length && $y == $text2_length) {
// Reached the end in single-path mode.
return $this->diff_path1($v_map1, $text1, $text2);
}
elseif ($done) {
// Front path ran over reverse path.
$v_map2 = array_slice($v_map2, 0, $footsteps[$footstep] + 1);
$a = $this->diff_path1($v_map1, mb_substr($text1, 0, $x), mb_substr($text2, 0, $y));
return array_merge($a, $this->diff_path2($v_map2, mb_substr($text1, $x), mb_substr($text2, $y)));
}
}
if ($doubleEnd) {
// Walk the reverse path one step.
$v_map2[$d] = array();
for ($k = -$d; $k <= $d; $k += 2) {
if ($k == -$d || $k != $d && $v2[$k -1] < $v2[$k +1]) {
$x = $v2[$k +1];
} else {
$x = $v2[$k -1] + 1;
}
$y = $x - $k;
$footstep = ($text1_length - $x) . ',' . ($text2_length - $y);
if (!$front && isset ($footsteps[$footstep])) {
$done = true;
}
if ($front) {
$footsteps[$footstep] = $d;
}
while (!$done && $x < $text1_length && $y < $text2_length && mb_substr($text1, $text1_length - $x -1, 1) == mb_substr($text2, $text2_length - $y -1, 1) ) {
$x++;
$y++;
$footstep = ($text1_length - $x) . ',' . ($text2_length - $y);
if (!$front && isset ($footsteps[$footstep])) {
$done = true;
}
if ($front) {
$footsteps[$footstep] = $d;
}
}
$v2[$k] = $x;
$v_map2[$d][$x . ',' . $y] = true;
if ($done) {
// Reverse path ran over front path.
$v_map1 = array_slice($v_map1, 0, $footsteps[$footstep] + 1);
$a = $this->diff_path1($v_map1, mb_substr($text1, 0, $text1_length - $x), mb_substr($text2, 0, $text2_length - $y));
return array_merge($a, $this->diff_path2($v_map2, mb_substr($text1, $text1_length - $x), mb_substr($text2, $text2_length - $y)));
}
}
}
}
// Number of diffs equals number of characters, no commonality at all.
return null;
}
/**
* Work from the middle back to the start to determine the path.
* @param {Array.<Object>} v_map Array of paths.ers
* @param {string} text1 Old string fragment to be diffed.
* @param {string} text2 New string fragment to be diffed.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
*/
function diff_path1($v_map, $text1, $text2) {
$path = array ();
$x = mb_strlen($text1);
$y = mb_strlen($text2);
/** @type {number?} */
$last_op = null;
for ($d = count($v_map) - 2; $d >= 0; $d--) {
while (1) {
if (isset ($v_map[$d][($x -1) . ',' . $y])) {
$x--;
if ($last_op === DIFF_DELETE) {
$path[0][1] = mb_substr($text1, $x, 1) . $path[0][1];
} else {
array_unshift($path, array (
DIFF_DELETE,
mb_substr($text1, $x, 1)
));
}
$last_op = DIFF_DELETE;
break;
} elseif (isset ($v_map[$d][$x . ',' . ($y -1)])) {
$y--;
if ($last_op === DIFF_INSERT) {
$path[0][1] = mb_substr($text2, $y, 1) . $path[0][1];
} else {
array_unshift($path, array (
DIFF_INSERT,
mb_substr($text2, $y, 1)
));
}
$last_op = DIFF_INSERT;
break;
} else {
$x--;
$y--;
//if (text1.charAt(x) != text2.charAt(y)) {
// throw new Error('No diagonal. Can\'t happen. (diff_path1)');
//}
if ($last_op === DIFF_EQUAL) {
$path[0][1] = mb_substr($text1, $x, 1) . $path[0][1];
} else {
array_unshift($path, array (
DIFF_EQUAL,
mb_substr($text1, $x, 1)
));
}
$last_op = DIFF_EQUAL;
}
}
}
return $path;
}
/**
* Work from the middle back to the end to determine the path.
* @param {Array.<Object>} v_map Array of paths.
* @param {string} text1 Old string fragment to be diffed.
* @param {string} text2 New string fragment to be diffed.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
*/
function diff_path2($v_map, $text1, $text2) {
$path = array ();
$pathLength = 0;
$x = mb_strlen($text1);
$y = mb_strlen($text2);
/** @type {number?} */
$last_op = null;
for ($d = count($v_map) - 2; $d >= 0; $d--) {
while (1) {
if (isset ($v_map[$d][($x -1) . ',' . $y])) {
$x--;
if ($last_op === DIFF_DELETE) {
$path[$pathLength -1][1] .= $text1[mb_strlen($text1) - $x -1];
} else {
$path[$pathLength++] = array (
DIFF_DELETE,
$text1[mb_strlen($text1) - $x -1]
);
}
$last_op = DIFF_DELETE;
break;
}
elseif (isset ($v_map[$d][$x . ',' . ($y -1)])) {
$y--;
if ($last_op === DIFF_INSERT) {
$path[$pathLength -1][1] .= $text2[mb_strlen($text2) - $y -1];
} else {
$path[$pathLength++] = array (
DIFF_INSERT,
$text2[mb_strlen($text2) - $y -1]
);
}
$last_op = DIFF_INSERT;
break;
} else {
$x--;
$y--;
//if (text1.charAt(text1.length - x - 1) !=
// text2.charAt(text2.length - y - 1)) {
// throw new Error('No diagonal. Can\'t happen. (diff_path2)');
//}
if ($last_op === DIFF_EQUAL) {
$path[$pathLength -1][1] .= $text1[mb_strlen($text1) - $x -1];
} else {
$path[$pathLength++] = array (
DIFF_EQUAL,
$text1[mb_strlen($text1) - $x -1]
);
}
$last_op = DIFF_EQUAL;
}
}
}
return $path;
}
/**
* Determine the common prefix of two strings
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
*/
function diff_commonPrefix($text1, $text2) {
for ($i = 0; 1; $i++) {
$t1 = mb_substr($text1, $i, 1);
$t2 = mb_substr($text2, $i, 1);
if($t1==='' || $t2==='' || $t1 !== $t2 ){
return $i;
}
}
}
/**
* Determine the common suffix of two strings
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
*/
function diff_commonSuffix($text1, $text2) {
return $this->diff_commonPrefix( strrev($text1), strrev($text2) );
}
/**
* Do the two texts share a mb_substring which is at least half the length of the
* longer text?
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {Array.<string>?} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or null if there was no match.
*/
function diff_halfMatch($text1, $text2) {
$longtext = mb_strlen($text1) > mb_strlen($text2) ? $text1 : $text2;
$shorttext = mb_strlen($text1) > mb_strlen($text2) ? $text2 : $text1;
if (mb_strlen($longtext) < 10 || mb_strlen($shorttext) < 1) {
return null; // Pointless.
}
// First check if the second quarter is the seed for a half-match.
$hm1 = $this->diff_halfMatchI($longtext, $shorttext, ceil(mb_strlen($longtext) / 4));
// Check again based on the third quarter.
$hm2 = $this->diff_halfMatchI($longtext, $shorttext, ceil(mb_strlen($longtext) / 2));
if (!$hm1 && !$hm2) {
return null;
} elseif (!$hm2) {
$hm = $hm1;
} elseif (!$hm1) {
$hm = $hm2;
} else {
// Both matched. Select the longest.
$hm = mb_strlen($hm1[4]) > mb_strlen($hm2[4]) ? $hm1 : $hm2;
}
// A half-match was found, sort out the return data.
if (mb_strlen($text1) > mb_strlen($text2)) {
$text1_a = $hm[0];
$text1_b = $hm[1];
$text2_a = $hm[2];
$text2_b = $hm[3];
} else {
$text2_a = $hm[0];
$text2_b = $hm[1];
$text1_a = $hm[2];
$text1_b = $hm[3];
}
$mid_common = $hm[4];
return array( $text1_a, $text1_b, $text2_a, $text2_b, $mid_common );
}
/**
* Does a mb_substring of shorttext exist within longtext such that the mb_substring
* is at least half the length of longtext?
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length mb_substring within longtext
* @return {Array.<string>?} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or null if there was no match.
* @private
*/
function diff_halfMatchI($longtext, $shorttext, $i) {
// Start with a 1/4 length mb_substring at position i as a seed.
$seed = mb_substr($longtext, $i, floor(mb_strlen($longtext) / 4));
$j = -1;
$best_common = '';
$best_longtext_a = null;
$best_longtext_b = null;
$best_shorttext_a = null;
$best_shorttext_b = null;
while ( ($j = mb_strpos($shorttext, $seed, $j + 1)) !== false ) {
$prefixLength = $this->diff_commonPrefix(mb_substr($longtext, $i), mb_substr($shorttext, $j));
$suffixLength = $this->diff_commonSuffix(mb_substr($longtext, 0, $i), mb_substr($shorttext, 0, $j));
if (mb_strlen($best_common) < $suffixLength + $prefixLength) {
$best_common = mb_substr($shorttext, $j - $suffixLength, $suffixLength) . mb_substr($shorttext, $j, $prefixLength);
$best_longtext_a = mb_substr($longtext, 0, $i - $suffixLength);
$best_longtext_b = mb_substr($longtext, $i + $prefixLength);
$best_shorttext_a = mb_substr($shorttext, 0, $j - $suffixLength);
$best_shorttext_b = mb_substr($shorttext, $j + $prefixLength);
}
}
if (mb_strlen($best_common) >= mb_strlen($longtext) / 2) {
return array (
$best_longtext_a,
$best_longtext_b,
$best_shorttext_a,
$best_shorttext_b,
$best_common
);
} else {
return null;
}
}
/**
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
*/
function diff_cleanupSemantic(&$diffs) {
$changes = false;
$equalities = array (); // Stack of indices where equalities are found.
$equalitiesLength = 0; // Keeping our own length var is faster in JS.
$lastequality = null; // Always equal to equalities[equalitiesLength-1][1]
$pointer = 0; // Index of current position.
// Number of characters that changed prior to the equality.
$length_changes1 = 0;
// Number of characters that changed after the equality.
$length_changes2 = 0;
while ($pointer < count($diffs)) {
if ($diffs[$pointer][0] == DIFF_EQUAL) { // equality found
$equalities[$equalitiesLength++] = $pointer;
$length_changes1 = $length_changes2;
$length_changes2 = 0;
$lastequality = $diffs[$pointer][1];
} else { // an insertion or deletion
$length_changes2 += mb_strlen($diffs[$pointer][1]);
if ($lastequality !== null && (mb_strlen($lastequality) <= $length_changes1) && (mb_strlen($lastequality) <= $length_changes2)) {
// Duplicate record
$zzz_diffs = array_splice($diffs, $equalities[$equalitiesLength -1], 0, array(array (
DIFF_DELETE,
$lastequality
)));
// Change second copy to insert.
$diffs[$equalities[$equalitiesLength -1] + 1][0] = DIFF_INSERT;
// Throw away the equality we just deleted.
$equalitiesLength--;
// Throw away the previous equality (it needs to be reevaluated).
$equalitiesLength--;
$pointer = $equalitiesLength > 0 ? $equalities[$equalitiesLength -1] : -1;
$length_changes1 = 0; // Reset the counters.
$length_changes2 = 0;
$lastequality = null;
$changes = true;
}
}
$pointer++;
}
if ($changes) {
$this->diff_cleanupMerge($diffs);
}
$this->diff_cleanupSemanticLossless($diffs);
}
/**
* Look for single edits surrounded on both sides by equalities
* which can be shifted sideways to align the edit to a word boundary.
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
*/
function diff_cleanupSemanticLossless(&$diffs) {
$pointer = 1;
// Intentionally ignore the first and last element (don't need checking).
while ($pointer < count($diffs) - 1) {
if ($diffs[$pointer -1][0] == DIFF_EQUAL && $diffs[$pointer +1][0] == DIFF_EQUAL) {
// This is a single edit surrounded by equalities.
$equality1 = $diffs[$pointer -1][1];
$edit = $diffs[$pointer][1];
$equality2 = $diffs[$pointer +1][1];
// First, shift the edit as far left as possible.
$commonOffset = $this->diff_commonSuffix($equality1, $edit);
if ($commonOffset !== '') {
$commonString = mb_substr($edit, mb_strlen($edit) - $commonOffset);
$equality1 = mb_substr($equality1, 0, mb_strlen($equality1) - $commonOffset);
$edit = $commonString . mb_substr($edit, 0, mb_strlen($edit) - $commonOffset);
$equality2 = $commonString . $equality2;
}
// Second, step character by character right, looking for the best fit.
$bestEquality1 = $equality1;
$bestEdit = $edit;
$bestEquality2 = $equality2;
$bestScore = $this->diff_cleanupSemanticScore($equality1, $edit) + $this->diff_cleanupSemanticScore($edit, $equality2);
while (isset($equality2[0]) && $edit[0] === $equality2[0]) {
$equality1 .= $edit[0];
$edit = mb_substr($edit, 1) . $equality2[0];
$equality2 = mb_substr($equality2, 1);
$score = $this->diff_cleanupSemanticScore($equality1, $edit) + $this->diff_cleanupSemanticScore($edit, $equality2);
// The >= encourages trailing rather than leading whitespace on edits.
if ($score >= $bestScore) {
$bestScore = $score;
$bestEquality1 = $equality1;
$bestEdit = $edit;
$bestEquality2 = $equality2;
}
}
if ($diffs[$pointer -1][1] != $bestEquality1) {
// We have an improvement, save it back to the diff.
if ($bestEquality1) {
$diffs[$pointer -1][1] = $bestEquality1;
} else {
$zzz_diffs = array_splice($diffs, $pointer -1, 1);
$pointer--;
}
$diffs[$pointer][1] = $bestEdit;
if ($bestEquality2) {
$diffs[$pointer +1][1] = $bestEquality2;
} else {
$zzz_diffs = array_splice($diffs, $pointer +1, 1);
$pointer--;
}
}
}
$pointer++;
}
}
/**
* Given two strings, compute a score representing whether the internal
* boundary falls on logical boundaries.
* Scores range from 5 (best) to 0 (worst).
* Closure, makes reference to regex patterns defined above.
* @param {string} one First string
* @param {string} two Second string
* @return {number} The score.
*/
function diff_cleanupSemanticScore($one, $two) {
// Define some regex patterns for matching boundaries.
$punctuation = '/[^a-zA-Z0-9]/';
$whitespace = '/\s/';
$linebreak = '/[\r\n]/';
$blanklineEnd = '/\n\r?\n$/';
$blanklineStart = '/^\r?\n\r?\n/';
if (!$one || !$two) {
// Edges are the best.
return 5;
}
// Each port of this function behaves slightly differently due to
// subtle differences in each language's definition of things like
// 'whitespace'. Since this function's purpose is largely cosmetic,
// the choice has been made to use each language's native features
// rather than force total conformity.
$score = 0;
// One point for non-alphanumeric.
if (preg_match($punctuation, $one[mb_strlen($one) - 1]) || preg_match($punctuation, $two[0])) {
$score++;
// Two points for whitespace.
if (preg_match($whitespace, $one[mb_strlen($one) - 1] ) || preg_match($whitespace, $two[0])) {
$score++;
// Three points for line breaks.
if (preg_match($linebreak, $one[mb_strlen($one) - 1]) || preg_match($linebreak, $two[0])) {
$score++;
// Four points for blank lines.
if (preg_match($blanklineEnd, $one) || preg_match($blanklineStart, $two)) {
$score++;
}
}
}
}
return $score;
}
/**
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
*/
function diff_cleanupEfficiency(&$diffs) {
$changes = false;
$equalities = array (); // Stack of indices where equalities are found.
$equalitiesLength = 0; // Keeping our own length var is faster in JS.
$lastequality = ''; // Always equal to equalities[equalitiesLength-1][1]
$pointer = 0; // Index of current position.
// Is there an insertion operation before the last equality.
$pre_ins = false;
// Is there a deletion operation before the last equality.
$pre_del = false;
// Is there an insertion operation after the last equality.
$post_ins = false;
// Is there a deletion operation after the last equality.
$post_del = false;
while ($pointer < count($diffs)) {
if ($diffs[$pointer][0] == DIFF_EQUAL) { // equality found
if (mb_strlen($diffs[$pointer][1]) < $this->Diff_EditCost && ($post_ins || $post_del)) {
// Candidate found.
$equalities[$equalitiesLength++] = $pointer;
$pre_ins = $post_ins;
$pre_del = $post_del;
$lastequality = $diffs[$pointer][1];
} else {
// Not a candidate, and can never become one.
$equalitiesLength = 0;
$lastequality = '';
}
$post_ins = $post_del = false;
} else { // an insertion or deletion
if ($diffs[$pointer][0] == DIFF_DELETE) {
$post_del = true;
} else {
$post_ins = true;
}
/*
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
*/
if ($lastequality && (($pre_ins && $pre_del && $post_ins && $post_del) || ((mb_strlen($lastequality) < $this->Diff_EditCost / 2) && ($pre_ins + $pre_del + $post_ins + $post_del) == 3))) {
// Duplicate record
$zzz_diffs = array_splice($diffs, $equalities[$equalitiesLength -1], 0, array(array (
DIFF_DELETE,
$lastequality
)));
// Change second copy to insert.
$diffs[$equalities[$equalitiesLength -1] + 1][0] = DIFF_INSERT;
$equalitiesLength--; // Throw away the equality we just deleted;
$lastequality = '';
if ($pre_ins && $pre_del) {
// No changes made which could affect previous entry, keep going.
$post_ins = $post_del = true;
$equalitiesLength = 0;
} else {
$equalitiesLength--; // Throw away the previous equality;
$pointer = $equalitiesLength > 0 ? $equalities[$equalitiesLength -1] : -1;
$post_ins = $post_del = false;
}
$changes = true;
}
}
$pointer++;
}
if ($changes) {
$this->diff_cleanupMerge($diffs);
}
}
/**
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
*/
function diff_cleanupMerge(&$diffs) {
array_push($diffs, array ( DIFF_EQUAL, '' )); // Add a dummy entry at the end.
$pointer = 0;
$count_delete = 0;
$count_insert = 0;
$text_delete = '';
$text_insert = '';
$commonlength = null;
while ($pointer < count($diffs)) {
switch ($diffs[$pointer][0]) {
case DIFF_INSERT :
$count_insert++;
$text_insert .= $diffs[$pointer][1];
$pointer++;
break;
case DIFF_DELETE :
$count_delete++;
$text_delete .= $diffs[$pointer][1];
$pointer++;
break;
case DIFF_EQUAL :
// Upon reaching an equality, check for prior redundancies.
if ($count_delete !== 0 || $count_insert !== 0) {
if ($count_delete !== 0 && $count_insert !== 0) {
// Factor out any common prefixies.
$commonlength = $this->diff_commonPrefix($text_insert, $text_delete);
if ($commonlength !== 0) {
if (($pointer - $count_delete - $count_insert) > 0 && $diffs[$pointer - $count_delete - $count_insert -1][0] == DIFF_EQUAL) {
$diffs[$pointer - $count_delete - $count_insert -1][1] .= mb_substr($text_insert, 0, $commonlength);
} else {
array_splice($diffs, 0, 0, array(array (
DIFF_EQUAL,
mb_substr($text_insert, 0, $commonlength)
)));
$pointer++;
}
$text_insert = mb_substr($text_insert, $commonlength);
$text_delete = mb_substr($text_delete, $commonlength);