Initial code import based on Amine's email 6/28/2016

master
Mahmoud Al-Qudsi 2016-07-04 10:04:24 -05:00
commit 8a81066ae0
488 changed files with 49069 additions and 0 deletions

@ -0,0 +1,135 @@
<?php
/*
Plugin Name: Visitors contributions
Plugin URI: http://codecanyon.net/user/Leavy
Description: A wordpress plugin that gives your visitors the possiblity to develop your website content by submiting new versions to your articles.
Version: 1.07
Author: Leavy
Author URI: http://codecanyon.net/user/Leavy
*/
class visitors_edits{
public function __construct() {
register_activation_hook( __FILE__, array($this,'install'));
add_action( 'admin_menu', array( $this, 'admin_pages' ) );
add_filter('the_content', array($this,'contentFilter'));
add_filter( 'query_vars', array($this,'query_vars') );
add_action( 'init',array($this,'init'));
add_action( 'parse_request',array($this,'parse_request'));
add_filter( 'mce_buttons', array($this,'tinymce_btns') );
add_filter( 'mce_external_plugins', array($this,'tinymce_scripts') );
add_action('admin_head', array($this,'admin_head') );
add_action('admin_init', array($this,'admin_init') );
}
public function admin_pages() {
add_menu_page('Visitors Contributions | Pending reviews','Visitors contributions','read','visitors_edits_main',array($this , 'main'),plugins_url("img/contribute.png",__FILE__),87);
add_submenu_page(null,"Visitors Contributions | Review","Review a contribution","read",'visitors_edits_approve',array($this,'approve'));
add_submenu_page("visitors_edits_main","Visitors Contributions | Settings","Settings","read",'visitors_edits_settings',array($this,'settings'));
}
public function admin_head(){
if(isset($_GET["page"]) && ($_GET["page"]==="visitors_edits_approve" || $_GET["page"]==="visitors_edits_main" || $_GET["page"]==="visitors_edits_settings")){
?>
<link rel="stylesheet" type="text/css" href="<?php echo plugins_url( '/css/app.css',__FILE__ );?>">
<?php
}
}
public function admin_init(){
add_editor_style(plugins_url( './css/tinymce.css',__FILE__ ));
}
public function main(){
require "inc/main.php";
}
public function approve(){
require 'inc/approve.php';
}
public function settings(){
require 'inc/settings.php';
}
public function contentFilter($content){
if(is_single()) {
$options=get_option( "visitors_edits_options", [
"propose_edit_link"=>"<p><a href='#post_link#'>Propose an edit</a></p>"
]);
global $post;
$new_content = str_replace("#post_link#", get_site_url().'/'.$post->post_name.'/suggestions', stripcslashes($options["propose_edit_link"]));
$content .= $new_content;
}
return $content;
}
public function install(){
//General Settings
delete_option("visitors_edits_options");
//Database Settings
global $wpdb;
$wpdb->show_errors();
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'visitors_edits';
$sql = "CREATE TABLE $table_name (
edit_id bigint(20) NOT NULL AUTO_INCREMENT,
edit_time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
visitor_name text DEFAULT '',
visitor_email text DEFAULT '',
visitor_comment longtext DEFAULT '',
edit_content longtext DEFAULT '',
post_id bigint(20),
post_content longtext DEFAULT '',
UNIQUE KEY (edit_id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
public function query_vars($query_vars){
$query_vars[] = 'visitors_edits_post_name';
return $query_vars;
}
public function init(){
add_rewrite_rule(
'(.*)?/suggestions/?$',
'index.php?visitors_edits_post_name=$matches[1]',
'top'
);
flush_rewrite_rules(true);
}
public function parse_request($request){
if( isset( $request->query_vars['visitors_edits_post_name'] ) ):
include( plugin_dir_path(__FILE__) . "/inc/editor.php" );
exit();
endif;
return $request;
}
public function tinymce_btns($buttons){
if(isset($_GET["page"]) && $_GET["page"]==="visitors_edits_approve"){
array_push($buttons,'|','visitors_edits_approve','visitors_edits_reject','visitors_edits_clean');
}
return $buttons;
}
public function tinymce_scripts($plugin_array){
$plugin_array['visitors_edits'] = plugins_url( 'js/approve.js',__FILE__ );
return $plugin_array;
}
static function scriptUrl($script){
return plugins_url( 'js/'.$script.'.js',__FILE__);
}
}
new visitors_edits();
use Caxy\HtmlDiff\HtmlDiff;
use PHPHtmlParser\Dom;
function visitors_editsDIFF($oldHtml,$newHtml){
require "vendor/autoload.php";
$htmlDiff = new HtmlDiff($oldHtml, $newHtml);
$htmlDiff->getConfig()->setGroupDiffs(false);
return $htmlDiff->build();
}
function visitors_editsDOM(){
return new Dom;
}
?>

@ -0,0 +1,178 @@
@import url("https://fonts.googleapis.com/css?family=Roboto:100,400,700");
/* line 3, ../sass/app.scss */
.visitors_edits_no_data {
text-align: center;
font-weight: bold;
font-size: 50px;
margin-top: 250px;
opacity: 0.3;
text-transform: uppercase;
display: none;
}
/* line 12, ../sass/app.scss */
.visitors_edits_pending {
padding: 15px;
}
/* line 14, ../sass/app.scss */
.visitors_edits_pending h1 {
font-weight: 100;
font-size: 20px;
}
/* line 22, ../sass/app.scss */
.visitors_flashMessage {
margin: 15px;
background: #fff;
padding: 10px 15px;
border-left: 6px solid #089D08;
color: #089D08;
font-size: 14px;
font-weight: 100;
}
/* line 30, ../sass/app.scss */
.visitors_flashMessage.danger {
color: #F6214E;
border-color: #F6214E;
}
/* line 36, ../sass/app.scss */
.visitors_edits_review_editor {
padding: 15px;
}
/* line 38, ../sass/app.scss */
.visitors_edits_review_editor h1 {
font-weight: 100;
font-size: 25px;
display: inline-block;
margin-right: 15px;
margin-bottom: 10px;
}
/* line 45, ../sass/app.scss */
.visitors_edits_review_editor .delete_edit {
transition-duration: 0.3s;
color: #F6214E;
text-decoration: none;
text-decoration: underline;
font-style: italic;
font-style: 12px;
opacity: 0.6;
}
/* line 53, ../sass/app.scss */
.visitors_edits_review_editor .delete_edit:hover {
opacity: 1;
}
/* line 57, ../sass/app.scss */
.visitors_edits_review_editor .edit_info, .visitors_edits_review_editor .edit_notify {
padding-left: 15px;
font-style: italic;
opacity: 0.8;
font-size: 14px;
}
/* line 62, ../sass/app.scss */
.visitors_edits_review_editor .edit_info .mail, .visitors_edits_review_editor .edit_notify .mail {
opacity: 0.6;
font-size: 12px;
}
/* line 67, ../sass/app.scss */
.visitors_edits_review_editor .edit_notify {
margin: 10px 0;
padding: 0;
}
/* line 70, ../sass/app.scss */
.visitors_edits_review_editor .edit_notify label {
display: block;
margin-bottom: 10px;
}
/* line 74, ../sass/app.scss */
.visitors_edits_review_editor .edit_notify #edit_notify_message {
font-family: "Roboto",sans-serif;
max-height: 100px;
min-height: 100px;
max-width: 100%;
min-width: 100%;
line-height: normal;
border: none;
border-bottom: 1px solid #DFDFDF;
font-size: 18px;
padding: 10px;
display: none;
}
/* line 85, ../sass/app.scss */
.visitors_edits_review_editor .edit_notify #edit_notify_message:focus {
outline: none;
border-bottom-width: 2px;
border-color: rgba(3, 133, 244, 0.7);
}
/* line 93, ../sass/app.scss */
.visitors_edits_review_editor .controls {
margin-top: 20px;
}
/* line 96, ../sass/app.scss */
.visitors_edits_review_editor .comment {
font-size: 14px;
margin: 0;
padding: 10px;
background: #fff;
border: 1px solid #999;
font-style: normal;
opacity: 1;
color: #000;
}
/* line 107, ../sass/app.scss */
.visitors_edits_admin {
font-family: "Roboto",sans-serif;
width: 70%;
margin: 50px auto;
background: #fff;
border: 1px solid #E2E2E2;
padding: 20px;
}
/* line 114, ../sass/app.scss */
.visitors_edits_admin h2 {
font-size: 25px;
font-weight: 100;
}
/* line 120, ../sass/app.scss */
.visitors_edits_admin .control label {
display: block;
font-weight: bold;
margin: 15px 0 0;
opacity: 0.9;
font-size: 13px;
}
/* line 127, ../sass/app.scss */
.visitors_edits_admin .control input[type="text"], .visitors_edits_admin .control .notif_message {
background: #F3F3F3;
outline: none;
padding: 0 10px;
height: 40px;
line-height: normal;
border: none;
border-bottom: 1px solid #DFDFDF;
width: 100%;
}
/* line 136, ../sass/app.scss */
.visitors_edits_admin .control input[type="text"]:focus, .visitors_edits_admin .control .notif_message:focus {
outline: none;
border-bottom-width: 2px;
border-color: rgba(3, 133, 244, 0.7);
}
/* line 142, ../sass/app.scss */
.visitors_edits_admin .control .notif_message {
min-height: 120px;
max-height: 120px;
padding: 10px;
min-width: 100%;
max-width: 100%;
line-height: normal;
}
/* line 150, ../sass/app.scss */
.visitors_edits_admin .control input[type="checkbox"] {
margin-right: 10px;
}
/* line 153, ../sass/app.scss */
.visitors_edits_admin .control .save_btn {
margin-top: 20px;
}

@ -0,0 +1,156 @@
@import url("https://fonts.googleapis.com/css?family=Roboto:100,400,700");
/* line 7, ../sass/editor.scss */
body {
font-family: "Roboto",sans-serif;
font-size: 18px;
color: #545454;
padding: 0;
margin: 0;
}
/* line 14, ../sass/editor.scss */
a {
text-decoration: none;
color: inherit;
}
/* line 18, ../sass/editor.scss */
* {
transition-duration: 0.3s;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
/* line 22, ../sass/editor.scss */
.header {
padding: 20px 60px;
background: #0385F4;
}
/* line 25, ../sass/editor.scss */
.header .header-title {
font-size: 50px;
font-weight: 100;
color: #fff;
opacity: 0.5;
}
/* line 31, ../sass/editor.scss */
.header .header-content {
font-weight: 100;
color: #fff;
text-align: right;
font-size: 14px;
opacity: 0.7;
}
/* line 37, ../sass/editor.scss */
.header .header-content:hover {
opacity: 0.9;
}
/* line 42, ../sass/editor.scss */
.editor_form {
padding: 20px 40px;
overflow: hidden;
width: 100%;
}
/* line 46, ../sass/editor.scss */
.editor_form .editor_field {
background: #f5f5f5;
padding: 15px;
}
/* line 50, ../sass/editor.scss */
.editor_form .submit_fields {
padding: 0 20px;
}
/* line 55, ../sass/editor.scss */
label {
display: block;
margin: 30px 0 10px;
}
/* line 59, ../sass/editor.scss */
.text_field, .area_field {
height: 40px;
line-height: 40px;
border: none;
border-bottom: 1px solid #DFDFDF;
width: 100%;
font-size: 18px;
}
/* line 66, ../sass/editor.scss */
.text_field:focus, .area_field:focus {
outline: none;
border-bottom-width: 2px;
border-color: rgba(3, 133, 244, 0.7);
}
/* line 72, ../sass/editor.scss */
.area_field {
font-family: "Roboto",sans-serif;
max-height: 100px;
min-height: 100px;
max-width: 100%;
min-width: 100%;
line-height: normal;
}
/* line 80, ../sass/editor.scss */
.submit_fields_error {
line-height: 20px;
font-style: italic;
font-size: 12px;
opacity: 0.8;
color: #e74c3c;
}
/* line 87, ../sass/editor.scss */
.btn {
height: 40px;
color: #fff;
line-height: 40px;
padding: 0 20px;
text-transform: uppercase;
background: #0385F4;
border: 1px solid #0385F4;
cursor: pointer;
margin: 20px 0;
}
/* line 97, ../sass/editor.scss */
.btn:hover {
color: #0385F4;
background: #fff;
}
/* line 102, ../sass/editor.scss */
.cb {
clear: both;
}
/* line 105, ../sass/editor.scss */
.grey {
background: #f5f5f5;
}
/* line 108, ../sass/editor.scss */
.submit_success {
margin-top: 200px;
background: #0385F4;
padding: 30px;
color: #fff;
}
/* line 113, ../sass/editor.scss */
.submit_success .alert_title {
font-size: 40px;
opacity: 0.4;
}
/* line 117, ../sass/editor.scss */
.submit_success .alert_content {
font-weight: 100;
}
/* line 120, ../sass/editor.scss */
.submit_success .alert_footer {
opacity: 0.7;
font-size: 12px;
font-style: italic;
}

@ -0,0 +1,230 @@
/* line 2, style.scss */
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
/* line 3, style.scss */
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
/* line 6, _grid.scss */
.col-1, .col-m-1, .col-l-1, .col-2, .col-m-2, .col-l-2, .col-3, .col-m-3, .col-l-3, .col-4, .col-m-4, .col-l-4, .col-5, .col-m-5, .col-l-5, .col-6, .col-m-6, .col-l-6, .col-7, .col-m-7, .col-l-7, .col-8, .col-m-8, .col-l-8, .col-9, .col-m-9, .col-l-9, .col-10, .col-m-10, .col-l-10, .col-11, .col-m-11, .col-l-11, .col-12, .col-m-12, .col-l-12 {
float: right;
position: relative;
min-height: 1px;
padding: 0 10px;
/*border: 1px solid rgba(255, 0, 0, 0.5);*/
}
/* line 16, _grid.scss */
.col-1 {
width: 8.33333%;
}
/* line 16, _grid.scss */
.col-2 {
width: 16.66667%;
}
/* line 16, _grid.scss */
.col-3 {
width: 25%;
}
/* line 16, _grid.scss */
.col-4 {
width: 33.33333%;
}
/* line 16, _grid.scss */
.col-5 {
width: 41.66667%;
}
/* line 16, _grid.scss */
.col-6 {
width: 50%;
}
/* line 16, _grid.scss */
.col-7 {
width: 58.33333%;
}
/* line 16, _grid.scss */
.col-8 {
width: 66.66667%;
}
/* line 16, _grid.scss */
.col-9 {
width: 75%;
}
/* line 16, _grid.scss */
.col-10 {
width: 83.33333%;
}
/* line 16, _grid.scss */
.col-11 {
width: 91.66667%;
}
/* line 16, _grid.scss */
.col-12 {
width: 100%;
}
/* line 23, _grid.scss */
.row {
margin: 0 -10px;
overflow: hidden;
*zoom: 1;
}
/* line 27, _grid.scss */
.col-center {
margin: 0 auto;
float: none;
}
@media only screen and (min-width: 640px) {
/* line 30, _grid.scss */
.col-m-center {
margin: 0 auto;
float: none;
}
/* line 32, _grid.scss */
.col-m-1 {
width: 8.33333%;
}
/* line 32, _grid.scss */
.col-m-2 {
width: 16.66667%;
}
/* line 32, _grid.scss */
.col-m-3 {
width: 25%;
}
/* line 32, _grid.scss */
.col-m-4 {
width: 33.33333%;
}
/* line 32, _grid.scss */
.col-m-5 {
width: 41.66667%;
}
/* line 32, _grid.scss */
.col-m-6 {
width: 50%;
}
/* line 32, _grid.scss */
.col-m-7 {
width: 58.33333%;
}
/* line 32, _grid.scss */
.col-m-8 {
width: 66.66667%;
}
/* line 32, _grid.scss */
.col-m-9 {
width: 75%;
}
/* line 32, _grid.scss */
.col-m-10 {
width: 83.33333%;
}
/* line 32, _grid.scss */
.col-m-11 {
width: 91.66667%;
}
/* line 32, _grid.scss */
.col-m-12 {
width: 100%;
}
}
@media only screen and (min-width: 1024px) {
/* line 39, _grid.scss */
.col-l-center {
margin: 0 auto;
float: none;
}
/* line 41, _grid.scss */
.col-l-1 {
width: 8.33333%;
}
/* line 41, _grid.scss */
.col-l-2 {
width: 16.66667%;
}
/* line 41, _grid.scss */
.col-l-3 {
width: 25%;
}
/* line 41, _grid.scss */
.col-l-4 {
width: 33.33333%;
}
/* line 41, _grid.scss */
.col-l-5 {
width: 41.66667%;
}
/* line 41, _grid.scss */
.col-l-6 {
width: 50%;
}
/* line 41, _grid.scss */
.col-l-7 {
width: 58.33333%;
}
/* line 41, _grid.scss */
.col-l-8 {
width: 66.66667%;
}
/* line 41, _grid.scss */
.col-l-9 {
width: 75%;
}
/* line 41, _grid.scss */
.col-l-10 {
width: 83.33333%;
}
/* line 41, _grid.scss */
.col-l-11 {
width: 91.66667%;
}
/* line 41, _grid.scss */
.col-l-12 {
width: 100%;
}
}

@ -0,0 +1,10 @@
ins{
background: transparent !important;
color: inherit !important;
}
.diffins{
background:#4DB1FB !important;
}
.diffmod{
background:#4DFB74 !important;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 261 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 629 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 546 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 484 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 336 B

@ -0,0 +1,204 @@
<?php
if(isset($_GET["edit"])){
global $wpdb;
$table_name = $wpdb->prefix . 'visitors_edits';
$edit = $wpdb->get_row("SELECT * FROM ".$table_name." WHERE edit_id=".$_GET["edit"]);
$edit->edit_content=stripcslashes($edit->edit_content);
$edit->post=get_post($edit->post_id);
$options=get_option( "visitors_edits_options", [
"advanced_merge"=>null
]);
//Fix nl
//$edit->post->post_content=str_replace(["\r\n", "\r", "\n"], "<br/>",$edit->post->post_content);
//$edit->post_content=str_replace(["\r\n", "\r", "\n"], "<br/>",$edit->post_content);
//$edit->edit_content=str_replace(["\r\n", "\r", "\n"], "<br/>",$edit->edit_content);
$edit->post->post_content=nl2br($edit->post->post_content);
$edit->post_content=nl2br($edit->post_content);
$edit->edit_content=nl2br($edit->edit_content);
if($options["advanced_merge"]!=null){
$diff1=visitors_editsDIFF($edit->post_content,$edit->edit_content);
$conv_diff1=encodeDiff($diff1);
$diff=visitors_editsDIFF($conv_diff1["html"],$edit->post->post_content);
$diff=cleanEncodedDiff($diff);
$diff=decodeDiff($diff,$conv_diff1["codes"]);
}else{
$diff=visitors_editsDIFF($edit->post->post_content,$edit->edit_content);
}
$diff=cleanDiff($diff);
echo '<div style="display:none" id="visitors_edits_diff">'.$diff.'</div>';
showEditor($edit);
}else{
noData("Select a visitor contribution");
?>
<script type="text/javascript">
setTimeout(function(){
window.location="<?php echo menu_page_url('visitors_edits_main',false);?>";
},2000)
</script>
<?php
}
function showEditor($edit,$editor_content=""){
$options=get_option( "visitors_edits_options", [
"edit_notify_message"=>"Thanks for your contribution to our blog, your contribution was reviewed and approved."
]);
?>
<div class="visitors_edits_review_editor">
<h1>Review a contribution</h1><a class="delete_edit" href="<?php echo menu_page_url('visitors_edits_main',false);?>&delete=<?php echo $edit->edit_id;?>">Delete this contribution</a>
<ul class="edit_info">
<li><a target="_blank" href="<?php echo get_permalink($edit->post->ID);?>">View original post</a></li>
<li>Author : <?php echo $edit->visitor_name; ?> <span class="mail"><?php echo $edit->visitor_email; ?></span></li>
<li>Submited on :
<?php
$creationDate=date_create($edit->edit_time);
echo date_format($creationDate,"m/d/Y")." at ".date_format($creationDate,"h:i a");
?>
</li>
<li>Author comment :</li>
<p class="comment">
<?php echo stripcslashes($edit->visitor_comment); ?>
</p>
</ul>
<div class="cb"></div>
<form action="<?php echo menu_page_url('visitors_edits_main',false);?>" method="POST" onsubmit="return editSubmit()">
<div class="editor">
<?php
wp_editor($editor_content,"diff_editor",[
"media_buttons"=>false,
"quicktags"=>false,
"textarea_name"=>"post_content",
"tinymce"=>[
"mode" => "textareas",
"theme" => "modern"
]
]);
?>
</div>
<style>
.diff_editor ins{
background: #44B3FD !important;
}
</style>
<div class="controls">
<input type="hidden" value="<?php echo $edit->visitor_name; ?>" name="visitor_name">
<input type="hidden" value="<?php echo $edit->visitor_email; ?>" name="visitor_email">
<input type="hidden" value="<?php echo $edit->edit_id; ?>" name="edit_id">
<input type="hidden" value="<?php echo $edit->post_id; ?>" name="ID">
<div class="edit_notify">
<label><input type="checkbox" name="notify_visitor" id="edit_notify_activate"> Notify the author.</label>
<textarea name="admin_message" id="edit_notify_message"><?php echo $options["edit_notify_message"]; ?></textarea>
</div>
<button class="button-primary" type="submit">Save changes</button>
</div>
</form>
<script src="<?php echo visitors_edits::scriptUrl('admin');?>"></script>
</div>
<?php
}
function noData($msg){
?>
<h1 class="visitors_edits_no_data" style="display:block">
<?php echo $msg; ?>
</h1>
<?php
}
function clearTag($tag,$content){
return preg_replace("#<".$tag.".*?>.*?</".$tag.">#i","", $content);
}
function addAttrTag($tag,$attr,$content){
return preg_replace("#<".$tag."(.*?)>#i","<".$tag." ".$attr."='1'$1>", $content);
}
function clearTagName($tag,$content){
return preg_replace("#</*".$tag.".*?>#i", "", $content);
}
function replaceTag($origin,$replace,$content){
return preg_replace("#(<(/*)(".$origin.")(.*?)>)#i", '[$2'.$replace.'$4]', $content);
}
function encodeDiff($diff){
//composer require paquettg/php-html-parser
require_once "parser.php";
$html=str_get_html($diff);
$encoded=[
"html"=>"",
"codes"=>[
"INS"=>[],
"DEL"=>[]
]
];
$id=0;
foreach($html->find('ins') as $ins){
$encoded["codes"]["INS"][$id]=$ins->outertext;
$ins->outertext="%INS".$id."%";
$id++;
}
$id=0;
foreach($html->find('del') as $del){
$encoded["codes"]["DEL"][$id]=$del->outertext;
$del->outertext="%DEL".$id."%";
$id++;
}
$encoded["html"]=$html->outertext;
return $encoded;
}
function cleanDiff($content){
require_once "parser.php";
$html=str_get_html($content);
foreach($html->find('ul') as $ul){
foreach($ul->find("br") as $br){
$br->outertext="";
}
}
foreach($html->find('ol') as $ol){
foreach($ol->find("br") as $br){
$br->outertext="";
}
}
return $html;
}
function cleanEncodedDiff($content){
$html=str_get_html($content);
$delete_next=false;
$diffs = $html->find('ins, del');
for ($i=0; $i < count($diffs); $i++) {
$diff=$diffs[$i];
if($delete_next){
$diff->outertext="";
$delete_next=false;
coutinue;
}else{
$isSpecial=preg_match("#%(INS|DEL)\d*?%#", $diff->innertext);
if ($isSpecial){
//is important
if(preg_match("#diffmod#",$diff->outertext)){
$delete_next=true;
}
$diff->outertext=$diff->innertext;
}else{
if($diff->tag==="ins"){
$diff->outertext=$diff->innertext;
}else{
$diff->outertext="";
}
}
}
}
return $html;
}
function decodeDiff($content,$codes){
foreach ($codes["INS"] as $id => $code) {
$content=str_replace("%INS".$id."%", $code, $content);
}
foreach ($codes["DEL"] as $id => $code) {
$content=str_replace("%DEL".$id."%", $code, $content);
}
return $content;
}

@ -0,0 +1,152 @@
<?php
$post=null;
if(!empty($_POST)){
global $wpdb;
$wpdb->show_errors();
$table_name = $wpdb->prefix . 'visitors_edits';
$post_id=$_POST["post_id"];
$visitor_name=$_POST["visitor_name"];
$visitor_email=$_POST["visitor_email"];
$visitor_comment=$_POST["visitor_comment"];
$edit_content=$_POST["edit_content"];
$post = get_post($post_id);
//Check if changed
if(md5($post->post_content)!==md5(stripcslashes($edit_content))){
$wpdb->insert($table_name,[
"edit_time"=>date('Y-m-d H:i:s'),
"visitor_name"=>$visitor_name,
"visitor_email"=>$visitor_email,
"visitor_comment"=>$visitor_comment,
"edit_content"=>$edit_content,
"post_id"=>$post_id,
"post_content"=>$post->post_content
]);
require "mail.php";
$options=get_option( "visitors_edits_options", [
"admin_email"=>"",
"notify_admin"=>null,
"visitor_notif_message"=>"Your suggestion was submitted.",
"admin_notif_message"=>"A new suggestion was submitted."
]);
$mail = [
"post_title"=>$post->post_title,
"post_url"=>get_permalink($post_id),
"visitor_name"=>$visitor_name,
"visitor_email"=>$visitor_email,
"edit_time"=>date('H:i')." - ".date('d/m/y'),
"blog_title" => get_bloginfo("name"),
"visitor_notif_message"=>$options["visitor_notif_message"],
"admin_notif_message"=>$options["admin_notif_message"]
];
$visitor_submitionMail=new visitors_edits_EMAIL($mail,"visitor_submition");
$visitor_submitionMail->send($visitor_email);
if($options["notify_admin"]!=null){
$admin_email=$options["admin_email"];
$admin_submitionMail=new visitors_edits_EMAIL($mail,"admin_submition");
$admin_submitionMail->send($admin_email);
}
}
}else{
global $wp;
global $post;
$post = get_posts([
"name"=> $wp->query_vars['visitors_edits_post_name'],
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 1
]);
$post=$post[0];
if($post->post_name!=$wp->query_vars['visitors_edits_post_name']){
header("Location:".get_site_url());
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w1.org/1998/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="<?php echo plugins_url( '/../css/grid.css',__FILE__ );?>">
<link rel="stylesheet" type="text/css" href="<?php echo plugins_url( '/../css/editor.css',__FILE__ );?>">
<script src="<?php echo visitors_edits::scriptUrl('jquery');?>"></script>
<title>Submit an edit</title>
</head>
<body <?php if(!empty($_POST)){echo 'class="grey"';} ?>>
<?php
if(!empty($_POST)){
confirmSubmit("Edit Submitted!","Thanks for your contribution you will be notified once the edit reviewed.");
}else{
showForm();
}
?>
</body>
</html>
<?php
function showForm(){
global $post;
?>
<div class="header">
<div class="header-title">Submit a contribution</div>
<p class="header-content">
<a href="<?php echo get_permalink($post->ID) ?>">Original post : <?php echo $post->post_title; ?>.</a>
</p>
</div>
<form action="" method="POST" class="editor_form row" id="editor_form" onsubmit="return validateEdit.run()">
<div class="submit_fields col-12 col-l-4">
<ul class="submit_fields_error" id="submit_fields_error">
</ul>
<label for="name">Name</label>
<input class="text_field" type="text" name="visitor_name" placeholder="Name" id="name">
<label for="email">Email</label>
<input class="text_field" type="email" name="visitor_email" placeholder="Email" id="email">
<label for="comment">Description</label>
<textarea class="area_field" type="text" name="visitor_comment" value=" " id="comment">
</textarea>
<input type="hidden" name="post_id" value="<?php echo $post->ID;?>">
<input type="hidden" name="post_url" value="<?php echo get_permalink($post->ID);?>">
<input type="submit" class="btn" value="Submit for review">
</div>
<div class="editor_field col-12 col-l-8">
<?php
wp_editor($post->post_content,"edit_content",[
"media_buttons"=>false,
"quicktags"=>false,
"textarea_name"=>"edit_content",
"tinymce"=>[
"mode" => "textareas",
"theme" => "modern"
]
]);
_WP_Editors::enqueue_scripts();
print_footer_scripts();
_WP_Editors::editor_js();
?>
</div>
<div class="cb"></div>
</form>
<script src="<?php echo visitors_edits::scriptUrl('editor');?>"></script>
<?php
}
function confirmSubmit($title,$message){
?>
<div class="submit_success col-10 col-l-6 col-center">
<strong class="alert_title">
<?php echo $title;?>
</strong>
<p class="alert_content">
<?php echo $message;?>
</p>
<p class="alert_footer">
<a href="<?php echo $_POST['post_url']?>">Click here to continue back to the post</a>
</p>
</div>
</div>
<?php
}
?>

@ -0,0 +1,48 @@
<?php
class visitors_edits_EMAIL{
var $subject;
var $body;
public function __construct($cpts,$template){
$template=$this->loadTemplate($template);
$this->subject=$this->inject($template["subject"],$cpts);
$this->body=$this->inject($template["body"],$cpts);
}
public function send($destination){
$options=get_option( "visitors_edits_options", [
"admin_email"=>"",
"notify_admin"=>null
]);
$headers= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
wp_mail($destination, $this->subject, $this->body,$headers);
/*
subject : $this->subject
body : $this->body
*/
}
private function loadTemplate($template){
ob_start();
require("mail_templates/".$template.".html");
$templateHtml=ob_get_clean();
preg_match("|<subject>(.*)</subject>|",$templateHtml,$subject);
$templateHtml=preg_replace("|<subject>.*</subject>|","",$templateHtml);
return [
"subject"=>$subject[1],
"body"=>$templateHtml
];
}
private function inject($str,$body){
foreach ($body as $key => $value) {
$str=str_replace("#$key#",$value,$str);
}
return $str;
}
public function preview(){
echo $this->subject;
echo $this->body;
}
}
?>

@ -0,0 +1,89 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<subject>[#blog_title# | Visitors Contributions] - Contribution submited</subject>
<meta http-equiv="content-type" content="text/html, charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<link href='https://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'>
</head>
<body leftmargin="0" rightmargin="0" marginwidth="0" marginheight="0">
<table bgcolor="#0385F4" width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
<table align="center" width="600" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;font-size:50px;color:#fff;mso-line-height-rule:exactly;line-height:28px">#blog_title#</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;font-size:20px;color:#fff;mso-line-height-rule:exactly;line-height:28px">Contribution submited</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table bgcolor="#E3E3E3" width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
<table align="center" width="600" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
#admin_notif_message#
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
Submition details
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
<a href="#post_url#" style="color:#262626">#post_title#</a>
</td>
</tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
Submited on : #edit_time#
</td>
</tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
Author : #visitor_name# (#visitor_email#)
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
<table align="center" bgcolor="#0385F4" width="100" border="0" cellpadding="0" cellspacing="0">
<tbody><tr><td height="4" style="font-size:4px; line-height:4px">&nbsp;</td></tr></tbody>
</table>
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
Visitors Contributions
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</body>
</html>

@ -0,0 +1,84 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<subject>[#blog_title#] - Contribution reviewed</subject>
<meta http-equiv="content-type" content="text/html, charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<link href='https://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'>
</head>
<body leftmargin="0" rightmargin="0" marginwidth="0" marginheight="0">
<table bgcolor="#0385F4" width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
<table align="center" width="600" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;font-size:50px;color:#fff;mso-line-height-rule:exactly;line-height:28px">#blog_title#</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;font-size:20px;color:#fff;mso-line-height-rule:exactly;line-height:28px">Contribution approved</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table bgcolor="#E3E3E3" width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
<table align="center" width="600" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
<strong>Dear #visitor_name#</strong>
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
#admin_message#
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
<a href="#post_url#" style="color:#262626">#post_title#</a>
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
<table align="center" bgcolor="#0385F4" width="100" border="0" cellpadding="0" cellspacing="0">
<tbody><tr><td height="4" style="font-size:4px; line-height:4px">&nbsp;</td></tr></tbody>
</table>
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
#blog_title# team
</td>
</tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
Regards
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</body>
</html>

@ -0,0 +1,95 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<subject>[#blog_title#] - Contribution submited</subject>
<meta http-equiv="content-type" content="text/html, charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<link href='https://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'>
</head>
<body leftmargin="0" rightmargin="0" marginwidth="0" marginheight="0">
<table bgcolor="#0385F4" width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
<table align="center" width="600" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;font-size:50px;color:#fff;mso-line-height-rule:exactly;line-height:28px">#blog_title#</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;font-size:20px;color:#fff;mso-line-height-rule:exactly;line-height:28px">Contribution submited</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table bgcolor="#E3E3E3" width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
<table align="center" width="600" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
<strong>Dear #visitor_name#</strong>
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
#visitor_notif_message#
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
Submition details
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
<a href="#post_url#" style="color:#262626">#post_title#</a>
</td>
</tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
Submited on : #edit_time#
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
<table align="center" bgcolor="#0385F4" width="100" border="0" cellpadding="0" cellspacing="0">
<tbody><tr><td height="4" style="font-size:4px; line-height:4px">&nbsp;</td></tr></tbody>
</table>
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
#blog_title# team
</td>
</tr>
<tr>
<td align="center "style="font-family:'Questrial',Helvetica,sans-serif; text-align:center;color:#262626;mso-line-height-rule:exactly;line-height:28px">
Regards
</td>
</tr>
<tr><td height="30" style="font-size:30px; line-height:30px">&nbsp;</td></tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</body>
</html>

@ -0,0 +1,86 @@
<?php
global $wpdb;
$table_name = $wpdb->prefix . 'visitors_edits';
if(isset($_GET["delete"])){
$wpdb->delete($table_name, array( 'edit_id' => $_GET["delete"] ) );
flashMessage("The review was deleted","danger");
}
if(!empty($_POST)){
wp_update_post([
"ID"=>$_POST["ID"],
"post_content"=>$_POST["post_content"]
]);
$wpdb->delete($table_name, array( 'edit_id' => $_POST["edit_id"] ) );
flashMessage("The post was updated successfully","");
//Notify visitor
if(isset($_POST["notify_visitor"])){
require 'mail.php';
$post = get_post($_POST["ID"]);
$mail = [
"visitor_name"=>$_POST["visitor_name"],
"post_title"=>$post->post_title,
"post_url"=>get_permalink($_POST["ID"]),
"blog_title" => get_bloginfo("name"),
"admin_message"=>$_POST["admin_message"]
];
$visitor_submitionMail=new visitors_edits_EMAIL($mail,"visitor_approval");
$visitor_submitionMail->send($_POST["visitor_email"]);
}
}
$edits = $wpdb->get_results("SELECT * FROM ".$table_name);
for ($r=0; $r <count($edits); $r++) {
$edits[$r]->post=get_post($edits[$r]->post_id);
}
?>
<h1 class="visitors_edits_no_data" <?php if(count($edits)==0){echo 'style="display:block"';}?>>
Emty pending list
</h1>
<div class="visitors_edits_pending" <?php if(count($edits)==0){echo 'style="display:none"';}?>>
<h1>Pending reviews (<?php echo count($edits);?>)</h1>
<table class="widefat pending">
<thead>
<tr>
<th>Post</th>
<th>Author</th>
<th>Author comment</th>
<th>Date</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<?php
for ($i=0; $i < count($edits); $i++) {
$edit=$edits[$i];
?>
<tr>
<td><?php echo $edit->post->post_title; ?></td>
<td><?php echo $edit->visitor_name?></td>
<td>
<?php echo stripslashes($edit->visitor_comment); ?>
</td>
<td><?php
$creationDate=date_create($edit->edit_time);
echo date_format($creationDate,"m/d/Y")." at ".date_format($creationDate,"h:i a")
?></td>
<td>
<a class="button-primary" href="<?php echo menu_page_url('visitors_edits_approve',false);?>&edit=<?php echo $edit->edit_id;?>">Review</a>
<a class="button-secondary" href="<?php echo menu_page_url('visitors_edits_main',false);?>&delete=<?php echo $edit->edit_id;?>">Delete</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<?php
function flashMessage($msg,$type){
?>
<div class="visitors_flashMessage <?php echo $type ?>">
<p>
<?php echo $msg ;?>
</p>
</div>
<?php
}
?>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,71 @@
<?php
$options=[];
if(isset($_POST["save_settings"])){
$options=[
"admin_email"=>$_POST["admin_email"],
"notify_admin"=>$_POST["notify_admin"],
"advanced_merge"=>$_POST["advanced_merge"],
"admin_notif_message"=>$_POST["admin_notif_message"],
"visitor_notif_message"=>$_POST["visitor_notif_message"],
"edit_notify_message"=>$_POST["edit_notify_message"],
"propose_edit_link"=>$_POST["propose_edit_link"]
];
update_option( "visitors_edits_options", $options );
flashMessage("Settings saved.","");
}else{
$options=get_option( "visitors_edits_options", [
"admin_email"=>"",
"notify_admin"=>null,
"advanced_merge"=>null,
"visitor_notif_message"=>"Your suggestion was submitted.",
"admin_notif_message"=>"A new suggestion was submitted.",
"edit_notify_message"=>"Thanks for your contribution to our blog, your contribution was reviewed and approved.",
"propose_edit_link"=>"<p><a href='#post_link#'>Propose an edit</a></p>"
]);
}
?>
<div class="visitors_edits_admin">
<h2>Settings</h2>
<form action="" method="post">
<div class="control">
<label>Propose an edit link</label>
<input type="text" name="propose_edit_link" value="<?php echo stripcslashes($options['propose_edit_link']) ?>">
</div>
<div class="control">
<label>Admin notification message</label>
<textarea name="admin_notif_message" class="notif_message" value=""><?php echo $options['admin_notif_message'] ?></textarea>
</div>
<div class="control">
<label>Visitor notification message (On Submit)</label>
<textarea name="visitor_notif_message" class="notif_message" value=""><?php echo $options['visitor_notif_message'] ?></textarea>
</div>
<div class="control">
<label>Visitor notification message (On Review)</label>
<textarea name="edit_notify_message" class="notif_message" value=""><?php echo $options['edit_notify_message'] ?></textarea>
</div>
<div class="control">
<label>Admin email</label>
<input type="text" placeholder="Email" name="admin_email" value="<?php echo $options['admin_email'] ?>">
</div>
<div class="control">
<label><input type="checkbox" name="notify_admin" <?php echo (($options['notify_admin']==null) ? "" : "checked")?>>Notify me on new submits.</label>
</div>
<div class="control">
<label><input type="checkbox" name="advanced_merge" <?php echo (($options['advanced_merge']==null) ? "" : "checked")?>>Use deep merging.</label>
</div>
<div class="control">
<input type="submit" class="save_btn button-primary" value="Save settings" name="save_settings">
</div>
</form>
</div>
<?php
function flashMessage($msg,$type){
?>
<div class="visitors_flashMessage <?php echo $type ?>">
<p>
<?php echo $msg ;?>
</p>
</div>
<?php
}
?>

@ -0,0 +1,8 @@
var $notification=document.querySelector("#edit_notify_message");
document.querySelector("#edit_notify_activate").addEventListener("change",function(){
if(this.checked){
$notification.style.display="block";
}else{
$notification.style.display="none";
}
});

@ -0,0 +1,121 @@
visitors_edits_tools={
data:{},
clearTag:function(content,tag){
var regexp=RegExp("<"+tag+">.*?<\/"+tag+">", "gi");
var editedContent=content.replace(regexp,"");
return editedContent;
},
clearTag:function(content,tag){
var $contentDiv=jQuery("<div/>").html(content);
$contentDiv.find(tag).each(function(){
$tag=jQuery(this);
$tag.remove();
});
return $contentDiv.html();
},
clearTagName:function(content,tag){
var $contentDiv=jQuery("<div/>").html(content);
$contentDiv.find(tag).each(function(){
$tag=jQuery(this);
$tag.replaceWith($tag.html());
});
return $contentDiv.html();
},
clearClassName:function(content,classname){
var $contentDiv=jQuery("<div/>").html(content);
$contentDiv.find("."+classname).each(function(){
$elm=jQuery(this);
$elm.removeClass(classname);
});
return $contentDiv.html();
},
clear:function(ed){
var elt=ed.selection.getNode();
elt.remove();
},
clean:function(ed){
var elt=ed.selection.getNode();
var eltContent=elt.outerHTML;
eltContent=visitors_edits_tools.clearTagName(eltContent,"ins");
eltContent=visitors_edits_tools.clearTagName(eltContent,"del");
elt.remove();
ed.execCommand('mceInsertContent', 0, eltContent);
}
};
(function($){
//Create plugin
tinymce.create('tinymce.plugins.visitors_edits', {
init : function(ed, url) {
//Add buttons
ed.addButton('visitors_edits_approve', {
title : 'Approve',
cmd : 'visitors_edits_approve',
image : url + '/../img/approve.png'
});
ed.addButton('visitors_edits_reject', {
title : 'Reject',
cmd : 'visitors_edits_reject',
image : url + '/../img/reject.png',
});
ed.addButton('visitors_edits_clean', {
title : 'Clean All',
cmd : 'visitors_edits_clean',
image : url + '/../img/clean.png'
});
//Add Commands
ed.addCommand('visitors_edits_approve', function() {
var elt=ed.selection.getNode();
if(elt.tagName.toLowerCase()=="ins"){
visitors_edits_tools.clean(ed);
}
if(elt.tagName.toLowerCase()=="del"){
visitors_edits_tools.clear(ed);
}
});
ed.addCommand('visitors_edits_reject', function() {
var elt=ed.selection.getNode();
if(elt.tagName.toLowerCase()=="del"){
visitors_edits_tools.clean(ed);
}
if(elt.tagName.toLowerCase()=="ins"){
visitors_edits_tools.clear(ed);
}
});
ed.addCommand('visitors_edits_clean',function(){
var content=ed.getContent();
content=visitors_edits_tools.clearTagName(content,"ins");
content=visitors_edits_tools.clearTag(content,"del");
content=visitors_edits_tools.clearClassName(content,"diffmod");
ed.setContent(content);
});
//Load content
setTimeout(function(){
//Procedce diff Html
var diffDiv=document.querySelector("#visitors_edits_diff");
var $diffDiv=jQuery(diffDiv);
$diffDiv.find("ins").each(function(){
var $ins=$(this);
if([""," "].indexOf($ins.html())>-1){
$ins.remove();
}
});
ed.setContent($diffDiv.html());
//Clean content
var $diffDiv=jQuery("<div/>").html(ed.getContent());
$diffDiv.find("p").each(function(){
var $p=$(this);
if(["&nbsp;"].indexOf($p.html())>-1){
$p.remove();
}
});
ed.setContent($diffDiv.html());
},0);
},
});
// Register plugin
tinymce.PluginManager.add( 'visitors_edits', tinymce.plugins.visitors_edits );
})(jQuery);
function editSubmit(){
tinyMCE.activeEditor.execCommand("visitors_edits_clean");
return true;
}

@ -0,0 +1,41 @@
var validateEdit={
container:jQuery("#submit_fields_error"),
validateRules:{
name:{
required:true,
msg:"Name field required"
},
email:{
required:true,
msg:"Email field required"
},
comment:{
required:true,
msg:"Please describe your edit to speed up the approval"
}
},
run:function(){
var errors=[];
jQuery.each(this.validateRules, function(id, rule) {
var element=jQuery("#"+id);
if(rule.required && element.val()===""){
errors.push(id);
}
});
if(errors.length){
this.container.html("");
for (var i = 0; i < errors.length; i++) {
this.container.append("<li>"+this.validateRules[errors[i]].msg+"</li>")
}
return false;
}else{
return true;
}
},init:function(){
jQuery.each(this.validateRules, function(id, rule) {
var element=jQuery("#"+id);
element.val("");
});
}
}
validateEdit.init();

4
js/jquery.js vendored

File diff suppressed because one or more lines are too long

1532
js/jquery.validate.js vendored

File diff suppressed because it is too large Load Diff

@ -0,0 +1,7 @@
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit8a728e750e2d17f1173f31bda205adec::getLoader();

@ -0,0 +1,145 @@
# Change Log
## [v0.1.1](https://github.com/caxy/php-htmldiff/tree/v0.1.1) (2016-03-16)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.1.0...v0.1.1)
**Features and Enhancements:**
- Update TableDiff HTMLPurifier Initialization [\#35](https://github.com/caxy/php-htmldiff/pull/35) ([dbergunder](https://github.com/dbergunder))
**Miscellaneous:**
- Update the README and add additional documentation [\#34](https://github.com/caxy/php-htmldiff/pull/34) ([jschroed91](https://github.com/jschroed91))
## [0.1.0](https://github.com/caxy/php-htmldiff/tree/0.1.0) (2016-03-10)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.14...0.1.0)
**Features and Enhancements:**
- Allow caching of the calculated diffs using a doctrine cache provider [\#33](https://github.com/caxy/php-htmldiff/pull/33) ([jschroed91](https://github.com/jschroed91))
- Create configuration class for HtmlDiff config options [\#32](https://github.com/caxy/php-htmldiff/pull/32) ([jschroed91](https://github.com/jschroed91))
- New Feature: Table Diffing [\#31](https://github.com/caxy/php-htmldiff/pull/31) ([jschroed91](https://github.com/jschroed91))
- Detect link changes to resolve [\#28](https://github.com/caxy/php-htmldiff/issues/28) [\#30](https://github.com/caxy/php-htmldiff/pull/30) ([jschroed91](https://github.com/jschroed91))
- Setup PHPUnit testsuite with basic functional test and a few test cases [\#26](https://github.com/caxy/php-htmldiff/pull/26) ([jschroed91](https://github.com/jschroed91))
## [0.1.0-beta.1](https://github.com/caxy/php-htmldiff/tree/0.1.0-beta.1) (2016-02-26)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.14...0.1.0-beta.1)
**Features and Enhancements:**
- New Feature: Table Diffing [\#31](https://github.com/caxy/php-htmldiff/pull/31) ([jschroed91](https://github.com/jschroed91))
- Detect link changes to resolve [\#28](https://github.com/caxy/php-htmldiff/issues/28) [\#30](https://github.com/caxy/php-htmldiff/pull/30) ([jschroed91](https://github.com/jschroed91))
- Setup PHPUnit testsuite with basic functional test and a few test cases [\#26](https://github.com/caxy/php-htmldiff/pull/26) ([jschroed91](https://github.com/jschroed91))
## [0.0.14](https://github.com/caxy/php-htmldiff/tree/0.0.14) (2016-02-03)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.13...0.0.14)
**Fixed bugs:**
- Fix HtmlDiff matching logic skipping over single word matches [\#25](https://github.com/caxy/php-htmldiff/pull/25) ([jschroed91](https://github.com/jschroed91))
## [0.0.13](https://github.com/caxy/php-htmldiff/tree/0.0.13) (2016-01-12)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.12...0.0.13)
**Fixed bugs:**
- Misc. list diffing updates and fixes [\#24](https://github.com/caxy/php-htmldiff/pull/24) ([jschroed91](https://github.com/jschroed91))
- Updated list diff class to maintain the tags on lists. [\#23](https://github.com/caxy/php-htmldiff/pull/23) ([adamCaxy](https://github.com/adamCaxy))
## [0.0.12](https://github.com/caxy/php-htmldiff/tree/0.0.12) (2015-11-11)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.11...0.0.12)
**Fixed bugs:**
- feature-list\_diffing-new [\#20](https://github.com/caxy/php-htmldiff/pull/20) ([adamCaxy](https://github.com/adamCaxy))
## [0.0.11](https://github.com/caxy/php-htmldiff/tree/0.0.11) (2015-11-06)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.10...0.0.11)
**Features and Enhancements:**
- Feature list diffing new [\#19](https://github.com/caxy/php-htmldiff/pull/19) ([adamCaxy](https://github.com/adamCaxy))
## [0.0.10](https://github.com/caxy/php-htmldiff/tree/0.0.10) (2015-10-21)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.9...0.0.10)
**Fixed bugs:**
- Fix: Updated code so that null is not given in list formatting. [\#17](https://github.com/caxy/php-htmldiff/pull/17) ([adamCaxy](https://github.com/adamCaxy))
## [0.0.9](https://github.com/caxy/php-htmldiff/tree/0.0.9) (2015-10-20)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.8...0.0.9)
**Fixed bugs:**
- Missed an array\_column in ListDiff. Updated to use ArrayColumn function. [\#16](https://github.com/caxy/php-htmldiff/pull/16) ([jschroed91](https://github.com/jschroed91))
## [0.0.8](https://github.com/caxy/php-htmldiff/tree/0.0.8) (2015-10-20)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.7...0.0.8)
**Fixed bugs:**
- Added update for php versions that do not have array\_column as a function. [\#15](https://github.com/caxy/php-htmldiff/pull/15) ([jschroed91](https://github.com/jschroed91))
## [0.0.7](https://github.com/caxy/php-htmldiff/tree/0.0.7) (2015-10-20)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.6...0.0.7)
**Features and Enhancements:**
- Created ListDiff class to handle diffing of lists. [\#14](https://github.com/caxy/php-htmldiff/pull/14) ([adamCaxy](https://github.com/adamCaxy))
## [0.0.6](https://github.com/caxy/php-htmldiff/tree/0.0.6) (2015-09-11)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.5...0.0.6)
**Features and Enhancements:**
- Feature - html tag isolation [\#12](https://github.com/caxy/php-htmldiff/pull/12) ([jschroed91](https://github.com/jschroed91))
- ICC-4313 | ICC-4314 | Replace Special HTML Elements with placeholder tokens and update diffing logic [\#11](https://github.com/caxy/php-htmldiff/pull/11) ([usaqlain01](https://github.com/usaqlain01))
## [0.0.5](https://github.com/caxy/php-htmldiff/tree/0.0.5) (2015-03-03)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.4...0.0.5)
**Features and Enhancements:**
- Support derived classes [\#10](https://github.com/caxy/php-htmldiff/pull/10) ([mkalkbrenner](https://github.com/mkalkbrenner))
## [0.0.4](https://github.com/caxy/php-htmldiff/tree/0.0.4) (2015-01-09)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.3...0.0.4)
**Fixed bugs:**
- Check for empty oldText or newText before processing del or ins in processReplaceOperation [\#9](https://github.com/caxy/php-htmldiff/pull/9) ([jschroed91](https://github.com/jschroed91))
## [0.0.3](https://github.com/caxy/php-htmldiff/tree/0.0.3) (2015-01-08)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.2...0.0.3)
**Features and Enhancements:**
- Add option to insert a space between del and ins tags [\#8](https://github.com/caxy/php-htmldiff/pull/8) ([jschroed91](https://github.com/jschroed91))
- Updated demo to accept input and diff on the fly [\#5](https://github.com/caxy/php-htmldiff/pull/5) ([jschroed91](https://github.com/jschroed91))
## [0.0.2](https://github.com/caxy/php-htmldiff/tree/0.0.2) (2014-08-12)
[Full Changelog](https://github.com/caxy/php-htmldiff/compare/0.0.1...0.0.2)
**Features and Enhancements:**
- Break out HTML content to individual HTML, CSS, JS files [\#6](https://github.com/caxy/php-htmldiff/pull/6) ([mgersten-caxy](https://github.com/mgersten-caxy))
**Fixed bugs:**
- Fix error caused when passing empty array into setSpecialCaseTags [\#7](https://github.com/caxy/php-htmldiff/pull/7) ([jschroed91](https://github.com/jschroed91))
## [0.0.1](https://github.com/caxy/php-htmldiff/tree/0.0.1) (2014-07-31)
**Features and Enhancements:**
- Added static properties for the default config variables [\#4](https://github.com/caxy/php-htmldiff/pull/4) ([jschroed91](https://github.com/jschroed91))
- Feature nonpartial word diffing [\#3](https://github.com/caxy/php-htmldiff/pull/3) ([jschroed91](https://github.com/jschroed91))
- Added option to group together diffed words in output [\#2](https://github.com/caxy/php-htmldiff/pull/2) ([jschroed91](https://github.com/jschroed91))
\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*

@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at dev@caxy.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

@ -0,0 +1,33 @@
Contributing
============
First of all, **thank you** for contributing, **you are awesome**!
Here are a few rules to follow in order to ease code reviews, and discussions before
maintainers accept and merge your work.
You MUST follow the [PSR-1](http://www.php-fig.org/psr/1/) and
[PSR-2](http://www.php-fig.org/psr/2/). If you don't know about any of them, you
should really read the recommendations. Can't wait? Use the [PHP-CS-Fixer
tool](http://cs.sensiolabs.org/).
You MUST run the test suite.
You MUST write (or update) unit tests.
You SHOULD write documentation.
Please, write [commit messages that make
sense](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html),
and [rebase your branch](http://git-scm.com/book/en/Git-Branching-Rebasing)
before submitting your Pull Request.
One may ask you to [squash your
commits](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html)
too. This is used to "clean" your Pull Request before merging it (we don't want
commits such as `fix tests`, `fix 2`, `fix 3`, etc.).
Also, while creating your Pull Request on GitHub, you MUST write a description
which gives the context and/or explains why you are creating it.
Thank you!

@ -0,0 +1,130 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does.
Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
type `show w'. This is free software, and you are welcome
to redistribute it under certain conditions; type `show c'
for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright
interest in the program `Gnomovision'
(which makes passes at compilers) written
by James Hacker.
signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.

@ -0,0 +1,201 @@
php-htmldiff
============
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/caxy/php-htmldiff/badges/quality-score.png?b=master)][badge_score]
[![Build Status](https://scrutinizer-ci.com/g/caxy/php-htmldiff/badges/build.png?b=master)][badge_status]
[![Code Coverage](https://scrutinizer-ci.com/g/caxy/php-htmldiff/badges/coverage.png?b=master)][badge_coverage]
[![Packagist](https://img.shields.io/packagist/dt/caxy/php-htmldiff.svg)][badge_packagist]
[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/caxy/php-htmldiff.svg)][badge_resolve]
[![Percentage of issues still open](http://isitmaintained.com/badge/open/caxy/php-htmldiff.svg)][badge_issues]
php-htmldiff is a library for comparing two HTML files/snippets and highlighting the differences using simple HTML.
This HTML Diff implementation was forked from [rashid2538/php-htmldiff][upstream] and has been modified with new features,
bug fixes, and enhancements to the original code.
For more information on these modifications, read the [differences from rashid2538/php-htmldiff][differences] or view the [CHANGELOG][changelog].
## Installation
The recommended way to install php-htmldiff is through [Composer][composer].
Require the [caxy/php-htmldiff][badge_packagist] package by running following command:
```sh
composer require caxy/php-htmldiff
```
This will resolve the latest stable version.
Otherwise, install the library and setup the autoloader yourself.
### Working with Symfony
If you are using Symfony, you can use the [caxy/HtmlDiffBundle][htmldiffbundle] to make life easy!
## Usage
```php
use Caxy\HtmlDiff\HtmlDiff;
$htmlDiff = new HtmlDiff($oldHtml, $newHtml);
$content = $htmlDiff->build();
```
## Configuration
The configuration for HtmlDiff is contained in the `Caxy\HtmlDiff\HtmlDiffConfig` class.
There are two ways to set the configuration:
1. [Configure an Existing HtmlDiff Object](#configure-an-existing-htmldiff-object)
2. [Create and Use a HtmlDiffConfig Object](#create-and-use-a-htmldiffconfig-object)
#### Configure an Existing HtmlDiff Object
When a new `HtmlDiff` object is created, it creates a `HtmlDiffConfig` object with the default configuration.
You can change the configuration using setters on the object:
```php
use Caxy\HtmlDiff\HtmlDiff;
// ...
$htmlDiff = new HtmlDiff($oldHtml, $newHtml);
// Set some of the configuration options.
$htmlDiff->getConfig()
->setMatchThreshold(80)
->setInsertSpaceInReplace(true)
;
// Calculate the differences using the configuration and get the html diff.
$content = $htmlDiff->build();
// ...
```
#### Create and Use a HtmlDiffConfig Object
You can also set the configuration by creating an instance of
`Caxy\HtmlDiff\HtmlDiffConfig` and using it when creating a new `HtmlDiff`
object using `HtmlDiff::create`.
This is useful when creating more than one instance of `HtmlDiff`:
```php
use Caxy\HtmlDiff\HtmlDiff;
use Caxy\HtmlDiff\HtmlDiffConfig;
// ...
$config = new HtmlDiffConfig();
$config
->setMatchThreshold(95)
->setInsertSpaceInReplace(true)
;
// Create an HtmlDiff object with the custom configuration.
$firstHtmlDiff = HtmlDiff::create($oldHtml, $newHtml, $config);
$firstContent = $firstHtmlDiff->build();
$secondHtmlDiff = HtmlDiff::create($oldHtml2, $newHtml2, $config);
$secondHtmlDiff->getConfig()->setMatchThreshold(50);
$secondContent = $secondHtmlDiff->build();
// ...
```
#### Full Configuration with Defaults:
```php
$config = new HtmlDiffConfig();
$config
// Percentage required for list items to be considered a match.
->setMatchThreshold(80)
// Set the encoding of the text to be diffed.
->setEncoding('UTF-8')
// If true, a space will be added between the <del> and <ins> tags of text that was replaced.
->setInsertSpaceInReplace(false)
// Option to disable the new Table Diffing feature and treat tables as regular text.
->setUseTableDiffing(true)
// Pass an instance of \Doctrine\Common\Cache\Cache to cache the calculated diffs.
->setCacheProvider(null)
// Set the cache directory that HTMLPurifier should use.
->setPurifierCacheLocation(null)
// Group consecutive deletions and insertions instead of showing a deletion and insertion for each word individually.
->setGroupDiffs(true)
// List of characters to consider part of a single word when in the middle of text.
->setSpecialCaseChars(array('.', ',', '(', ')', '\''))
// List of tags to treat as special case tags.
->setSpecialCaseTags(array('strong', 'b', 'i', 'big', 'small', 'u', 'sub', 'sup', 'strike', 's', 'p'))
// List of tags (and their replacement strings) to be diffed in isolation.
->setIsolatedDiffTags(array(
'ol' => '[[REPLACE_ORDERED_LIST]]',
'ul' => '[[REPLACE_UNORDERED_LIST]]',
'sub' => '[[REPLACE_SUB_SCRIPT]]',
'sup' => '[[REPLACE_SUPER_SCRIPT]]',
'dl' => '[[REPLACE_DEFINITION_LIST]]',
'table' => '[[REPLACE_TABLE]]',
'strong' => '[[REPLACE_STRONG]]',
'b' => '[[REPLACE_B]]',
'em' => '[[REPLACE_EM]]',
'i' => '[[REPLACE_I]]',
'a' => '[[REPLACE_A]]',
))
;
```
## Contributing
See [CONTRIBUTING][contributing] file.
## Contributor Code of Conduct
Please note that this project is released with a [Contributor Code of
Conduct][contributor_covenant]. By participating in this project
you agree to abide by its terms. See [CODE_OF_CONDUCT][code_of_conduct] file.
## Credits
* [rashid2538][] for the port to PHP and the base for our project: [rashid2538/php-htmldiff][upstream]
* [willdurand][] for an excellent post on [open sourcing libraries][].
Much of this documentation is based off of the examples in the post.
Did we miss anyone? If we did, let us know or put in a pull request!
## License
php-htmldiff is available under [GNU General Public License, version 2][gnu]. See the [LICENSE][license] file for details.
[badge_score]: https://scrutinizer-ci.com/g/caxy/php-htmldiff/?branch=master
[badge_status]: https://scrutinizer-ci.com/g/caxy/php-htmldiff/build-status/master
[badge_coverage]: https://scrutinizer-ci.com/g/caxy/php-htmldiff/?branch=master
[badge_packagist]: https://packagist.org/packages/caxy/php-htmldiff
[badge_resolve]: http://isitmaintained.com/project/caxy/php-htmldiff "Average time to resolve an issue"
[badge_issues]: http://isitmaintained.com/project/caxy/php-htmldiff "Percentage of issues still open"
[upstream]: https://github.com/rashid2538/php-htmldiff
[htmldiffbundle]: https://github.com/caxy/HtmlDiffBundle
[differences]: https://github.com/caxy/php-htmldiff/blob/master/doc/differences.rst
[changelog]: https://github.com/caxy/php-htmldiff/blob/master/CHANGELOG.md
[contributing]: https://github.com/caxy/php-htmldiff/blob/master/CONTRIBUTING.md
[gnu]: http://www.gnu.org/licenses/gpl-2.0.html
[license]: https://github.com/caxy/php-htmldiff/blob/master/LICENSE
[code_of_conduct]: https://github.com/caxy/php-htmldiff/blob/master/CODE_OF_CONDUCT.md
[composer]: http://getcomposer.org/
[contributor_covenant]: http://contributor-covenant.org/
[rashid2538]: https://github.com/rashid2538
[willdurand]: https://github.com/willdurand
[open sourcing libraries]: http://williamdurand.fr/2013/07/04/on-open-sourcing-libraries/

@ -0,0 +1,43 @@
{
"name": "caxy/php-htmldiff",
"type": "library",
"description": "A library for comparing two HTML files/snippets and highlighting the differences using simple HTML.",
"keywords": [
"diff",
"html"
],
"homepage": "https://github.com/caxy/php-htmldiff",
"license": "GPL-2.0",
"authors": [
{
"name": "Josh Schroeder",
"email": "jschroeder@caxy.com",
"homepage": "http://www.caxy.com"
}
],
"support": {
"issues": "https://github.com/caxy/php-htmldiff/issues"
},
"require": {
"php": ">=5.3.3",
"ezyang/htmlpurifier": "^4.7"
},
"require-dev": {
"phpunit/phpunit": "~4.8",
"doctrine/cache": "~1.0"
},
"suggest": {
"doctrine/cache": "Used for caching the calculated diffs using a Doctrine Cache Provider"
},
"autoload": {
"psr-0": { "Caxy\\HtmlDiff": "lib/" }
},
"autoload-dev": {
"psr-4": { "Caxy\\Tests\\": "tests/Caxy/Tests" }
},
"extra": {
"branch-alias": {
"dev-master": "0.1.x-dev"
}
}
}

@ -0,0 +1 @@
Just write the code as shown in php file and enjoy.

@ -0,0 +1,16 @@
{
"name": "php-htmldiff-demo",
"dependencies": {
"bootstrap": "v4.0.0-alpha.2",
"angular": "1.5.0",
"clipboard": "^1.5.8",
"font-awesome": "^4.5.0",
"angular-sanitize": "^1.5.0",
"tether": "^1.2.0",
"ng-ckeditor": "^0.2.1",
"ckeditor": "^4.5.7",
"angular-ui": "^0.4.0",
"AngularJS-Toaster": "angularjs-toaster#^1.2.0",
"angular-bootstrap": "^1.1.2"
}
}

@ -0,0 +1,276 @@
/*
Document : codes
Created on : Sep 23, 2013, 4:41:58 PM
Author : mgersten
Description: CSS related to I-code specific display
*/
.diff-list > li.normal,
.diff-list > li.removed,
.diff-list > li.replacement{
display: table-row;
}
.diff-list > li.normal:before,
.diff-list > li.removed:before,
.diff-list > li.replacement:before{
width: 15px;
overflow: hidden;
content: counters(section,".") ". ";
display: table-cell;
text-indent: -1em;
padding-left: 1em;
}
/* overwrite width of :before on ballot pages */
.ballot-monograph .diff-list > li.normal:before,
.ballot-monograph .diff-list > li.removed:before,
.ballot-monograph .diff-list > li.replacement:before {
width: 30px;
}
.diff-list > li.normal:before,
li.replacement + li.replacement:before,
.diff-list > li.replacement:first-child:before{
counter-increment: section;
}
.diff-list > li.removed:before{
counter-increment: section;
text-decoration: line-through;
}
ol.diff-list li.removed + li.replacement {
counter-increment: none;
}
ol.diff-list li.removed + li.removed + li.replacement {
counter-increment: section -1;
}
ol.diff-list li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -2;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -3;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -4;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -5;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -6;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -7;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -8;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -9;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement{
counter-increment: section -10;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -11;
}
.diff-list > li.replacement:before,
.diff-list > li.new:before{
text-decoration: underline;
}
.diff-list > li > div{
display: inline;
}
.diff-list{
list-style: none;
counter-reset: section;
display: table;
}
.sectionContent ol,
.revision-container ol{
list-style: none;
counter-reset: section;
}
.sectionContent ol li,
.revision-container ol li{
position: relative;
padding: 0 0 0 30px;
color: #000000;
text-indent: 0px;
}
.sectionContent ol ol li,
.revision-container ol ol li{
padding: 0 0 0 45px;
}
.sectionContent ol ol ol li,
.revision-container ol ol ol li{
padding: 0 0 0 60px;
}
.sectionContent ol ol ol ol li,
.revision-container ol ol ol ol li{
padding: 0 0 0 75px;
}
.sectionContent ol ol ol ol ol li,
.revision-container ol ol ol ol ol li{
padding: 0 0 0 90px;
}
.sectionContent ol ol ol ol ol ol li,
.revision-container ol ol ol ol ol ol li{
padding: 0 0 0 105px;
}
.sectionContent ol ol ol ol ol ol ol li,
.revision-container ol ol ol ol ol ol ol li{
padding: 0 0 0 120px;
}
.sectionContent ol ol ol ol ol ol ol ol li,
.revision-container ol ol ol ol ol ol ol ol li{
padding: 0 0 0 135px;
}
.sectionContent ol ol ol ol ol ol ol ol ol li,
.revision-container ol ol ol ol ol ol ol ol ol li{
padding: 0 0 0 160px;
}
.sectionContent ol ol ol ol ol ol ol ol ol ol li,
.revision-container ol ol ol ol ol ol ol ol ol ol li{
padding: 0 0 0 175px;
}
.sectionContent ol li:before,
.revision-container ol li:before{
counter-increment: section;
content:counters(section, ".") ".";
position: absolute;
left: 0px;
}
li.italic {
font-style: italic;
}
.sectionTitle {
text-align: center;
margin: 23px 0 15px;
}
.precontent-title {
margin-bottom: 10px;
display: block;
}
.secondParagraph {
text-indent: 1em;
}
.indentedParagraph {
margin-left: 1em;
}
.outdentOneLevel {
margin-left: -75px;
}
ol.list-alpha-upper > li:before {
content: counter(section, upper-alpha) ".";
}
ol.list-alpha-lower > li:before {
content: counter(section, lower-alpha) ".";
}
ol.list-roman-upper > li:before {
content: counter(section, upper-roman) ".";
}
ol.list-roman-lower > li:before {
content: counter(section, lower-roman) ".";
}
ol.list-roman-lower-parentheses > li:before {
content: "(" counter(section, lower-roman) ")";
}
ol.list-alpha-lower-parentheses > li:before {
content: "(" counter(section, lower-alpha) ")";
}
ol.list-numeric-right-parenthesis > li:before {
content: counter(section) ")";
}
.revision-content,
.revision-content p,
.revision-content ol,
.revision-content ul,
.revision-content li,
.revision-content td,
.sectionContent,
.sectionContent p,
.sectionContent ol,
.sectionContent ul,
.sectionContent li,
.sectionContent td,
.revision-notes {
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif !important;
font-size: 14px !important;
font-weight: normal !important;
line-height: 18px !important;
color:#404040 !important;
}
.revision-content .footnotes p,
.revision-content .footnotes ol,
.revision-content .footnotes ul,
.revision-content .footnotes li,
.revision-content .footnotes td,
.sectionContent .footnotes p,
.sectionContent .footnotes ol,
.sectionContent .footnotes ul,
.sectionContent .footnotes li,
.sectionContent .footnotes td {
font-size: 12px !important;
}
.diff-list ul.exception ol ,
.sectionContent ul.exception ol ,
.revision-container ul.exception ol{
list-style: none;
counter-reset: exception-section;
/* Creates a new instance of the section counter with each ol element */
}
ul.exception,
ul.exception li:before {
list-style: none;
content: none;
}
.diff-list ul.exception ol > li:before,
.sectionContent ul.exception ol > li:before,
.revision-container ul.exception ol > li:before {
counter-increment: exception-section;
content:counters(exception-section, ".") ".";
}
.sectionContent i > sub,
.revision-container i > sub {
font-style: italic;
}
div.print-section a {
text-align: center;
color: #818181;
display: block;
text-decoration: none;
font-size: 0.8em;
}
div.print-section a.disabled {
display: none;
}
.print-link {
color: #818181;
}
.print-link.disabled {
cursor: text;
text-decoration: none;
}
/* Hack for generic styles that shouldn't exist in the database */
.content_bold {
font-weight: bold;
}
.content_italics {
font-style: italic;
}

@ -0,0 +1,212 @@
(function() {
'use strict';
angular
.module('demo')
.controller('DemoController', DemoController);
DemoController.$inject = ['$q', '$http', '$sce', '$timeout'];
function DemoController($q, $http, $sce, $timeout) {
var vm = this;
vm.demos = [];
vm.updateDelay = 800;
vm.currentTimeout = null;
vm.loading = false;
vm.waiting = false;
vm.diffName = '';
vm.currentDemo = null;
vm.debugOutput = {};
vm.matchThreshold = 80;
vm.overrides = [];
vm.legislativeOverride = null;
vm.tableDiffNumber = 1;
vm.tableDiffing = true;
vm.editorOptions = {};
vm.ckEditorEnabled = true;
vm.trustHtml = trustHtml;
vm.reset = reset;
vm.update = update;
vm.swapText = swapText;
vm.diffDemo = diffDemo;
vm.diffOverride = diffOverride;
vm.diffTableDemo = diffTableDemo;
vm.updateDemo = updateDemo;
vm.saveNewDemo = saveNewDemo;
vm.toggleCkEditor = toggleCkEditor;
activate();
function activate() {
var promises = [loadDemos(), loadOverrides()];
return $q.all(promises).then(function() {
});
}
function trustHtml(text) {
return typeof text !== 'undefined' ? $sce.trustAsHtml(text) : '';
}
function toggleCkEditor() {
vm.ckEditorEnabled = !vm.ckEditorEnabled;
}
function reset() {
vm.oldText = '';
vm.newText = '';
vm.diff = '';
vm.loading = false;
vm.waiting = false;
vm.currentDemo = null;
vm.legislativeOverride = null;
if (vm.currentTimeout) {
$timeout.cancel(vm.currentTimeout);
}
}
function update() {
if (vm.currentTimeout) {
$timeout.cancel(vm.currentTimeout);
}
vm.currentTimeout = $timeout(function () {
getDiff();
}, vm.updateDelay);
vm.diff = null;
vm.waiting = true;
}
function swapText() {
var oldText = vm.oldText;
vm.oldText = vm.newText;
vm.newText = oldText;
getDiff();
}
function diffDemo(index) {
if (typeof index === 'undefined') {
index = 0;
}
vm.oldText = vm.demos[index]['old'];
vm.newText = vm.demos[index]['new'];
getDiff();
vm.currentDemo = vm.demos[index];
vm.legislativeOverride = vm.demos[index].hasOwnProperty('legislativeOverride') ? vm.demos[index]['legislativeOverride'] : null;
}
function diffOverride(override, index) {
vm.oldText = override.old;
vm.newText = override.new;
vm.legislativeOverride = override.override;
getDiff();
vm.currentDemo = override;
if (!vm.currentDemo.name) {
vm.currentDemo.name = 'Override Demo ' + (index + 1);
}
vm.currentDemo.isOverride = true;
}
function diffTableDemo(index) {
loadTableDiff(index)
.then(function(response) {
vm.oldText = response.data.old;
vm.newText = response.data.new;
vm.legislativeOverride = null;
getDiff();
vm.currentDemo = null;
})
.catch(function(e) {
console.log(e);
});
}
function updateDemo() {
vm.currentDemo.old = vm.oldText;
vm.currentDemo.new = vm.newText;
return $http.post('save_demo.php', vm.currentDemo)
.then(function (response) {
return response;
});
}
function saveNewDemo() {
var newIndex = vm.demos.length + 1;
if (vm.diffName.length === 0) {
vm.diffName = 'DEMO ' + newIndex;
}
var newDemo = {'old': vm.oldText, 'new': vm.newText, 'name': vm.diffName, 'legislativeOverride': vm.legislativeOverride};
vm.demos.push(newDemo);
return $http.post('save_demo.php', newDemo)
.then(function (response) {
vm.currentDemo = newDemo;
return vm.currentDemo;
});
}
function loadTableDiff(index) {
return $http({
url: 'load_table_diff.php',
method: 'POST',
data: {index: index},
header: {'Content-Type': 'application/json; charset=UTF-8'}
});
}
function getDiff() {
vm.waiting = false;
vm.loading = true;
vm.diff = null;
$http.post('index.php', {
oldText: vm.oldText,
newText: vm.newText,
matchThreshold: vm.matchThreshold,
tableDiffing: vm.tableDiffing
})
.then(function (response) {
vm.diff = response.data.hasOwnProperty('diff') ? response.data.diff : response.data;
vm.loading = false;
addDebugOutput(response.data.debug);
})
.catch(function (response) {
console.error('Gists error', response.status, response.data);
});
}
function loadDemos() {
$http.get('demos.json')
.success(function (data) {
vm.demos = data;
});
}
function loadOverrides() {
return $http.get('diff.json')
.then(function (response) {
vm.overrides = response.data;
return vm.overrides;
});
}
function addDebugOutput(data) {
angular.forEach(data, function(value, key) {
data[key] = {
messages: value,
isCollapsed: true
};
});
vm.debugOutput = data;
}
}
})();

@ -0,0 +1,246 @@
<!DOCTYPE html>
<html lang="en" ng-app="demo">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<link rel="stylesheet" href="bower_components/tether/dist/css/tether.min.css">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="bower_components/ng-ckeditor/ng-ckeditor.css">
<link rel="stylesheet" href="bower_components/angular-ui/build/angular-ui.min.css">
<link rel="stylesheet" href="bower_components/AngularJS-Toaster/toaster.min.css">
<link rel="stylesheet" href="bower_components/angular-bootstrap/ui-bootstrap-csp.css">
<link type="text/css" href="codes.css" rel="stylesheet">
</head>
<body ng-controller="DemoController as vm">
<!-- Main Navigation -->
<nav class="navbar navbar-light bg-faded">
<a class="navbar-brand" href="#">caxy/php-htmldiff</a>
<ul class="nav navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Demo <span class="sr-only">(current)</span></a>
</li>
</ul>
</nav>
<!-- Main Content -->
<div class="container-fluid">
<!-- diff controls and input -->
<div class="card">
<div class="card-header">
<button class="btn btn-secondary btn-sm" type="button" data-toggle="collapse" data-target="#diffControls">
<i class="fa fa-compress"></i>
</button>
Diff Controls
<div class="pull-right">
<div ng-if="vm.currentDemo">
<p>
Current Demo: {{ vm.currentDemo.name }}
<button ng-if="!vm.currentDemo.isOverride" type="button" class="btn btn-primary btn-sm" ng-click="vm.updateDemo()">
Update Demo
</button>
</p>
</div>
</div>
</div>
<div class="card-block collapse in" id="diffControls">
<!-- Diff controls -->
<div class="form-inline row">
<!-- Reset button -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-sm btn-danger-outline" ng-click="vm.reset()">RESET</button>
</div>
<!-- Load demo buttons w/ dropdowns -->
<div class="btn-group" role="group">
<div class="btn-group btn-group-sm">
<button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Load Custom Demo
</button>
<div class="dropdown-menu">
<a href ng-repeat="demo in vm.demos" type="button" class="dropdown-item" ng-class="{active: demo == vm.currentDemo}" ng-click="vm.diffDemo($index)">
{{ demo.name }}
</a>
</div>
</div>
<div class="btn-group btn-group-sm" role="group">
<button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Load Diff Override Demo
</button>
<div class="dropdown-menu">
<a href class="dropdown-item" ng-repeat="override in vm.overrides" ng-class="{active: vm.currentDemo == override}" ng-click="vm.diffOverride(override, $index)">
Override Demo {{ $index + 1 }}
</a>
</div>
</div>
</div>
<!-- Load table diff button and input -->
<div class="form-group">
<div class="input-group input-group-sm" role="group">
<span class="input-group-btn">
<button ng-click="vm.diffTableDemo(vm.tableDiffNumber)" type="button" class="btn btn-secondary">Load Table Diff</button>
</span>
<input type="number" class="form-control" ng-model="vm.tableDiffNumber" />
</div>
</div>
<!-- Match Threshold -->
<div class="form-group">
<label for="matchThreshold">Match Threshold</label>
<input type="number" class="form-control form-control-sm" ng-model="vm.matchThreshold" id="matchThreshold" ng-change="vm.update()">
</div>
<!-- Table Diffing Checkbox -->
<div class="form-group">
<label class="checkbox-inline" for="tableDiffing">
<input type="checkbox" ng-model="vm.tableDiffing" id="tableDiffing" ng-change="vm.update()"> Use Table Diffing
</label>
</div>
<!-- Swap Text Button -->
<button type="button" class="btn btn-secondary btn-sm" ng-click="vm.swapText()">Swap Text</button>
<!-- Save as New Demo -->
<div class="form-group">
<div class="input-group input-group-sm">
<input type="text" class="form-control" placeholder="Demo Name" ng-model="vm.diffName" />
<span class="input-group-btn">
<button class="btn btn-secondary" type="button" ng-click="vm.saveNewDemo()">Save as New Demo</button>
</span>
</div>
</div>
</div><!-- end of diff controls -->
<!-- Diff Inputs (Old Text / New Text) -->
<div class="form-group row m-t-2">
<div class="col-sm-6">
<label class="form-control-label" for="oldText">
Old Text
<button type="button" class="btn btn-sm btn-secondary clipboard" data-clipboard-target="#oldText">
<i class="fa fa-clipboard"></i>
</button>
<a ng-click="vm.toggleCkEditor()">Toggle CK</a>
</label>
<div ng-if="vm.ckEditorEnabled">
<textarea ckeditor="vm.editorOptions" ng-model="vm.oldText" id="oldText" ng-change="vm.update()"></textarea>
</div>
<textarea ng-if="!vm.ckEditorEnabled" class="form-control" ng-model="vm.oldText" name="old_text" ng-change="vm.update()" rows="15"></textarea>
</div>
<div class="col-sm-6">
<label class="form-control-label" for="newText">
New Text
<button type="button" class="btn btn-sm btn-secondary clipboard" data-clipboard-target="#newText">
<i class="fa fa-clipboard"></i>
</button>
<a ng-click="vm.toggleCkEditor()">Toggle CK</a>
</label>
<div ng-if="vm.ckEditorEnabled">
<textarea ckeditor="vm.editorOptions" ng-model="vm.newText" id="newText" ng-change="vm.update()"></textarea>
</div>
<textarea ng-if="!vm.ckEditorEnabled" class="form-control" ng-model="vm.newText" name="new_text" ng-change="vm.update()" rows="15"></textarea>
</div>
</div><!-- end of diff inputs -->
</div><!-- end of diff controls card-block -->
</div><!-- end of diff controls card -->
<!-- Diff Output -->
<div class="card">
<div class="card-header">
<div class="btn-group">
<button class="btn btn-secondary btn-sm" type="button" data-toggle="collapse" data-target="#diffBlock">
<i class="fa fa-compress"></i>
</button>
<button type="button" class="btn btn-sm btn-secondary clipboard" data-clipboard-target="#diffPreview">
<i class="fa fa-clipboard"></i>
</button>
<button type="button" class="btn btn-sm btn-secondary" ng-click="vm.update()">
<i class="fa fa-refresh"></i>
</button>
</div>
Diff Output
<span ng-show="vm.loading || vm.waiting">- {{ vm.loading ? 'Loading' : 'Waiting' }}...</span>
</div>
<div class="card-block collapse in" id="diffBlock">
<div class="form-group row">
<div class="col-sm-12">
<div id="diffPreview" class="html-preview" ng-bind-html="vm.trustHtml(vm.diff)"></div>
</div>
</div>
</div>
</div><!-- end of diff output -->
<!-- Diff Output (HTML) -->
<div class="card">
<div class="card-header">
<button class="btn btn-secondary btn-sm" type="button" data-toggle="collapse" data-target="#rawDiffBlock">
<i class="fa fa-compress"></i>
</button>
<label class="form-control-label" for="rawDiff">
Diff Output (HTML)
<button type="button" class="btn btn-sm btn-secondary clipboard" data-clipboard-target="#rawDiff">
<i class="fa fa-clipboard"></i>
</button>
</label>
<span ng-show="vm.loading || vm.waiting">- {{ vm.loading ? 'Loading' : 'Waiting' }}...</span>
</div>
<div class="card-block collapse" id="rawDiffBlock">
<div class="form-group row">
<div class="col-sm-12">
<textarea id="rawDiff" class="form-control" ng-model="vm.diff" name="diff" readonly ng-change="vm.update()" rows="15"></textarea>
</div>
</div>
</div>
</div><!-- end of diff output (html) -->
<!-- Debug Output -->
<div class="row">
<div class="col-sm-6">
<h3>Debug Output</h3>
<div class="card" ng-repeat="(category, categoryMessages) in vm.debugOutput track by category">
<div class="card-header">
<h5>
<a ng-click="categoryMessages.isCollapsed = !categoryMessages.isCollapsed">
{{ category }}
</a>
</h5>
</div>
<div class="card-block" uib-collapse="categoryMessages.isCollapsed">
<pre ng-repeat="message in categoryMessages.messages track by $index">
{{ message }}
</pre>
</div>
</div>
</div>
<div class="col-sm-6" ng-show="vm.legislativeOverride">
<h3>Legislative Override</h3>
<div class="html-preview" ng-bind-html="vm.trustHtml(vm.legislativeOverride)"></div>
</div>
</div><!-- end of debug output -->
</div><!-- end of outer container div -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/tether/dist/js/tether.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script src="bower_components/clipboard/dist/clipboard.min.js"></script>
<script src="bower_components/ckeditor/ckeditor.js"></script>
<script src="bower_components/ng-ckeditor/ng-ckeditor.min.js"></script>
<script src="bower_components/angular-ui/build/angular-ui.min.js"></script>
<script src="bower_components/angular-animate/angular-animate.min.js"></script>
<script src="bower_components/AngularJS-Toaster/toaster.min.js"></script>
<script src="bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<script type="text/javascript" src="demo.module.js"></script>
<script type="text/javascript" src="demo.controller.js"></script>
<script>
new Clipboard('.clipboard');
</script>
</body>
</html>

@ -0,0 +1,9 @@
(function() {
'use strict';
angular.module('demo', [
'ngSanitize',
'ngCkeditor',
'ui.bootstrap'
]);
})();

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -0,0 +1,56 @@
<?php
use Caxy\HtmlDiff\HtmlDiff;
ini_set('display_errors', 1);
error_reporting(E_ALL);
require __DIR__.'/../vendor/autoload.php';
$debugOutput = array();
function addDebugOutput($value, $key = 'general')
{
global $debugOutput;
if (!is_string($value)) {
$value = var_export($value, true);
}
if (!array_key_exists($key, $debugOutput)) {
$debugOutput[$key] = array();
}
$debugOutput[$key][] = $value;
}
$input = file_get_contents('php://input');
if ($input) {
header('Content-Type: application/json');
$data = json_decode($input, true);
$oldText = $data['oldText'];
$newText = $data['newText'];
$useTableDiffing = isset($data['tableDiffing']) ? $data['tableDiffing'] : true;
$diff = new HtmlDiff($oldText, $newText, 'UTF-8', array());
if (array_key_exists('matchThreshold', $data)) {
$diff->setMatchThreshold($data['matchThreshold']);
}
$diff->setUseTableDiffing($useTableDiffing);
$diffOutput = $diff->build();
$diffOutput = mb_convert_encoding($diffOutput, 'UTF-8');
$jsonOutput = json_encode(array('diff' => $diffOutput, 'debug' => $debugOutput));
if (false === $jsonOutput) {
throw new \Exception('Failed to encode JSON: '.json_last_error_msg());
}
echo $jsonOutput;
} else {
header('Content-Type: text/html');
echo file_get_contents('demo.html');
}

@ -0,0 +1,22 @@
<?php
$requestBody = file_get_contents('php://input');
$requestJson = json_decode($requestBody, true);
if (empty($requestJson['index'])) {
throw new \Exception('index is required.');
}
$jsonFile = __DIR__.'/tablediffs.json';
$demoStorage = json_decode(file_get_contents($jsonFile), true);
if (!array_key_exists($requestJson['index'], $demoStorage)) {
throw new \Exception('index not found.');
}
$targetDemo = $demoStorage[$requestJson['index']];
header('Content-Type: application/json');
echo json_encode($targetDemo);

@ -0,0 +1,46 @@
<?php
$requestBody = file_get_contents('php://input');
$requestJson = json_decode($requestBody, true);
if (empty($requestJson['old']) && empty($requestJson['new'])) {
throw new \Exception('Old text or new text is required.');
}
$jsonFile = __DIR__.'/demos.json';
$demoStorage = json_decode(file_get_contents($jsonFile), true);
if (empty($requestJson['name'])) {
$requestJson['name'] = 'DEMO '.count($demoStorage);
}
$oldText = $requestJson['old'];
$newText = $requestJson['new'];
$name = $requestJson['name'];
$legislativeOverride = !empty($requestJson['legislativeOverride']) ? $requestJson['legislativeOverride'] : null;
$existingDemoIndex = null;
foreach ($demoStorage as $index => $demo) {
if ($demo['name'] === $name) {
$existingDemoIndex = $index;
break;
}
}
if ($existingDemoIndex !== null) {
$demoStorage[$existingDemoIndex]['old'] = $oldText;
$demoStorage[$existingDemoIndex]['new'] = $newText;
} else {
$demoStorage[] = array(
'name' => $name,
'old' => $oldText,
'new' => $newText,
'legislativeOverride' => $legislativeOverride,
);
}
if (false === file_put_contents($jsonFile, json_encode($demoStorage))) {
throw new \Exception("Unable to save to file: $jsonFile");
}

File diff suppressed because one or more lines are too long

@ -0,0 +1,116 @@
Differences from rashid2538/php-htmldiff
========================================
.. contents:: Table of Contents
Code Styling and Clean-up
-------------------------
* Added namespaces, split up classes to their own files, some code styling changes
Enhancements
------------
* Allow the specialCaseOpeningTags and specialCaseClosingTags properties to be modified by passing an array into the constructor or using set/add/remove functions
* Updated the demo to accept input and diff via AJAX
* Added static properties for the default config variables
Bug Fixes
---------
* Fixed an index out of range bug (may have been fixed on the original repo since): c9ba1fa_
* Check for empty oldText or newText before processing del or ins in processReplaceOperation function
New Features
------------
Isolated Diffing of certain HTML elements
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is the one of the largest changes from the original repository.
For more information, see the release notes for tag `0.0.6`_
List Diffing
^^^^^^^^^^^^
Similar to the Isolated Diffing feature, but specifically for HTML lists.
More information is to come on this, and there will definitely be some tweaks and configuration options added for this
feature. Currently there is no easy way to enable/disable the feature, so if you're having issues with it I suggest
using the `0.0.6`_ or earlier release.
Table Diffing
^^^^^^^^^^^^^
Similar to the Isolated Diffing and List Diffing features, but specifically for HTML tables.
More information to come on this soon.
New option to group together diffed words by not matching on whitespace-only. Option is enabled by default.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This was a specific requirement for an application we use this library for. The original library would replace
single words at a time, but enabling this feature will group replacements instead. See example below.
Old Text::
testing some text here and there
New Text::
testing other words here and there
With $groupDiffs = false (original functionality)::
testing <del>some</del><ins>other</ins> <del>text</del><ins>words</ins> here and there
With $groupDiffs = true (new feature)::
testing <del>some text</del><ins>other words</ins> here and there
Change diffing to strike through entire words/numbers if they contain periods or commas within the word
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This change introduced a new property ``$specialCaseChars``, which defaults to the following characters: ``.`` ``,`` ``(`` ``)`` ``'``
This feature can be "disabled" by simply setting the $specialCaseChars to an empty array i.e. ``$diff->setSpecialCaseChars(array())``
In the original library, special characters are treated as their own "words" even if they are in the middle of a word.
This causes weird things to happen when diffing numbers that have a comma or a period in the middle of the number.
For example, diffing ``10,000.50`` against ``11,100.75`` gives you:
Original Functionality::
<del class="diffmod">10</del><ins class="diffmod">11</ins>,<del class="diffmod">000</del><ins class="diffmod">100</ins>.<del class="diffmod">50</del><ins class="diffmod">75</ins>
This is very difficult to read, so the new feature allows you to add ``.`` and ``,`` to the ``$specialCaseChars`` array in order
to get output that looks like::
<del class="diffmod">10,000.50</del><ins class="diffmod">11,100.75</ins>
Note: It will *not* treat the specialCaseChars as part of the word if it is at the beginning or end of the word,
so normal periods or commas at the end of words will still be diffed like the original.
Added option to insert a space between ``<del>`` and ``<ins>`` tags. Disabled by default.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This was a requirement for one our applications that uses this library.
New property ``$insertSpaceInReplace`` was added, and setting it to true will simply add a space between
the ``<del>`` and ``<ins>`` tags in replace operations, which was requested for easier reading.
Enable it by calling ``$diff->setInsertSpaceInReplace(true);``
Original Functionality::
<del>Old</del><ins>New</ins>
New Functionality::
<del>Old</del> <ins>New</ins>
.. _c9ba1fa: https://github.com/caxy/php-htmldiff/commit/c9ba1fab6777cd47427477f8d747293bb01ef1e8
.. _0.0.6: https://github.com/caxy/php-htmldiff/releases/tag/0.0.6

@ -0,0 +1,490 @@
<?php
namespace Caxy\HtmlDiff;
/**
* Class AbstractDiff
* @package Caxy\HtmlDiff
*/
abstract class AbstractDiff
{
/**
* @var array
*
* @deprecated since 0.1.0
*/
public static $defaultSpecialCaseTags = array('strong', 'b', 'i', 'big', 'small', 'u', 'sub', 'sup', 'strike', 's', 'p');
/**
* @var array
*
* @deprecated since 0.1.0
*/
public static $defaultSpecialCaseChars = array('.', ',', '(', ')', '\'');
/**
* @var bool
*
* @deprecated since 0.1.0
*/
public static $defaultGroupDiffs = true;
/**
* @var HtmlDiffConfig
*/
protected $config;
/**
* @var string
*/
protected $content;
/**
* @var string
*/
protected $oldText;
/**
* @var string
*/
protected $newText;
/**
* @var array
*/
protected $oldWords = array();
/**
* @var array
*/
protected $newWords = array();
/**
* @var DiffCache[]
*/
private $diffCaches = array();
/**
* AbstractDiff constructor.
*
* @param string $oldText
* @param string $newText
* @param string $encoding
* @param null|array $specialCaseTags
* @param null|bool $groupDiffs
*/
public function __construct($oldText, $newText, $encoding = 'UTF-8', $specialCaseTags = null, $groupDiffs = null)
{
mb_substitute_character(0x20);
$this->config = HtmlDiffConfig::create()->setEncoding($encoding);
if ($specialCaseTags !== null) {
$this->config->setSpecialCaseTags($specialCaseTags);
}
if ($groupDiffs !== null) {
$this->config->setGroupDiffs($groupDiffs);
}
$this->oldText = $this->purifyHtml(trim($oldText));
$this->newText = $this->purifyHtml(trim($newText));
$this->content = '';
}
/**
* @return bool|string
*/
abstract public function build();
/**
* @return DiffCache|null
*/
protected function getDiffCache()
{
if (!$this->hasDiffCache()) {
return null;
}
$hash = spl_object_hash($this->getConfig()->getCacheProvider());
if (!array_key_exists($hash, $this->diffCaches)) {
$this->diffCaches[$hash] = new DiffCache($this->getConfig()->getCacheProvider());
}
return $this->diffCaches[$hash];
}
/**
* @return bool
*/
protected function hasDiffCache()
{
return null !== $this->getConfig()->getCacheProvider();
}
/**
* @return HtmlDiffConfig
*/
public function getConfig()
{
return $this->config;
}
/**
* @param HtmlDiffConfig $config
*
* @return AbstractDiff
*/
public function setConfig(HtmlDiffConfig $config)
{
$this->config = $config;
return $this;
}
/**
* @return int
*
* @deprecated since 0.1.0
*/
public function getMatchThreshold()
{
return $this->config->getMatchThreshold();
}
/**
* @param int $matchThreshold
*
* @return AbstractDiff
*
* @deprecated since 0.1.0
*/
public function setMatchThreshold($matchThreshold)
{
$this->config->setMatchThreshold($matchThreshold);
return $this;
}
/**
* @param array $chars
*
* @deprecated since 0.1.0
*/
public function setSpecialCaseChars(array $chars)
{
$this->config->setSpecialCaseChars($chars);
}
/**
* @return array|null
*
* @deprecated since 0.1.0
*/
public function getSpecialCaseChars()
{
return $this->config->getSpecialCaseChars();
}
/**
* @param string $char
*
* @deprecated since 0.1.0
*/
public function addSpecialCaseChar($char)
{
$this->config->addSpecialCaseChar($char);
}
/**
* @param string $char
*
* @deprecated since 0.1.0
*/
public function removeSpecialCaseChar($char)
{
$this->config->removeSpecialCaseChar($char);
}
/**
* @param array $tags
*
* @deprecated since 0.1.0
*/
public function setSpecialCaseTags(array $tags = array())
{
$this->config->setSpecialCaseChars($tags);
}
/**
* @param string $tag
*
* @deprecated since 0.1.0
*/
public function addSpecialCaseTag($tag)
{
$this->config->addSpecialCaseTag($tag);
}
/**
* @param string $tag
*
* @deprecated since 0.1.0
*/
public function removeSpecialCaseTag($tag)
{
$this->config->removeSpecialCaseTag($tag);
}
/**
* @return array|null
*
* @deprecated since 0.1.0
*/
public function getSpecialCaseTags()
{
return $this->config->getSpecialCaseTags();
}
/**
* @return string
*/
public function getOldHtml()
{
return $this->oldText;
}
/**
* @return string
*/
public function getNewHtml()
{
return $this->newText;
}
/**
* @return string
*/
public function getDifference()
{
return $this->content;
}
/**
* @param bool $boolean
*
* @return $this
*
* @deprecated since 0.1.0
*/
public function setGroupDiffs($boolean)
{
$this->config->setGroupDiffs($boolean);
return $this;
}
/**
* @return bool
*
* @deprecated since 0.1.0
*/
public function isGroupDiffs()
{
return $this->config->isGroupDiffs();
}
/**
* @param string $tag
*
* @return string
*/
protected function getOpeningTag($tag)
{
return "/<".$tag."[^>]*/i";
}
/**
* @param string $tag
*
* @return string
*/
protected function getClosingTag($tag)
{
return "</".$tag.">";
}
/**
* @param string $str
* @param string $start
* @param string $end
*
* @return string
*/
protected function getStringBetween($str, $start, $end)
{
$expStr = explode( $start, $str, 2 );
if ( count( $expStr ) > 1 ) {
$expStr = explode( $end, $expStr[ 1 ] );
if ( count( $expStr ) > 1 ) {
array_pop( $expStr );
return implode( $end, $expStr );
}
}
return '';
}
/**
* @param string $html
*
* @return string
*/
protected function purifyHtml($html)
{
if ( class_exists( 'Tidy' ) && false ) {
$config = array( 'output-xhtml' => true, 'indent' => false );
$tidy = new tidy();
$tidy->parseString( $html, $config, 'utf8' );
$html = (string) $tidy;
return $this->getStringBetween( $html, '<body>' );
}
return $html;
}
protected function splitInputsToWords()
{
$this->oldWords = $this->convertHtmlToListOfWords( $this->explode( $this->oldText ) );
$this->newWords = $this->convertHtmlToListOfWords( $this->explode( $this->newText ) );
}
/**
* @param string $text
*
* @return bool
*/
protected function isPartOfWord($text)
{
return ctype_alnum(str_replace($this->config->getSpecialCaseChars(), '', $text));
}
/**
* @param array $characterString
*
* @return array
*/
protected function convertHtmlToListOfWords($characterString)
{
$mode = 'character';
$current_word = '';
$words = array();
foreach ($characterString as $i => $character) {
switch ($mode) {
case 'character':
if ( $this->isStartOfTag( $character ) ) {
if ($current_word != '') {
$words[] = $current_word;
}
$current_word = "<";
$mode = 'tag';
} elseif (preg_match("/\s/", $character)) {
if ($current_word !== '') {
$words[] = $current_word;
}
$current_word = preg_replace('/\s+/S', ' ', $character);
$mode = 'whitespace';
} else {
if (
(ctype_alnum($character) && (strlen($current_word) == 0 || $this->isPartOfWord($current_word))) ||
(in_array($character, $this->config->getSpecialCaseChars()) && isset($characterString[$i+1]) && $this->isPartOfWord($characterString[$i+1]))
) {
$current_word .= $character;
} else {
$words[] = $current_word;
$current_word = $character;
}
}
break;
case 'tag' :
if ( $this->isEndOfTag( $character ) ) {
$current_word .= ">";
$words[] = $current_word;
$current_word = "";
if ( !preg_match('[^\s]', $character ) ) {
$mode = 'whitespace';
} else {
$mode = 'character';
}
} else {
$current_word .= $character;
}
break;
case 'whitespace':
if ( $this->isStartOfTag( $character ) ) {
if ($current_word !== '') {
$words[] = $current_word;
}
$current_word = "<";
$mode = 'tag';
} elseif ( preg_match( "/\s/", $character ) ) {
$current_word .= $character;
$current_word = preg_replace('/\s+/S', ' ', $current_word);
} else {
if ($current_word != '') {
$words[] = $current_word;
}
$current_word = $character;
$mode = 'character';
}
break;
default:
break;
}
}
if ($current_word != '') {
$words[] = $current_word;
}
return $words;
}
/**
* @param string $val
*
* @return bool
*/
protected function isStartOfTag($val)
{
return $val == "<";
}
/**
* @param string $val
*
* @return bool
*/
protected function isEndOfTag($val)
{
return $val == ">";
}
/**
* @param string $value
*
* @return bool
*/
protected function isWhiteSpace($value)
{
return !preg_match( '[^\s]', $value );
}
/**
* @param string $value
*
* @return array
*/
protected function explode($value)
{
// as suggested by @onassar
return preg_split( '//u', $value );
}
}

@ -0,0 +1,112 @@
<?php
namespace Caxy\HtmlDiff;
use Doctrine\Common\Cache\Cache;
/**
* Class DiffCache
* @package Caxy\HtmlDiff
*/
class DiffCache
{
/**
* @var Cache
*/
protected $cacheProvider;
/**
* DiffCache constructor.
*
* @param Cache $cacheProvider
*/
public function __construct(Cache $cacheProvider)
{
$this->cacheProvider = $cacheProvider;
}
/**
* @return Cache
*/
public function getCacheProvider()
{
return $this->cacheProvider;
}
/**
* @param Cache $cacheProvider
*
* @return DiffCache
*/
public function setCacheProvider($cacheProvider)
{
$this->cacheProvider = $cacheProvider;
return $this;
}
/**
* @param string $oldText
* @param string $newText
*
* @return bool
*/
public function contains($oldText, $newText)
{
return $this->cacheProvider->contains($this->getHashKey($oldText, $newText));
}
/**
* @param string $oldText
* @param string $newText
*
* @return string
*/
public function fetch($oldText, $newText)
{
return $this->cacheProvider->fetch($this->getHashKey($oldText, $newText));
}
/**
* @param string $oldText
* @param string $newText
* @param string $data
* @param int $lifeTime
*
* @return bool
*/
public function save($oldText, $newText, $data, $lifeTime = 0)
{
return $this->cacheProvider->save($this->getHashKey($oldText, $newText), $data, $lifeTime);
}
/**
* @param string $oldText
* @param string $newText
*
* @return bool
*/
public function delete($oldText, $newText)
{
return $this->cacheProvider->delete($this->getHashKey($oldText, $newText));
}
/**
* @return array|null
*/
public function getStats()
{
return $this->cacheProvider->getStats();
}
/**
* @param string $oldText
* @param string $newText
*
* @return string
*/
protected function getHashKey($oldText, $newText)
{
return sprintf('%s_%s', md5($oldText), md5($newText));
}
}

@ -0,0 +1,795 @@
<?php
namespace Caxy\HtmlDiff;
use Caxy\HtmlDiff\Table\TableDiff;
/**
* Class HtmlDiff
* @package Caxy\HtmlDiff
*/
class HtmlDiff extends AbstractDiff
{
/**
* @var array
*/
protected $wordIndices;
/**
* @var array
*/
protected $oldTables;
/**
* @var array
*/
protected $newTables;
/**
* @var array
*/
protected $newIsolatedDiffTags;
/**
* @var array
*/
protected $oldIsolatedDiffTags;
/**
* @param string $oldText
* @param string $newText
* @param HtmlDiffConfig|null $config
*
* @return self
*/
public static function create($oldText, $newText, HtmlDiffConfig $config = null)
{
$diff = new self($oldText, $newText);
if (null !== $config) {
$diff->setConfig($config);
}
return $diff;
}
/**
* @param $bool
*
* @return $this
*
* @deprecated since 0.1.0
*/
public function setUseTableDiffing($bool)
{
$this->config->setUseTableDiffing($bool);
return $this;
}
/**
* @param boolean $boolean
* @return HtmlDiff
*
* @deprecated since 0.1.0
*/
public function setInsertSpaceInReplace($boolean)
{
$this->config->setInsertSpaceInReplace($boolean);
return $this;
}
/**
* @return boolean
*
* @deprecated since 0.1.0
*/
public function getInsertSpaceInReplace()
{
return $this->config->isInsertSpaceInReplace();
}
/**
* @return string
*/
public function build()
{
if ($this->hasDiffCache() && $this->getDiffCache()->contains($this->oldText, $this->newText)) {
$this->content = $this->getDiffCache()->fetch($this->oldText, $this->newText);
return $this->content;
}
$this->splitInputsToWords();
$this->replaceIsolatedDiffTags();
$this->indexNewWords();
$operations = $this->operations();
foreach ($operations as $item) {
$this->performOperation( $item );
}
if ($this->hasDiffCache()) {
$this->getDiffCache()->save($this->oldText, $this->newText, $this->content);
}
return $this->content;
}
protected function indexNewWords()
{
$this->wordIndices = array();
foreach ($this->newWords as $i => $word) {
if ( $this->isTag( $word ) ) {
$word = $this->stripTagAttributes( $word );
}
if ( isset( $this->wordIndices[ $word ] ) ) {
$this->wordIndices[ $word ][] = $i;
} else {
$this->wordIndices[ $word ] = array( $i );
}
}
}
protected function replaceIsolatedDiffTags()
{
$this->oldIsolatedDiffTags = $this->createIsolatedDiffTagPlaceholders($this->oldWords);
$this->newIsolatedDiffTags = $this->createIsolatedDiffTagPlaceholders($this->newWords);
}
/**
* @param array $words
*
* @return array
*/
protected function createIsolatedDiffTagPlaceholders(&$words)
{
$openIsolatedDiffTags = 0;
$isolatedDiffTagIndicies = array();
$isolatedDiffTagStart = 0;
$currentIsolatedDiffTag = null;
foreach ($words as $index => $word) {
$openIsolatedDiffTag = $this->isOpeningIsolatedDiffTag($word, $currentIsolatedDiffTag);
if ($openIsolatedDiffTag) {
if ($openIsolatedDiffTags === 0) {
$isolatedDiffTagStart = $index;
}
$openIsolatedDiffTags++;
$currentIsolatedDiffTag = $openIsolatedDiffTag;
} elseif ($openIsolatedDiffTags > 0 && $this->isClosingIsolatedDiffTag($word, $currentIsolatedDiffTag)) {
$openIsolatedDiffTags--;
if ($openIsolatedDiffTags == 0) {
$isolatedDiffTagIndicies[] = array ('start' => $isolatedDiffTagStart, 'length' => $index - $isolatedDiffTagStart + 1, 'tagType' => $currentIsolatedDiffTag);
$currentIsolatedDiffTag = null;
}
}
}
$isolatedDiffTagScript = array();
$offset = 0;
foreach ($isolatedDiffTagIndicies as $isolatedDiffTagIndex) {
$start = $isolatedDiffTagIndex['start'] - $offset;
$placeholderString = $this->config->getIsolatedDiffTagPlaceholder($isolatedDiffTagIndex['tagType']);
$isolatedDiffTagScript[$start] = array_splice($words, $start, $isolatedDiffTagIndex['length'], $placeholderString);
$offset += $isolatedDiffTagIndex['length'] - 1;
}
return $isolatedDiffTagScript;
}
/**
* @param string $item
* @param null|string $currentIsolatedDiffTag
*
* @return false|string
*/
protected function isOpeningIsolatedDiffTag($item, $currentIsolatedDiffTag = null)
{
$tagsToMatch = $currentIsolatedDiffTag !== null
? array($currentIsolatedDiffTag => $this->config->getIsolatedDiffTagPlaceholder($currentIsolatedDiffTag))
: $this->config->getIsolatedDiffTags();
foreach ($tagsToMatch as $key => $value) {
if (preg_match("#<".$key."[^>]*>\\s*#iU", $item)) {
return $key;
}
}
return false;
}
/**
* @param string $item
* @param null|string $currentIsolatedDiffTag
*
* @return false|string
*/
protected function isClosingIsolatedDiffTag($item, $currentIsolatedDiffTag = null)
{
$tagsToMatch = $currentIsolatedDiffTag !== null
? array($currentIsolatedDiffTag => $this->config->getIsolatedDiffTagPlaceholder($currentIsolatedDiffTag))
: $this->config->getIsolatedDiffTags();
foreach ($tagsToMatch as $key => $value) {
if (preg_match("#</".$key."[^>]*>\\s*#iU", $item)) {
return $key;
}
}
return false;
}
/**
* @param Operation $operation
*/
protected function performOperation($operation)
{
switch ($operation->action) {
case 'equal' :
$this->processEqualOperation( $operation );
break;
case 'delete' :
$this->processDeleteOperation( $operation, "diffdel" );
break;
case 'insert' :
$this->processInsertOperation( $operation, "diffins");
break;
case 'replace':
$this->processReplaceOperation( $operation );
break;
default:
break;
}
}
/**
* @param Operation $operation
*/
protected function processReplaceOperation($operation)
{
$this->processDeleteOperation( $operation, "diffmod" );
$this->processInsertOperation( $operation, "diffmod" );
}
/**
* @param Operation $operation
* @param string $cssClass
*/
protected function processInsertOperation($operation, $cssClass)
{
$text = array();
foreach ($this->newWords as $pos => $s) {
if ($pos >= $operation->startInNew && $pos < $operation->endInNew) {
if ($this->config->isIsolatedDiffTagPlaceholder($s) && isset($this->newIsolatedDiffTags[$pos])) {
foreach ($this->newIsolatedDiffTags[$pos] as $word) {
$text[] = $word;
}
} else {
$text[] = $s;
}
}
}
$this->insertTag( "ins", $cssClass, $text );
}
/**
* @param Operation $operation
* @param string $cssClass
*/
protected function processDeleteOperation($operation, $cssClass)
{
$text = array();
foreach ($this->oldWords as $pos => $s) {
if ($pos >= $operation->startInOld && $pos < $operation->endInOld) {
if ($this->config->isIsolatedDiffTagPlaceholder($s) && isset($this->oldIsolatedDiffTags[$pos])) {
foreach ($this->oldIsolatedDiffTags[$pos] as $word) {
$text[] = $word;
}
} else {
$text[] = $s;
}
}
}
$this->insertTag( "del", $cssClass, $text );
}
/**
* @param Operation $operation
* @param int $pos
* @param string $placeholder
* @param bool $stripWrappingTags
*
* @return string
*/
protected function diffIsolatedPlaceholder($operation, $pos, $placeholder, $stripWrappingTags = true)
{
$oldText = implode("", $this->findIsolatedDiffTagsInOld($operation, $pos));
$newText = implode("", $this->newIsolatedDiffTags[$pos]);
if ($this->isListPlaceholder($placeholder)) {
return $this->diffList($oldText, $newText);
} elseif ($this->config->isUseTableDiffing() && $this->isTablePlaceholder($placeholder)) {
return $this->diffTables($oldText, $newText);
} elseif ($this->isLinkPlaceholder($placeholder)) {
return $this->diffLinks($oldText, $newText);
}
return $this->diffElements($oldText, $newText, $stripWrappingTags);
}
/**
* @param string $oldText
* @param string $newText
* @param bool $stripWrappingTags
*
* @return string
*/
protected function diffElements($oldText, $newText, $stripWrappingTags = true)
{
$wrapStart = '';
$wrapEnd = '';
if ($stripWrappingTags) {
$pattern = '/(^<[^>]+>)|(<\/[^>]+>$)/i';
$matches = array();
if (preg_match_all($pattern, $newText, $matches)) {
$wrapStart = isset($matches[0][0]) ? $matches[0][0] : '';
$wrapEnd = isset($matches[0][1]) ? $matches[0][1] : '';
}
$oldText = preg_replace($pattern, '', $oldText);
$newText = preg_replace($pattern, '', $newText);
}
$diff = HtmlDiff::create($oldText, $newText, $this->config);
return $wrapStart . $diff->build() . $wrapEnd;
}
/**
* @param string $oldText
* @param string $newText
*
* @return string
*/
protected function diffList($oldText, $newText)
{
$diff = ListDiffNew::create($oldText, $newText, $this->config);
return $diff->build();
}
/**
* @param string $oldText
* @param string $newText
*
* @return string
*/
protected function diffTables($oldText, $newText)
{
$diff = TableDiff::create($oldText, $newText, $this->config);
return $diff->build();
}
/**
* @param string $oldText
* @param string $newText
*
* @return string
*/
protected function diffLinks($oldText, $newText)
{
$oldHref = $this->getAttributeFromTag($oldText, 'href');
$newHref = $this->getAttributeFromTag($newText, 'href');
if ($oldHref != $newHref) {
return sprintf(
'%s%s',
$this->wrapText($oldText, 'del', 'diffmod diff-href'),
$this->wrapText($newText, 'ins', 'diffmod diff-href')
);
}
return $this->diffElements($oldText, $newText);
}
/**
* @param Operation $operation
*/
protected function processEqualOperation($operation)
{
$result = array();
foreach ($this->newWords as $pos => $s) {
if ($pos >= $operation->startInNew && $pos < $operation->endInNew) {
if ($this->config->isIsolatedDiffTagPlaceholder($s) && isset($this->newIsolatedDiffTags[$pos])) {
$result[] = $this->diffIsolatedPlaceholder($operation, $pos, $s);
} else {
$result[] = $s;
}
}
}
$this->content .= implode( "", $result );
}
/**
* @param string $text
* @param string $attribute
*
* @return null|string
*/
protected function getAttributeFromTag($text, $attribute)
{
$matches = array();
if (preg_match(sprintf('/<a\s+[^>]*%s=([\'"])(.*)\1[^>]*>/i', $attribute), $text, $matches)) {
return $matches[2];
}
return null;
}
/**
* @param string $text
*
* @return bool
*/
protected function isListPlaceholder($text)
{
return $this->isPlaceholderType($text, array('ol', 'dl', 'ul'));
}
/**
* @param string $text
*
* @return bool
*/
public function isLinkPlaceholder($text)
{
return $this->isPlaceholderType($text, 'a');
}
/**
* @param string $text
* @param array|string $types
* @param bool $strict
*
* @return bool
*/
protected function isPlaceholderType($text, $types, $strict = true)
{
if (!is_array($types)) {
$types = array($types);
}
$criteria = array();
foreach ($types as $type) {
if ($this->config->isIsolatedDiffTag($type)) {
$criteria[] = $this->config->getIsolatedDiffTagPlaceholder($type);
} else {
$criteria[] = $type;
}
}
return in_array($text, $criteria, $strict);
}
/**
* @param string $text
*
* @return bool
*/
protected function isTablePlaceholder($text)
{
return $this->isPlaceholderType($text, 'table');
}
/**
* @param Operation $operation
* @param int $posInNew
*
* @return array
*/
protected function findIsolatedDiffTagsInOld($operation, $posInNew)
{
$offset = $posInNew - $operation->startInNew;
return $this->oldIsolatedDiffTags[$operation->startInOld + $offset];
}
/**
* @param string $tag
* @param string $cssClass
* @param array $words
*/
protected function insertTag($tag, $cssClass, &$words)
{
while (true) {
if ( count( $words ) == 0 ) {
break;
}
$nonTags = $this->extractConsecutiveWords( $words, 'noTag' );
$specialCaseTagInjection = '';
$specialCaseTagInjectionIsBefore = false;
if ( count( $nonTags ) != 0 ) {
$text = $this->wrapText( implode( "", $nonTags ), $tag, $cssClass );
$this->content .= $text;
} else {
$firstOrDefault = false;
foreach ($this->config->getSpecialCaseOpeningTags() as $x) {
if ( preg_match( $x, $words[ 0 ] ) ) {
$firstOrDefault = $x;
break;
}
}
if ($firstOrDefault) {
$specialCaseTagInjection = '<ins class="mod">';
if ($tag == "del") {
unset( $words[ 0 ] );
}
} elseif ( array_search( $words[ 0 ], $this->config->getSpecialCaseClosingTags()) !== false ) {
$specialCaseTagInjection = "</ins>";
$specialCaseTagInjectionIsBefore = true;
if ($tag == "del") {
unset( $words[ 0 ] );
}
}
}
if ( count( $words ) == 0 && count( $specialCaseTagInjection ) == 0 ) {
break;
}
if ($specialCaseTagInjectionIsBefore) {
$this->content .= $specialCaseTagInjection . implode( "", $this->extractConsecutiveWords( $words, 'tag' ) );
} else {
$workTag = $this->extractConsecutiveWords( $words, 'tag' );
if ( isset( $workTag[ 0 ] ) && $this->isOpeningTag( $workTag[ 0 ] ) && !$this->isClosingTag( $workTag[ 0 ] ) ) {
if ( strpos( $workTag[ 0 ], 'class=' ) ) {
$workTag[ 0 ] = str_replace( 'class="', 'class="diffmod ', $workTag[ 0 ] );
$workTag[ 0 ] = str_replace( "class='", 'class="diffmod ', $workTag[ 0 ] );
} else {
$workTag[ 0 ] = str_replace( ">", ' class="diffmod">', $workTag[ 0 ] );
}
}
$this->content .= implode( "", $workTag ) . $specialCaseTagInjection;
}
}
}
/**
* @param string $word
* @param string $condition
*
* @return bool
*/
protected function checkCondition($word, $condition)
{
return $condition == 'tag' ? $this->isTag( $word ) : !$this->isTag( $word );
}
/**
* @param string $text
* @param string $tagName
* @param string $cssClass
*
* @return string
*/
protected function wrapText($text, $tagName, $cssClass)
{
return sprintf( '<%1$s class="%2$s">%3$s</%1$s>', $tagName, $cssClass, $text );
}
/**
* @param array $words
* @param string $condition
*
* @return array
*/
protected function extractConsecutiveWords(&$words, $condition)
{
$indexOfFirstTag = null;
$words = array_values($words);
foreach ($words as $i => $word) {
if ( !$this->checkCondition( $word, $condition ) ) {
$indexOfFirstTag = $i;
break;
}
}
if ($indexOfFirstTag !== null) {
$items = array();
foreach ($words as $pos => $s) {
if ($pos >= 0 && $pos < $indexOfFirstTag) {
$items[] = $s;
}
}
if ($indexOfFirstTag > 0) {
array_splice( $words, 0, $indexOfFirstTag );
}
return $items;
} else {
$items = array();
foreach ($words as $pos => $s) {
if ( $pos >= 0 && $pos <= count( $words ) ) {
$items[] = $s;
}
}
array_splice( $words, 0, count( $words ) );
return $items;
}
}
/**
* @param string $item
*
* @return bool
*/
protected function isTag($item)
{
return $this->isOpeningTag( $item ) || $this->isClosingTag( $item );
}
/**
* @param string $item
*
* @return bool
*/
protected function isOpeningTag($item)
{
return preg_match( "#<[^>]+>\\s*#iU", $item );
}
/**
* @param string $item
*
* @return bool
*/
protected function isClosingTag($item)
{
return preg_match( "#</[^>]+>\\s*#iU", $item );
}
/**
* @return Operation[]
*/
protected function operations()
{
$positionInOld = 0;
$positionInNew = 0;
$operations = array();
$matches = $this->matchingBlocks();
$matches[] = new Match( count( $this->oldWords ), count( $this->newWords ), 0 );
foreach ($matches as $i => $match) {
$matchStartsAtCurrentPositionInOld = ( $positionInOld == $match->startInOld );
$matchStartsAtCurrentPositionInNew = ( $positionInNew == $match->startInNew );
$action = 'none';
if ($matchStartsAtCurrentPositionInOld == false && $matchStartsAtCurrentPositionInNew == false) {
$action = 'replace';
} elseif ($matchStartsAtCurrentPositionInOld == true && $matchStartsAtCurrentPositionInNew == false) {
$action = 'insert';
} elseif ($matchStartsAtCurrentPositionInOld == false && $matchStartsAtCurrentPositionInNew == true) {
$action = 'delete';
} else { // This occurs if the first few words are the same in both versions
$action = 'none';
}
if ($action != 'none') {
$operations[] = new Operation( $action, $positionInOld, $match->startInOld, $positionInNew, $match->startInNew );
}
if ( count( $match ) != 0 ) {
$operations[] = new Operation( 'equal', $match->startInOld, $match->endInOld(), $match->startInNew, $match->endInNew() );
}
$positionInOld = $match->endInOld();
$positionInNew = $match->endInNew();
}
return $operations;
}
/**
* @return Match[]
*/
protected function matchingBlocks()
{
$matchingBlocks = array();
$this->findMatchingBlocks( 0, count( $this->oldWords ), 0, count( $this->newWords ), $matchingBlocks );
return $matchingBlocks;
}
/**
* @param int $startInOld
* @param int $endInOld
* @param int $startInNew
* @param int $endInNew
* @param array $matchingBlocks
*/
protected function findMatchingBlocks($startInOld, $endInOld, $startInNew, $endInNew, &$matchingBlocks)
{
$match = $this->findMatch( $startInOld, $endInOld, $startInNew, $endInNew );
if ($match !== null) {
if ($startInOld < $match->startInOld && $startInNew < $match->startInNew) {
$this->findMatchingBlocks( $startInOld, $match->startInOld, $startInNew, $match->startInNew, $matchingBlocks );
}
$matchingBlocks[] = $match;
if ( $match->endInOld() < $endInOld && $match->endInNew() < $endInNew ) {
$this->findMatchingBlocks( $match->endInOld(), $endInOld, $match->endInNew(), $endInNew, $matchingBlocks );
}
}
}
/**
* @param string $word
*
* @return string
*/
protected function stripTagAttributes($word)
{
$word = explode( ' ', trim( $word, '<>' ) );
return '<' . $word[ 0 ] . '>';
}
/**
* @param int $startInOld
* @param int $endInOld
* @param int $startInNew
* @param int $endInNew
*
* @return Match|null
*/
protected function findMatch($startInOld, $endInOld, $startInNew, $endInNew)
{
$bestMatchInOld = $startInOld;
$bestMatchInNew = $startInNew;
$bestMatchSize = 0;
$matchLengthAt = array();
for ($indexInOld = $startInOld; $indexInOld < $endInOld; $indexInOld++) {
$newMatchLengthAt = array();
$index = $this->oldWords[ $indexInOld ];
if ( $this->isTag( $index ) ) {
$index = $this->stripTagAttributes( $index );
}
if ( !isset( $this->wordIndices[ $index ] ) ) {
$matchLengthAt = $newMatchLengthAt;
continue;
}
foreach ($this->wordIndices[ $index ] as $indexInNew) {
if ($indexInNew < $startInNew) {
continue;
}
if ($indexInNew >= $endInNew) {
break;
}
$newMatchLength = ( isset( $matchLengthAt[ $indexInNew - 1 ] ) ? $matchLengthAt[ $indexInNew - 1 ] : 0 ) + 1;
$newMatchLengthAt[ $indexInNew ] = $newMatchLength;
if ($newMatchLength > $bestMatchSize ||
(
$this->isGroupDiffs() &&
$bestMatchSize > 0 &&
preg_match(
'/^\s+$/',
implode('', array_slice($this->oldWords, $bestMatchInOld, $bestMatchSize))
)
)
) {
$bestMatchInOld = $indexInOld - $newMatchLength + 1;
$bestMatchInNew = $indexInNew - $newMatchLength + 1;
$bestMatchSize = $newMatchLength;
}
}
$matchLengthAt = $newMatchLengthAt;
}
// Skip match if none found or match consists only of whitespace
if ($bestMatchSize != 0 &&
(
!$this->isGroupDiffs() ||
!preg_match('/^\s+$/', implode('', array_slice($this->oldWords, $bestMatchInOld, $bestMatchSize)))
)
) {
return new Match($bestMatchInOld, $bestMatchInNew, $bestMatchSize);
}
return null;
}
}

@ -0,0 +1,488 @@
<?php
namespace Caxy\HtmlDiff;
/**
* Class HtmlDiffConfig
* @package Caxy\HtmlDiff
*/
class HtmlDiffConfig
{
/**
* @var array
*/
protected $specialCaseTags = array('strong', 'b', 'i', 'big', 'small', 'u', 'sub', 'sup', 'strike', 's', 'p');
/**
* @var array
*/
protected $specialCaseChars = array('.', ',', '(', ')', '\'');
/**
* @var bool
*/
protected $groupDiffs = true;
/**
* @var bool
*/
protected $insertSpaceInReplace = false;
/**
* @var string
*/
protected $encoding = 'UTF-8';
/**
* @var array
*/
protected $isolatedDiffTags = array(
'ol' => '[[REPLACE_ORDERED_LIST]]',
'ul' => '[[REPLACE_UNORDERED_LIST]]',
'sub' => '[[REPLACE_SUB_SCRIPT]]',
'sup' => '[[REPLACE_SUPER_SCRIPT]]',
'dl' => '[[REPLACE_DEFINITION_LIST]]',
'table' => '[[REPLACE_TABLE]]',
'strong' => '[[REPLACE_STRONG]]',
'b' => '[[REPLACE_B]]',
'em' => '[[REPLACE_EM]]',
'i' => '[[REPLACE_I]]',
'a' => '[[REPLACE_A]]',
);
/**
* @var int
*/
protected $matchThreshold = 80;
/**
* @var array
*/
protected $specialCaseOpeningTags = array();
/**
* @var array
*/
protected $specialCaseClosingTags = array();
/**
* @var bool
*/
protected $useTableDiffing = true;
/**
* @var null|\Doctrine\Common\Cache\Cache
*/
protected $cacheProvider;
/**
* @var null|string
*/
protected $purifierCacheLocation = null;
/**
* @return HtmlDiffConfig
*/
public static function create()
{
return new self();
}
/**
* HtmlDiffConfig constructor.
*/
public function __construct()
{
$this->setSpecialCaseTags($this->specialCaseTags);
}
/**
* @return int
*/
public function getMatchThreshold()
{
return $this->matchThreshold;
}
/**
* @param int $matchThreshold
*
* @return AbstractDiff
*/
public function setMatchThreshold($matchThreshold)
{
$this->matchThreshold = $matchThreshold;
return $this;
}
/**
* @param array $chars
*/
public function setSpecialCaseChars(array $chars)
{
$this->specialCaseChars = $chars;
}
/**
* @return array|null
*/
public function getSpecialCaseChars()
{
return $this->specialCaseChars;
}
/**
* @param string $char
*
* @return $this
*/
public function addSpecialCaseChar($char)
{
if (!in_array($char, $this->specialCaseChars)) {
$this->specialCaseChars[] = $char;
}
return $this;
}
/**
* @param string $char
*
* @return $this
*/
public function removeSpecialCaseChar($char)
{
$key = array_search($char, $this->specialCaseChars);
if ($key !== false) {
unset($this->specialCaseChars[$key]);
}
return $this;
}
/**
* @param array $tags
*
* @return $this
*/
public function setSpecialCaseTags(array $tags = array())
{
$this->specialCaseTags = $tags;
$this->specialCaseOpeningTags = array();
$this->specialCaseClosingTags = array();
foreach ($this->specialCaseTags as $tag) {
$this->addSpecialCaseTag($tag);
}
return $this;
}
/**
* @param string $tag
*
* @return $this
*/
public function addSpecialCaseTag($tag)
{
if (!in_array($tag, $this->specialCaseTags)) {
$this->specialCaseTags[] = $tag;
}
$opening = $this->getOpeningTag($tag);
$closing = $this->getClosingTag($tag);
if (!in_array($opening, $this->specialCaseOpeningTags)) {
$this->specialCaseOpeningTags[] = $opening;
}
if (!in_array($closing, $this->specialCaseClosingTags)) {
$this->specialCaseClosingTags[] = $closing;
}
return $this;
}
/**
* @param string $tag
*
* @return $this
*/
public function removeSpecialCaseTag($tag)
{
if (($key = array_search($tag, $this->specialCaseTags)) !== false) {
unset($this->specialCaseTags[$key]);
$opening = $this->getOpeningTag($tag);
$closing = $this->getClosingTag($tag);
if (($key = array_search($opening, $this->specialCaseOpeningTags)) !== false) {
unset($this->specialCaseOpeningTags[$key]);
}
if (($key = array_search($closing, $this->specialCaseClosingTags)) !== false) {
unset($this->specialCaseClosingTags[$key]);
}
}
return $this;
}
/**
* @return array|null
*/
public function getSpecialCaseTags()
{
return $this->specialCaseTags;
}
/**
* @return boolean
*/
public function isGroupDiffs()
{
return $this->groupDiffs;
}
/**
* @param boolean $groupDiffs
*
* @return HtmlDiffConfig
*/
public function setGroupDiffs($groupDiffs)
{
$this->groupDiffs = $groupDiffs;
return $this;
}
/**
* @return string
*/
public function getEncoding()
{
return $this->encoding;
}
/**
* @param string $encoding
*
* @return HtmlDiffConfig
*/
public function setEncoding($encoding)
{
$this->encoding = $encoding;
return $this;
}
/**
* @return boolean
*/
public function isInsertSpaceInReplace()
{
return $this->insertSpaceInReplace;
}
/**
* @param boolean $insertSpaceInReplace
*
* @return HtmlDiffConfig
*/
public function setInsertSpaceInReplace($insertSpaceInReplace)
{
$this->insertSpaceInReplace = $insertSpaceInReplace;
return $this;
}
/**
* @return array
*/
public function getIsolatedDiffTags()
{
return $this->isolatedDiffTags;
}
/**
* @param array $isolatedDiffTags
*
* @return HtmlDiffConfig
*/
public function setIsolatedDiffTags($isolatedDiffTags)
{
$this->isolatedDiffTags = $isolatedDiffTags;
return $this;
}
/**
* @param string $tag
* @param null|string $placeholder
*
* @return $this
*/
public function addIsolatedDiffTag($tag, $placeholder = null)
{
if (null === $placeholder) {
$placeholder = sprintf('[[REPLACE_%s]]', strtoupper($tag));
}
if ($this->isIsolatedDiffTag($tag) && $this->isolatedDiffTags[$tag] !== $placeholder) {
throw new \InvalidArgumentException(
sprintf('Isolated diff tag "%s" already exists using a different placeholder', $tag)
);
}
$matchingKey = array_search($placeholder, $this->isolatedDiffTags, true);
if (false !== $matchingKey && $matchingKey !== $tag) {
throw new \InvalidArgumentException(
sprintf('Placeholder already being used for a different tag "%s"', $tag)
);
}
if (!array_key_exists($tag, $this->isolatedDiffTags)) {
$this->isolatedDiffTags[$tag] = $placeholder;
}
return $this;
}
/**
* @param string $tag
*
* @return $this
*/
public function removeIsolatedDiffTag($tag)
{
if ($this->isIsolatedDiffTag($tag)) {
unset($this->isolatedDiffTags[$tag]);
}
return $this;
}
/**
* @param string $tag
*
* @return bool
*/
public function isIsolatedDiffTag($tag)
{
return array_key_exists($tag, $this->isolatedDiffTags);
}
/**
* @param string $text
*
* @return bool
*/
public function isIsolatedDiffTagPlaceholder($text)
{
return in_array($text, $this->isolatedDiffTags, true);
}
/**
* @param string $tag
*
* @return null|string
*/
public function getIsolatedDiffTagPlaceholder($tag)
{
return $this->isIsolatedDiffTag($tag) ? $this->isolatedDiffTags[$tag] : null;
}
/**
* @return array
*/
public function getSpecialCaseOpeningTags()
{
return $this->specialCaseOpeningTags;
}
/**
* @return array
*/
public function getSpecialCaseClosingTags()
{
return $this->specialCaseClosingTags;
}
/**
* @return boolean
*/
public function isUseTableDiffing()
{
return $this->useTableDiffing;
}
/**
* @param boolean $useTableDiffing
*
* @return HtmlDiffConfig
*/
public function setUseTableDiffing($useTableDiffing)
{
$this->useTableDiffing = $useTableDiffing;
return $this;
}
/**
* @param null|\Doctrine\Common\Cache\Cache $cacheProvider
*
* @return $this
*/
public function setCacheProvider(\Doctrine\Common\Cache\Cache $cacheProvider = null)
{
$this->cacheProvider = $cacheProvider;
return $this;
}
/**
* @return null|\Doctrine\Common\Cache\Cache
*/
public function getCacheProvider()
{
return $this->cacheProvider;
}
/**
* @param null|string
*
* @return $this
*/
public function setPurifierCacheLocation($purifierCacheLocation = null)
{
$this->purifierCacheLocation = $purifierCacheLocation;
return $this;
}
/**
* @return null|string
*/
public function getPurifierCacheLocation()
{
return $this->purifierCacheLocation;
}
/**
* @param string $tag
*
* @return string
*/
protected function getOpeningTag($tag)
{
return "/<".$tag."[^>]*/i";
}
/**
* @param string $tag
*
* @return string
*/
protected function getClosingTag($tag)
{
return "</".$tag.">";
}
}

@ -0,0 +1,944 @@
<?php
namespace Caxy\HtmlDiff;
class ListDiff extends HtmlDiff
{
/**
* This is the minimum percentage a list item can match its counterpart in order to be considered a match.
* @var integer
*/
protected static $listMatchThreshold = 35;
/** @var array */
protected $listWords = array();
/** @var array */
protected $listTags = array();
/** @var array */
protected $listIsolatedDiffTags = array();
/** @var array */
protected $isolatedDiffTags = array (
'ol' => '[[REPLACE_ORDERED_LIST]]',
'ul' => '[[REPLACE_UNORDERED_LIST]]',
'dl' => '[[REPLACE_DEFINITION_LIST]]',
);
/**
* List (li) placeholder.
* @var string
*/
protected static $listPlaceHolder = "[[REPLACE_LIST_ITEM]]";
/**
* Holds the type of list this is ol, ul, dl.
* @var string
*/
protected $listType;
/**
* Used to hold what type of list the old list is.
* @var string
*/
protected $oldListType;
/**
* Used to hold what type of list the new list is.
* @var string
*/
protected $newListType;
/**
* Hold the old/new content of the content of the list.
* @var array
*/
protected $list;
/**
* Contains the old/new child lists content within this list.
* @var array
*/
protected $childLists;
/**
* Contains the old/new text strings that match
* @var array
*/
protected $textMatches;
/**
* Contains the indexed start positions of each list within word string.
* @var array
*/
protected $listsIndex;
/**
* Array that holds the index of all content outside of the array. Format is array(index => content).
* @var array
*/
protected $contentIndex = array();
/**
* Holds the order and data on each list/content block within this list.
* @var array
*/
protected $diffOrderIndex = array();
/**
* This is the opening ol,ul,dl ist tag.
* @var string
*/
protected $oldParentTag;
/**
* This is the opening ol,ul,dl ist tag.
* @var string
*/
protected $newParentTag;
/**
* We're using the same functions as the parent in build() to get us to the point of
* manipulating the data within this class.
*
* @return string
*/
public function build()
{
// Use the parent functions to get the data we need organized.
$this->splitInputsToWords();
$this->replaceIsolatedDiffTags();
$this->indexNewWords();
// Now use the custom functions in this class to use the data and generate our diff.
$this->diffListContent();
return $this->content;
}
/**
* Calls to the actual custom functions of this class, to diff list content.
*/
protected function diffListContent()
{
/* Format the list we're focusing on.
* There will always be one list, though passed as an array with one item.
* Format this to only have the list contents, outside of the array.
*/
$this->formatThisListContent();
/* Build an index of content outside of list tags.
*/
$this->indexContent();
/* In cases where we're dealing with nested lists,
* make sure we use placeholders to replace the nested lists
*/
$this->replaceListIsolatedDiffTags();
/* Build a list of matches we can reference when we diff the contents of the lists.
* This is needed so that we each NEW list node is matched against the best possible OLD list node/
* It helps us determine whether the list was added, removed, or changed.
*/
$this->matchAndCompareLists();
/* Go through the list of matches, content, and diff each.
* Any nested lists would be sent to parent's diffList function, which creates a new listDiff class.
*/
$this->diff();
}
/**
* This function is used to populate both contentIndex and diffOrderIndex arrays for use in the diff function.
*/
protected function indexContent()
{
$this->contentIndex = array();
$this->diffOrderIndex = array('new' => array(), 'old' => array());
foreach ($this->list as $type => $list) {
$this->contentIndex[$type] = array();
$depth = 0;
$parentList = 0;
$position = 0;
$newBlock = true;
$listCount = 0;
$contentCount = 0;
foreach ($list as $key => $word) {
if (!$parentList && $this->isOpeningListTag($word)) {
$depth++;
$this->diffOrderIndex[$type][] = array('type' => 'list', 'position' => $listCount, 'index' => $key);
$listCount++;
continue;
}
if (!$parentList && $this->isClosingListTag($word)) {
$depth--;
if ($depth == 0) {
$newBlock = true;
}
continue;
}
if ($this->isOpeningIsolatedDiffTag($word)) {
$parentList++;
}
if ($this->isClosingIsolatedDiffTag($word)) {
$parentList--;
}
if ($depth == 0) {
if ($newBlock && !array_key_exists($contentCount, $this->contentIndex[$type])) {
$this->diffOrderIndex[$type][] = array('type' => 'content', 'position' => $contentCount, 'index' => $key);
$position = $contentCount;
$this->contentIndex[$type][$position] = '';
$contentCount++;
}
$this->contentIndex[$type][$position] .= $word;
}
$newBlock = false;
}
}
}
/*
* This function is used to remove the wrapped ul, ol, or dl characters from this list
* and sets the listType as ul, ol, or dl, so that we can use it later.
* $list is being set here as well, as an array with the old and new version of this list content.
*/
protected function formatThisListContent()
{
$formatArray = array(
array('type' => 'old', 'array' => $this->oldIsolatedDiffTags),
array('type' => 'new', 'array' => $this->newIsolatedDiffTags)
);
foreach ($formatArray as $item) {
$values = array_values($item['array']);
$this->list[$item['type']] = count($values)
? $this->formatList($values[0], $item['type'])
: array();
}
$this->listType = $this->newListType ?: $this->oldListType;
}
/**
*
* @param array $arrayData
* @param string $index
* @return array
*/
protected function formatList(array $arrayData, $index = 'old')
{
$openingTag = $this->getAndStripTag($arrayData[0]);
$closingTag = $this->getAndStripTag($arrayData[count($arrayData) - 1]);
if (array_key_exists($openingTag, $this->isolatedDiffTags) &&
array_key_exists($closingTag, $this->isolatedDiffTags)
) {
if ($index == 'new' && $this->isOpeningTag($arrayData[0])) {
$this->newParentTag = $arrayData[0];
$this->newListType = $this->getAndStripTag($arrayData[0]);
}
if ($index == 'old' && $this->isOpeningTag($arrayData[0])) {
$this->oldParentTag = $arrayData[0];
$this->oldListType = $this->getAndStripTag($arrayData[0]);
}
array_shift($arrayData);
array_pop($arrayData);
}
return $arrayData;
}
/**
* @param string $tag
* @return string
*/
protected function getAndStripTag($tag)
{
$content = explode(' ', preg_replace("/[^A-Za-z0-9 ]/", '', $tag));
return $content[0];
}
protected function matchAndCompareLists()
{
/**
* Build the an array (childLists) to hold the contents of the list nodes within this list.
* This only holds the content of each list node.
*/
$this->buildChildLists();
/**
* Index the list, starting positions, so that we can refer back to it later.
* This is used to see where one list node starts and another ends.
*/
$this->indexLists();
/**
* Compare the lists and build $textMatches array with the matches.
* Each match is an array of "new" and "old" keys, with the id of the list it matches to.
* Whenever there is no match (in cases where a new list item was added or removed), null is used instead of the id.
*/
$this->compareChildLists();
}
/**
* Creates matches for lists.
*/
protected function compareChildLists()
{
$this->createNewOldMatches($this->childLists, $this->textMatches, 'content');
}
/**
* Abstracted function used to match items in an array.
* This is used primarily for populating lists matches.
*
* @param array $listArray
* @param array $resultArray
* @param string|null $column
*/
protected function createNewOldMatches(&$listArray, &$resultArray, $column = null)
{
// Always compare the new against the old.
// Compare each new string against each old string.
$bestMatchPercentages = array();
foreach ($listArray['new'] as $thisKey => $thisList) {
$bestMatchPercentages[$thisKey] = array();
foreach ($listArray['old'] as $thatKey => $thatList) {
// Save the percent amount each new list content compares against the old list content.
similar_text(
$column ? $thisList[$column] : $thisList,
$column ? $thatList[$column] : $thatList,
$percentage
);
$bestMatchPercentages[$thisKey][] = $percentage;
}
}
// Sort each array by value, highest percent to lowest percent.
foreach ($bestMatchPercentages as &$thisMatch) {
arsort($thisMatch);
}
// Build matches.
$matches = array();
$taken = array();
$takenItems = array();
$absoluteMatch = 100;
foreach ($bestMatchPercentages as $item => $percentages) {
$highestMatch = -1;
$highestMatchKey = -1;
$takeItemKey = -1;
foreach ($percentages as $key => $percent) {
// Check that the key for the percentage is not already taken and the new percentage is higher.
if (!in_array($key, $taken) && $percent > $highestMatch) {
// If an absolute match, choose this one.
if ($percent == $absoluteMatch) {
$highestMatch = $percent;
$highestMatchKey = $key;
$takenItemKey = $item;
break;
} else {
// Get all the other matces for the same $key
$columns = $this->getArrayColumn($bestMatchPercentages, $key);
$thisBestMatches = array_filter(
$columns,
function ($v) use ($percent) {
return $v > $percent;
}
);
arsort($thisBestMatches);
/**
* If the list item does not meet the threshold, it will not be considered a match.
*/
if ($percent >= self::$listMatchThreshold) {
// If no greater amounts, use this one.
if (!count($thisBestMatches)) {
$highestMatch = $percent;
$highestMatchKey = $key;
$takenItemKey = $item;
break;
}
// Loop through, comparing only the items that have not already been added.
foreach ($thisBestMatches as $k => $v) {
if (in_array($k, $takenItems)) {
$highestMatch = $percent;
$highestMatchKey = $key;
$takenItemKey = $item;
break(2);
}
}
}
}
}
}
$matches[] = array('new' => $item, 'old' => $highestMatchKey > -1 ? $highestMatchKey : null);
if ($highestMatchKey > -1) {
$taken[] = $highestMatchKey;
$takenItems[] = $takenItemKey;
}
}
/* Checking for removed items. Basically, if a list item from the old lists is removed
* it will not be accounted for, and will disappear in the results altogether.
* Loop through all the old lists, any that has not been added, will be added as:
* array( new => null, old => oldItemId )
*/
$matchColumns = $this->getArrayColumn($matches, 'old');
foreach ($listArray['old'] as $thisKey => $thisList) {
if (!in_array($thisKey, $matchColumns)) {
$matches[] = array('new' => null, 'old' => $thisKey);
}
}
// Save the matches.
$resultArray = $matches;
}
/**
* This fuction is exactly like array_column. This is added for PHP versions that do not support array_column.
* @param array $targetArray
* @param mixed $key
* @return array
*/
protected function getArrayColumn(array $targetArray, $key)
{
$data = array();
foreach ($targetArray as $item) {
if (array_key_exists($key, $item)) {
$data[] = $item[$key];
}
}
return $data;
}
/**
* Build multidimensional array holding the contents of each list node, old and new.
*/
protected function buildChildLists()
{
$this->childLists['old'] = $this->getListsContent($this->list['old']);
$this->childLists['new'] = $this->getListsContent($this->list['new']);
}
/**
* Diff the actual contents of the lists against their matched counterpart.
* Build the content of the class.
*/
protected function diff()
{
// Add the opening parent node from listType. So if ol, <ol>, etc.
$this->content = $this->addListTypeWrapper();
$oldIndexCount = 0;
$diffOrderNewKeys = array_keys($this->diffOrderIndex['new']);
foreach ($this->diffOrderIndex['new'] as $key => $index) {
if ($index['type'] == "list") {
// Check to see if an old list was deleted.
$oldMatch = $this->getArrayByColumnValue($this->textMatches, 'old', $index['position']);
if ($oldMatch && $oldMatch['new'] === null) {
$newList = '';
$oldList = $this->getListByMatch($oldMatch, 'old');
$this->content .= $this->addListElementToContent($newList, $oldList, $oldMatch, $index, 'old');
}
$match = $this->getArrayByColumnValue($this->textMatches, 'new', $index['position']);
$newList = $this->childLists['new'][$match['new']];
$oldList = $this->getListByMatch($match, 'old');
$this->content .= $this->addListElementToContent($newList, $oldList, $match, $index, 'new');
}
if ($index['type'] == 'content') {
$this->content .= $this->addContentElementsToContent($oldIndexCount, $index['position']);
}
$oldIndexCount++;
if ($key == $diffOrderNewKeys[count($diffOrderNewKeys) - 1]) {
foreach ($this->diffOrderIndex['old'] as $oldKey => $oldIndex) {
if ($oldKey > $key) {
if ($oldIndex['type'] == 'list') {
$oldMatch = $this->getArrayByColumnValue($this->textMatches, 'old', $oldIndex['position']);
if ($oldMatch && $oldMatch['new'] === null) {
$newList = '';
$oldList = $this->getListByMatch($oldMatch, 'old');
$this->content .= $this->addListElementToContent($newList, $oldList, $oldMatch, $oldIndex, 'old');
}
} else {
$this->content .= $this->addContentElementsToContent($oldKey);
}
}
}
}
}
// Add the closing parent node from listType. So if ol, </ol>, etc.
$this->content .= $this->addListTypeWrapper(false);
}
/**
*
* @param string $newList
* @param string $oldList
* @param array $match
* @param array $index
* @return string
*/
protected function addListElementToContent($newList, $oldList, array $match, array $index, $type)
{
$content = $this->list[$type][$index['index']];
$content .= $this->processPlaceholders(
$this->diffElements(
$this->convertListContentArrayToString($oldList),
$this->convertListContentArrayToString($newList),
false
),
$match
);
$content .= "</li>";
return $content;
}
/**
*
* @param integer $oldIndexCount
* @param null|integer $newPosition
* @return string
*/
protected function addContentElementsToContent($oldIndexCount, $newPosition = null)
{
$newContent = $newPosition && array_key_exists($newPosition, $this->contentIndex['new'])
? $this->contentIndex['new'][$newPosition]
: '';
$oldDiffOrderIndexMatch = array_key_exists($oldIndexCount, $this->diffOrderIndex['old'])
? $this->diffOrderIndex['old'][$oldIndexCount]
: '';
$oldContent = $oldDiffOrderIndexMatch && array_key_exists($oldDiffOrderIndexMatch['position'], $this->contentIndex['old'])
? $this->contentIndex['old'][$oldDiffOrderIndexMatch['position']]
: '';
$diffObject = new HtmlDiff($oldContent, $newContent);
$content = $diffObject->build();
return $content;
}
/**
*
* @param array $match
* @param string $type
* @return array|string
*/
protected function getListByMatch(array $match, $type = 'new')
{
return array_key_exists($match[$type], $this->childLists[$type])
? $this->childLists[$type][$match[$type]]
: '';
}
/**
* This function replaces array_column function in PHP for older versions of php.
*
* @param array $parentArray
* @param string $column
* @param mixed $value
* @param boolean $allMatches
* @return array|boolean
*/
protected function getArrayByColumnValue($parentArray, $column, $value, $allMatches = false)
{
$returnArray = array();
foreach ($parentArray as $array) {
if (array_key_exists($column, $array) && $array[$column] == $value) {
if ($allMatches) {
$returnArray[] = $array;
} else {
return $array;
}
}
}
return $allMatches ? $returnArray : false;
}
/**
* Converts the list (li) content arrays to string.
*
* @param array $listContentArray
* @return string
*/
protected function convertListContentArrayToString($listContentArray)
{
if (!is_array($listContentArray)) {
return $listContentArray;
}
$content = array();
$words = explode(" ", $listContentArray['content']);
$nestedListCount = 0;
foreach ($words as $word) {
$match = $word == self::$listPlaceHolder;
$content[] = $match
? "<li>" . $this->convertListContentArrayToString($listContentArray['kids'][$nestedListCount]) . "</li>"
: $word;
if ($match) {
$nestedListCount++;
}
}
return implode(" ", $content);
}
/**
* Return the contents of each list node.
* Process any placeholders for nested lists.
*
* @param string $text
* @param array $matches
* @return string
*/
protected function processPlaceholders($text, array $matches)
{
// Prepare return
$returnText = array();
// Save the contents of all list nodes, new and old.
$contentVault = array(
'old' => $this->getListContent('old', $matches),
'new' => $this->getListContent('new', $matches)
);
$count = 0;
// Loop through the text checking for placeholders. If a nested list is found, create a new ListDiff object for it.
foreach (explode(' ', $text) as $word) {
$preContent = $this->checkWordForDiffTag($this->stripNewLine($word));
if (in_array(
is_array($preContent) ? $preContent[1] : $preContent,
$this->isolatedDiffTags
)
) {
$oldText = array_key_exists($count, $contentVault['old']) ? implode('', $contentVault['old'][$count]) : '';
$newText = array_key_exists($count, $contentVault['new']) ? implode('', $contentVault['new'][$count]) : '';
$content = $this->diffList($oldText, $newText);
$count++;
} else {
$content = $preContent;
}
$returnText[] = is_array($preContent) ? $preContent[0] . $content . $preContent[2] : $content;
}
// Return the result.
return implode(' ', $returnText);
}
/**
* Checks to see if a diff tag is in string.
*
* @param string $word
* @return string
*/
protected function checkWordForDiffTag($word)
{
foreach ($this->isolatedDiffTags as $diffTag) {
if (strpos($word, $diffTag) > -1) {
$position = strpos($word, $diffTag);
$length = strlen($diffTag);
$result = array(
substr($word, 0, $position),
$diffTag,
substr($word, ($position + $length))
);
return $result;
}
}
return $word;
}
/**
* Used to remove new lines.
*
* @param string $text
* @return string
*/
protected function stripNewLine($text)
{
return trim(preg_replace('/\s\s+/', ' ', $text));
}
/**
* Grab the list content using the listsIndex array.
*
* @param string $indexKey
* @param array $matches
* @return array
*/
protected function getListContent($indexKey = 'new', array $matches)
{
$bucket = array();
if (isset($matches[$indexKey]) && $matches[$indexKey] !== null) {
$start = $this->listsIndex[$indexKey][$matches[$indexKey]];
$stop = $this->findEndForIndex($this->list[$indexKey], $start);
for ($x = $start; $x <= $stop; $x++) {
if (in_array($this->list[$indexKey][$x], $this->isolatedDiffTags)) {
$bucket[] = $this->listIsolatedDiffTags[$indexKey][$x];
}
}
}
return $bucket;
}
/**
* Finds the end of list within its index.
*
* @param array $index
* @param integer $start
* @return integer
*/
protected function findEndForIndex(array $index, $start)
{
$array = array_splice($index, $start);
$count = 0;
foreach ($array as $key => $item) {
if ($this->isOpeningListTag($item)) {
$count++;
}
if ($this->isClosingListTag($item)) {
$count--;
if ($count === 0) {
return $start + $key;
}
}
}
return $start + count($array);
}
/**
* indexLists
*
* Index the list, starting positions, so that we can refer back to it later.
* This is used to see where one list node starts and another ends.
*/
protected function indexLists()
{
$this->listsIndex = array();
$count = 0;
foreach ($this->list as $type => $list) {
$this->listsIndex[$type] = array();
foreach ($list as $key => $listItem) {
if ($this->isOpeningListTag($listItem)) {
$count++;
if ($count === 1) {
$this->listsIndex[$type][] = $key;
}
}
if ($this->isClosingListTag($listItem)) {
$count--;
}
}
}
}
/**
* Adds the opening or closing list html element, based on listType.
*
* @param boolean $opening
* @return string
*/
protected function addListTypeWrapper($opening = true)
{
if ($opening) {
return $this->newParentTag ?: $this->oldParentTag;
} else {
return "<" . (!$opening ? "/" : '') . $this->listType . ">";
}
}
/**
* Replace nested list with placeholders.
*/
public function replaceListIsolatedDiffTags()
{
$this->listIsolatedDiffTags['old'] = $this->createIsolatedDiffTagPlaceholders($this->list['old']);
$this->listIsolatedDiffTags['new'] = $this->createIsolatedDiffTagPlaceholders($this->list['new']);
}
/**
* Grab the contents of a list node.
*
* @param array $contentArray
* @param boolean $stripTags
* @return array
*/
protected function getListsContent(array $contentArray, $stripTags = true)
{
$lematches = array();
$arrayDepth = 0;
$nestedCount = array();
foreach ($contentArray as $index => $word) {
if ($this->isOpeningListTag($word)) {
$arrayDepth++;
if (!array_key_exists($arrayDepth, $nestedCount)) {
$nestedCount[$arrayDepth] = 1;
} else {
$nestedCount[$arrayDepth]++;
}
continue;
}
if ($this->isClosingListTag($word)) {
$arrayDepth--;
continue;
}
if ($arrayDepth > 0) {
$this->addStringToArrayByDepth($word, $lematches, $arrayDepth, 1, $nestedCount);
}
}
return $lematches;
}
/**
* This function helps build the list content array of a list.
* If a list has another list within it, the inner list is replaced with the list placeholder and the inner list
* content becomes a child of the parent list.
* This goes recursively down.
*
* @param string $word
* @param array $array
* @param integer $targetDepth
* @param integer $thisDepth
* @param array $nestedCount
*/
protected function addStringToArrayByDepth($word, array &$array, $targetDepth, $thisDepth, array $nestedCount)
{
// determine what depth we're at
if ($targetDepth == $thisDepth) {
// decide on what to do at this level
if (array_key_exists('content', $array)) {
$array['content'] .= $word;
} else {
// if we're on depth 1, add content
if ($nestedCount[$targetDepth] > count($array)) {
$array[] = array('content' => '', 'kids' => array());
}
$array[count($array) - 1]['content'] .= $word;
}
} else {
// create first kid if not exist
$newArray = array('content' => '', 'kids' => array());
if (array_key_exists('kids', $array)) {
if ($nestedCount[$targetDepth] > count($array['kids'])) {
$array['kids'][] = $newArray;
$array['content'] .= self::$listPlaceHolder;
}
// continue to the next depth
$thisDepth++;
// get last kid and send to next depth
$this->addStringToArrayByDepth(
$word,
$array['kids'][count($array['kids']) - 1],
$targetDepth,
$thisDepth,
$nestedCount
);
} else {
if ($nestedCount[$targetDepth] > count($array[count($array) - 1]['kids'])) {
$array[count($array) - 1]['kids'][] = $newArray;
$array[count($array) - 1]['content'] .= self::$listPlaceHolder;
}
// continue to the next depth
$thisDepth++;
// get last kid and send to next depth
$this->addStringToArrayByDepth(
$word,
$array[count($array) - 1]['kids'][count($array[count($array) - 1]['kids']) - 1],
$targetDepth,
$thisDepth,
$nestedCount
);
}
}
}
/**
* Checks if text is opening list tag.
*
* @param string $item
* @return boolean
*/
protected function isOpeningListTag($item)
{
if (preg_match("#<li[^>]*>\\s*#iU", $item)) {
return true;
}
return false;
}
/**
* Check if text is closing list tag.
*
* @param string $item
* @return boolean
*/
protected function isClosingListTag($item)
{
if (preg_match("#</li[^>]*>\\s*#iU", $item)) {
return true;
}
return false;
}
}

@ -0,0 +1,102 @@
<?php
namespace Caxy\HtmlDiff\ListDiff;
class DiffList
{
protected $listType;
protected $listItems = array();
protected $attributes = array();
protected $startTag;
protected $endTag;
public function __construct($listType, $startTag, $endTag, $listItems = array(), $attributes = array())
{
$this->listType = $listType;
$this->startTag = $startTag;
$this->endTag = $endTag;
$this->listItems = $listItems;
$this->attributes = $attributes;
}
/**
* @return mixed
*/
public function getListType()
{
return $this->listType;
}
/**
* @param mixed $listType
*
* @return DiffList
*/
public function setListType($listType)
{
$this->listType = $listType;
return $this;
}
/**
* @return mixed
*/
public function getStartTag()
{
return $this->startTag;
}
public function getStartTagWithDiffClass($class = 'diff-list')
{
return str_replace('>', ' class="'.$class.'">', $this->startTag);
}
/**
* @param mixed $startTag
*/
public function setStartTag($startTag)
{
$this->startTag = $startTag;
}
/**
* @return mixed
*/
public function getEndTag()
{
return $this->endTag;
}
/**
* @param mixed $endTag
*/
public function setEndTag($endTag)
{
$this->endTag = $endTag;
}
/**
* @return mixed
*/
public function getListItems()
{
return $this->listItems;
}
/**
* @param mixed $listItems
*
* @return DiffList
*/
public function setListItems($listItems)
{
$this->listItems = $listItems;
return $this;
}
}

@ -0,0 +1,124 @@
<?php
namespace Caxy\HtmlDiff\ListDiff;
class DiffListItem
{
protected $attributes = array();
protected $text;
protected $startTag;
protected $endTag;
public function __construct($text, $attributes = array(), $startTag, $endTag)
{
$this->text = $text;
$this->attributes = $attributes;
$this->startTag = $startTag;
$this->endTag = $endTag;
}
/**
* @return array
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* @param array $attributes
*
* @return DiffListItem
*/
public function setAttributes($attributes)
{
$this->attributes = $attributes;
return $this;
}
/**
* @return mixed
*/
public function getText()
{
return $this->text;
}
/**
* @param mixed $text
*
* @return DiffListItem
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* @return mixed
*/
public function getStartTag()
{
return $this->startTag;
}
public function getStartTagWithDiffClass($class = 'normal')
{
return str_replace('>', ' class="'.$class.'">', $this->startTag);
}
/**
* @param mixed $startTag
*
* @return DiffListItem
*/
public function setStartTag($startTag)
{
$this->startTag = $startTag;
return $this;
}
/**
* @return mixed
*/
public function getEndTag()
{
return $this->endTag;
}
/**
* @param mixed $endTag
*
* @return DiffListItem
*/
public function setEndTag($endTag)
{
$this->endTag = $endTag;
return $this;
}
public function getHtml($class = 'normal', $wrapTag = null)
{
$startWrap = $wrapTag ? sprintf('<%s>', $wrapTag) : '';
$endWrap = $wrapTag ? sprintf('</%s>', $wrapTag) : '';
return sprintf('%s%s%s%s%s', $this->getStartTagWithDiffClass($class), $startWrap, $this->getInnerHtml(), $endWrap, $this->endTag);
}
public function getInnerHtml()
{
return implode('', $this->text);
}
public function __toString()
{
return $this->getHtml();
}
}

@ -0,0 +1,280 @@
<?php
namespace Caxy\HtmlDiff;
use Caxy\HtmlDiff\ListDiff\DiffList;
use Caxy\HtmlDiff\ListDiff\DiffListItem;
class ListDiffNew extends AbstractDiff
{
protected static $listTypes = array('ul', 'ol', 'dl');
/**
* @param string $oldText
* @param string $newText
* @param HtmlDiffConfig|null $config
*
* @return self
*/
public static function create($oldText, $newText, HtmlDiffConfig $config = null)
{
$diff = new self($oldText, $newText);
if (null !== $config) {
$diff->setConfig($config);
}
return $diff;
}
public function build()
{
if ($this->hasDiffCache() && $this->getDiffCache()->contains($this->oldText, $this->newText)) {
$this->content = $this->getDiffCache()->fetch($this->oldText, $this->newText);
return $this->content;
}
$this->splitInputsToWords();
$this->content = $this->diffLists(
$this->buildDiffList($this->oldWords),
$this->buildDiffList($this->newWords)
);
if ($this->hasDiffCache()) {
$this->getDiffCache()->save($this->oldText, $this->newText, $this->content);
}
return $this->content;
}
protected function diffLists(DiffList $oldList, DiffList $newList)
{
$oldMatchData = array();
$newMatchData = array();
$oldListIndices = array();
$newListIndices = array();
$oldListItems = array();
$newListItems = array();
foreach ($oldList->getListItems() as $oldIndex => $oldListItem) {
if ($oldListItem instanceof DiffListItem) {
$oldListItems[$oldIndex] = $oldListItem;
$oldListIndices[] = $oldIndex;
$oldMatchData[$oldIndex] = array();
// Get match percentages
foreach ($newList->getListItems() as $newIndex => $newListItem) {
if ($newListItem instanceof DiffListItem) {
if (!in_array($newListItem, $newListItems)) {
$newListItems[$newIndex] = $newListItem;
}
if (!in_array($newIndex, $newListIndices)) {
$newListIndices[] = $newIndex;
}
if (!array_key_exists($newIndex, $newMatchData)) {
$newMatchData[$newIndex] = array();
}
$oldText = implode('', $oldListItem->getText());
$newText = implode('', $newListItem->getText());
// similar_text
$percentage = null;
similar_text($oldText, $newText, $percentage);
$oldMatchData[$oldIndex][$newIndex] = $percentage;
$newMatchData[$newIndex][$oldIndex] = $percentage;
}
}
}
}
$currentIndexInOld = 0;
$currentIndexInNew = 0;
$oldCount = count($oldListIndices);
$newCount = count($newListIndices);
$difference = max($oldCount, $newCount) - min($oldCount, $newCount);
$diffOutput = '';
foreach ($newList->getListItems() as $newIndex => $newListItem) {
if ($newListItem instanceof DiffListItem) {
$operation = null;
$oldListIndex = array_key_exists($currentIndexInOld, $oldListIndices) ? $oldListIndices[$currentIndexInOld] : null;
$class = 'normal';
if (null !== $oldListIndex && array_key_exists($oldListIndex, $oldMatchData)) {
// Check percentage matches of upcoming list items in old.
$matchPercentage = $oldMatchData[$oldListIndex][$newIndex];
// does the old list item match better?
$otherMatchBetter = false;
foreach ($oldMatchData[$oldListIndex] as $index => $percentage) {
if ($index > $newIndex && $percentage > $matchPercentage) {
$otherMatchBetter = $index;
}
}
if (false !== $otherMatchBetter && $newCount > $oldCount && $difference > 0) {
$diffOutput .= sprintf('%s', $newListItem->getHtml('normal new', 'ins'));
$currentIndexInNew++;
$difference--;
continue;
}
$nextOldListIndex = array_key_exists($currentIndexInOld + 1, $oldListIndices) ? $oldListIndices[$currentIndexInOld + 1] : null;
$replacement = false;
if ($nextOldListIndex !== null && $oldMatchData[$nextOldListIndex][$newIndex] > $matchPercentage && $oldMatchData[$nextOldListIndex][$newIndex] > $this->config->getMatchThreshold()) {
// Following list item in old is better match, use that.
$diffOutput .= sprintf('%s', $oldListItems[$oldListIndex]->getHtml('removed', 'del'));
$currentIndexInOld++;
$oldListIndex = $nextOldListIndex;
$matchPercentage = $oldMatchData[$oldListIndex];
$replacement = true;
}
if ($matchPercentage > $this->config->getMatchThreshold() || $currentIndexInNew === $currentIndexInOld) {
// Diff the two lists.
$htmlDiff = HtmlDiff::create(
$oldListItems[$oldListIndex]->getInnerHtml(),
$newListItem->getInnerHtml(),
$this->config
);
$diffContent = $htmlDiff->build();
$diffOutput .= sprintf('%s%s%s', $newListItem->getStartTagWithDiffClass($replacement ? 'replacement' : 'normal'), $diffContent, $newListItem->getEndTag());
} else {
$diffOutput .= sprintf('%s', $oldListItems[$oldListIndex]->getHtml('removed', 'del'));
$diffOutput .= sprintf('%s', $newListItem->getHtml('replacement', 'ins'));
}
$currentIndexInOld++;
} else {
$diffOutput .= sprintf('%s', $newListItem->getHtml('normal new', 'ins'));
}
$currentIndexInNew++;
}
}
// Output any additional list items
while (array_key_exists($currentIndexInOld, $oldListIndices)) {
$oldListIndex = $oldListIndices[$currentIndexInOld];
$diffOutput .= sprintf('%s', $oldListItems[$oldListIndex]->getHtml('removed', 'del'));
$currentIndexInOld++;
}
return sprintf('%s%s%s', $newList->getStartTagWithDiffClass(), $diffOutput, $newList->getEndTag());
}
protected function buildDiffList($words)
{
$listType = null;
$listStartTag = null;
$listEndTag = null;
$attributes = array();
$openLists = 0;
$openListItems = 0;
$list = array();
$currentListItem = null;
$listItemType = null;
$listItemStart = null;
$listItemEnd = null;
foreach ($words as $i => $word) {
if ($this->isOpeningListTag($word, $listType)) {
if ($openLists > 0) {
if ($openListItems > 0) {
$currentListItem[] = $word;
} else {
$list[] = $word;
}
} else {
$listType = substr($word, 1, 2);
$listStartTag = $word;
}
$openLists++;
} elseif ($this->isClosingListTag($word, $listType)) {
if ($openLists > 1) {
if ($openListItems > 0) {
$currentListItem[] = $word;
} else {
$list[] = $word;
}
} else {
$listEndTag = $word;
}
$openLists--;
} elseif ($this->isOpeningListItemTag($word, $listItemType)) {
if ($openListItems === 0) {
// New top-level list item
$currentListItem = array();
$listItemType = substr($word, 1, 2);
$listItemStart = $word;
} else {
$currentListItem[] = $word;
}
$openListItems++;
} elseif ($this->isClosingListItemTag($word, $listItemType)) {
if ($openListItems === 1) {
$listItemEnd = $word;
$listItem = new DiffListItem($currentListItem, array(), $listItemStart, $listItemEnd);
$list[] = $listItem;
$currentListItem = null;
} else {
$currentListItem[] = $word;
}
$openListItems--;
} else {
if ($openListItems > 0) {
$currentListItem[] = $word;
} else {
$list[] = $word;
}
}
}
$diffList = new DiffList($listType, $listStartTag, $listEndTag, $list, $attributes);
return $diffList;
}
protected function isOpeningListTag($word, $type = null)
{
$filter = $type !== null ? array('<' . $type) : array('<ul', '<ol', '<dl');
return in_array(substr($word, 0, 3), $filter);
}
protected function isClosingListTag($word, $type = null)
{
$filter = $type !== null ? array('</' . $type) : array('</ul', '</ol', '</dl');
return in_array(substr($word, 0, 4), $filter);
}
protected function isOpeningListItemTag($word, $type = null)
{
$filter = $type !== null ? array('<' . $type) : array('<li', '<dd', '<dt');
return in_array(substr($word, 0, 3), $filter);
}
protected function isClosingListItemTag($word, $type = null)
{
$filter = $type !== null ? array('</' . $type) : array('</li', '</dd', '</dt');
return in_array(substr($word, 0, 4), $filter);
}
}

@ -0,0 +1,27 @@
<?php
namespace Caxy\HtmlDiff;
class Match
{
public $startInOld;
public $startInNew;
public $size;
public function __construct($startInOld, $startInNew, $size)
{
$this->startInOld = $startInOld;
$this->startInNew = $startInNew;
$this->size = $size;
}
public function endInOld()
{
return $this->startInOld + $this->size;
}
public function endInNew()
{
return $this->startInNew + $this->size;
}
}

@ -0,0 +1,21 @@
<?php
namespace Caxy\HtmlDiff;
class Operation
{
public $action;
public $startInOld;
public $endInOld;
public $startInNew;
public $endInNew;
public function __construct($action, $startInOld, $endInOld, $startInNew, $endInNew)
{
$this->action = $action;
$this->startInOld = $startInOld;
$this->endInOld = $endInOld;
$this->startInNew = $startInNew;
$this->endInNew = $endInNew;
}
}

@ -0,0 +1,94 @@
<?php
namespace Caxy\HtmlDiff\Table;
/**
* Class AbstractTableElement
* @package Caxy\HtmlDiff\Table
*/
abstract class AbstractTableElement
{
/**
* @var \DOMElement
*/
protected $domNode;
/**
* AbstractTableElement constructor.
*
* @param \DOMElement|null $domNode
*/
public function __construct(\DOMElement $domNode = null)
{
$this->domNode = $domNode;
}
/**
* @return \DOMElement
*/
public function getDomNode()
{
return $this->domNode;
}
/**
* @param \DOMElement $domNode
*
* @return $this
*/
public function setDomNode(\DOMElement $domNode)
{
$this->domNode = $domNode;
return $this;
}
/**
* @return string
*/
public function getInnerHtml()
{
$innerHtml = '';
if ($this->domNode) {
foreach ($this->domNode->childNodes as $child) {
$innerHtml .= static::htmlFromNode($child);
}
}
return $innerHtml;
}
/**
* @param string $name
*
* @return string
*/
public function getAttribute($name)
{
return $this->domNode->getAttribute($name);
}
/**
* @param \DOMDocument $domDocument
*
* @return \DOMElement
*/
public function cloneNode(\DOMDocument $domDocument)
{
return $domDocument->importNode($this->getDomNode()->cloneNode(false), false);
}
/**
* @param \DOMElement $node
*
* @return string
*/
public static function htmlFromNode($node)
{
$domDocument = new \DOMDocument();
$newNode = $domDocument->importNode($node, true);
$domDocument->appendChild($newNode);
return trim($domDocument->saveHTML());
}
}

@ -0,0 +1,268 @@
<?php
namespace Caxy\HtmlDiff\Table;
/**
* Class DiffRowPosition
* @package Caxy\HtmlDiff\Table
*/
class DiffRowPosition
{
/**
* @var int
*/
protected $indexInOld;
/**
* @var int
*/
protected $indexInNew;
/**
* @var int
*/
protected $columnInOld;
/**
* @var int
*/
protected $columnInNew;
/**
* DiffRowPosition constructor.
*
* @param int $indexInOld
* @param int $indexInNew
* @param int $columnInOld
* @param int $columnInNew
*/
public function __construct($indexInOld = 0, $indexInNew = 0, $columnInOld = 0, $columnInNew = 0)
{
$this->indexInOld = $indexInOld;
$this->indexInNew = $indexInNew;
$this->columnInOld = $columnInOld;
$this->columnInNew = $columnInNew;
}
/**
* @return int
*/
public function getIndexInOld()
{
return $this->indexInOld;
}
/**
* @param int $indexInOld
*
* @return DiffRowPosition
*/
public function setIndexInOld($indexInOld)
{
$this->indexInOld = $indexInOld;
return $this;
}
/**
* @return int
*/
public function getIndexInNew()
{
return $this->indexInNew;
}
/**
* @param int $indexInNew
*
* @return DiffRowPosition
*/
public function setIndexInNew($indexInNew)
{
$this->indexInNew = $indexInNew;
return $this;
}
/**
* @return int
*/
public function getColumnInOld()
{
return $this->columnInOld;
}
/**
* @param int $columnInOld
*
* @return DiffRowPosition
*/
public function setColumnInOld($columnInOld)
{
$this->columnInOld = $columnInOld;
return $this;
}
/**
* @return int
*/
public function getColumnInNew()
{
return $this->columnInNew;
}
/**
* @param int $columnInNew
*
* @return DiffRowPosition
*/
public function setColumnInNew($columnInNew)
{
$this->columnInNew = $columnInNew;
return $this;
}
/**
* @param int $increment
*
* @return int
*/
public function incrementColumnInNew($increment = 1)
{
$this->columnInNew += $increment;
return $this->columnInNew;
}
/**
* @param int $increment
*
* @return int
*/
public function incrementColumnInOld($increment = 1)
{
$this->columnInOld += $increment;
return $this->columnInOld;
}
/**
* @param int $increment
*
* @return int
*/
public function incrementIndexInNew($increment = 1)
{
$this->indexInNew += $increment;
return $this->indexInNew;
}
/**
* @param int $increment
*
* @return int
*/
public function incrementIndexInOld($increment = 1)
{
$this->indexInOld += $increment;
return $this->indexInOld;
}
/**
* @param string $type
* @param int $increment
*
* @return int
*/
public function incrementIndex($type, $increment = 1)
{
if ($type === 'new') {
return $this->incrementIndexInNew($increment);
}
return $this->incrementIndexInOld($increment);
}
/**
* @param string $type
* @param int $increment
*
* @return int
*/
public function incrementColumn($type, $increment = 1)
{
if ($type === 'new') {
return $this->incrementColumnInNew($increment);
}
return $this->incrementColumnInOld($increment);
}
/**
* @param string $type
*
* @return bool
*/
public function isColumnLessThanOther($type)
{
if ($type === 'new') {
return $this->getColumnInNew() < $this->getColumnInOld();
}
return $this->getColumnInOld() < $this->getColumnInNew();
}
/**
* @param string $type
*
* @return int
*/
public function getColumn($type)
{
if ($type === 'new') {
return $this->getColumnInNew();
}
return $this->getColumnInOld();
}
/**
* @param string $type
*
* @return int
*/
public function getIndex($type)
{
if ($type === 'new') {
return $this->getIndexInNew();
}
return $this->getIndexInOld();
}
/**
* @return bool
*/
public function areColumnsEqual()
{
return $this->getColumnInOld() === $this->getColumnInNew();
}
/**
* @return null|string
*/
public function getLesserColumnType()
{
if ($this->isColumnLessThanOther('new')) {
return 'new';
} elseif ($this->isColumnLessThanOther('old')) {
return 'old';
}
return null;
}
}

@ -0,0 +1,133 @@
<?php
namespace Caxy\HtmlDiff\Table;
/**
* Class RowMatch
* @package Caxy\HtmlDiff\Table
*/
class RowMatch
{
/**
* @var int
*/
protected $startInNew;
/**
* @var int
*/
protected $startInOld;
/**
* @var int
*/
protected $endInNew;
/**
* @var int
*/
protected $endInOld;
/**
* @var float|null
*/
protected $percentage;
/**
* RowMatch constructor.
*
* @param int $startInNew
* @param int $startInOld
* @param int $endInNew
* @param int $endInOld
* @param float|null $percentage
*/
public function __construct($startInNew = 0, $startInOld = 0, $endInNew = 0, $endInOld = 0, $percentage = null)
{
$this->startInNew = $startInNew;
$this->startInOld = $startInOld;
$this->endInNew = $endInNew;
$this->endInOld = $endInOld;
$this->percentage = $percentage;
}
/**
* @return int
*/
public function getStartInNew()
{
return $this->startInNew;
}
/**
* @param int $startInNew
*
* @return RowMatch
*/
public function setStartInNew($startInNew)
{
$this->startInNew = $startInNew;
return $this;
}
/**
* @return int
*/
public function getStartInOld()
{
return $this->startInOld;
}
/**
* @param int $startInOld
*
* @return RowMatch
*/
public function setStartInOld($startInOld)
{
$this->startInOld = $startInOld;
return $this;
}
/**
* @return int
*/
public function getEndInNew()
{
return $this->endInNew;
}
/**
* @param int $endInNew
*
* @return RowMatch
*/
public function setEndInNew($endInNew)
{
$this->endInNew = $endInNew;
return $this;
}
/**
* @return int
*/
public function getEndInOld()
{
return $this->endInOld;
}
/**
* @param int $endInOld
*
* @return RowMatch
*/
public function setEndInOld($endInOld)
{
$this->endInOld = $endInOld;
return $this;
}
}

@ -0,0 +1,161 @@
<?php
namespace Caxy\HtmlDiff\Table;
/**
* Class Table
* @package Caxy\HtmlDiff\Table
*/
class Table extends AbstractTableElement
{
/**
* @var TableRow[]
*/
protected $rows = array();
/**
* @return TableRow[]
*/
public function getRows()
{
return $this->rows;
}
/**
* @param TableRow $row
*/
public function addRow(TableRow $row)
{
$this->rows[] = $row;
if (!$row->getTable()) {
$row->setTable($this);
}
}
/**
* @param TableRow $row
*/
public function removeRow(TableRow $row)
{
$key = array_search($row, $this->rows, true);
if ($key !== false) {
unset($this->rows[$key]);
if ($row->getTable()) {
$row->setTable(null);
}
}
}
/**
* @param int $index
*
* @return null|TableRow
*/
public function getRow($index)
{
return isset($this->rows[$index]) ? $this->rows[$index] : null;
}
/**
* @param TableRow[] $rows
* @param null|int $position
*/
public function insertRows($rows, $position = null)
{
if ($position === null) {
$this->rows = array_merge($this->rows, $rows);
} else {
array_splice($this->rows, $position, 0, $rows);
}
}
/**
* @param TablePosition $position
*
* @return null|TableCell
*/
public function getCellByPosition(TablePosition $position)
{
$row = $this->getRow($position->getRow());
return $row ? $row->getCell($position->getCell()) : null;
}
/**
* @param TablePosition $position
* @param int $offset
*
* @return TablePosition|null
*/
public function getPositionBefore(TablePosition $position, $offset = 1)
{
if ($position->getCell() > ($offset - 1)) {
$newRow = $position->getRow();
$newCell = $position->getCell() - $offset;
} elseif ($position->getRow() > 0) {
$cellsToMove = $offset;
$newRow = $position->getRow();
$newCell = $position->getCell();
while ($cellsToMove > 0 && $newRow >= 0) {
if ($cellsToMove > $newCell) {
$newRow--;
if ($newRow < 0) {
return null;
}
$cellsToMove = $cellsToMove - ($newCell + 1);
$cellCount = count($this->getRow($newRow)->getCells());
$newCell = $cellCount - 1;
} else {
$newCell = $newCell - $cellsToMove;
$cellsToMove -= $newCell;
}
}
} else {
return null;
}
if ($newRow >= 0 && $newCell >= 0) {
return new TablePosition($newRow, $newCell);
}
return null;
}
/**
* @param TablePosition $position
* @param int $offset
*
* @return TablePosition|null
*/
public function getPositionAfter(TablePosition $position, $offset = 1)
{
$cellsToMove = $offset;
$newRow = $position->getRow();
$newCell = $position->getCell();
while ($cellsToMove > 0 && $newRow < count($this->rows)) {
$cellCount = count($this->getRow($newRow)->getCells());
$cellsLeft = $cellCount - $newCell - 1;
if ($cellsToMove > $cellsLeft) {
$newRow++;
$cellsToMove -= $cellsLeft - 1;
$newCell = 0;
} else {
$newCell = $newCell + $cellsToMove;
$cellsToMove -= $cellsLeft;
}
}
if ($newRow >= 0 && $newCell >= 0) {
return new TablePosition($newRow, $newCell);
}
return null;
}
}

@ -0,0 +1,55 @@
<?php
namespace Caxy\HtmlDiff\Table;
/**
* Class TableCell
* @package Caxy\HtmlDiff\Table
*/
class TableCell extends AbstractTableElement
{
/**
* @var TableRow
*/
protected $row;
/**
* @return TableRow
*/
public function getRow()
{
return $this->row;
}
/**
* @param TableRow|null $row
*
* @return $this
*/
public function setRow(TableRow $row = null)
{
$this->row = $row;
if (null !== $row && !in_array($this, $row->getCells())) {
$row->addCell($this);
}
return $this;
}
/**
* @return int
*/
public function getColspan()
{
return (int)$this->getAttribute('colspan') ?: 1;
}
/**
* @return int
*/
public function getRowspan()
{
return (int)$this->getAttribute('rowspan') ?: 1;
}
}

@ -0,0 +1,921 @@
<?php
namespace Caxy\HtmlDiff\Table;
use Caxy\HtmlDiff\AbstractDiff;
use Caxy\HtmlDiff\HtmlDiff;
use Caxy\HtmlDiff\HtmlDiffConfig;
use Caxy\HtmlDiff\Operation;
/**
* Class TableDiff
* @package Caxy\HtmlDiff\Table
*/
class TableDiff extends AbstractDiff
{
/**
* @var null|Table
*/
protected $oldTable = null;
/**
* @var null|Table
*/
protected $newTable = null;
/**
* @var null|\DOMElement
*/
protected $diffTable = null;
/**
* @var null|\DOMDocument
*/
protected $diffDom = null;
/**
* @var int
*/
protected $newRowOffsets = 0;
/**
* @var int
*/
protected $oldRowOffsets = 0;
/**
* @var array
*/
protected $cellValues = array();
/**
* @var \HTMLPurifier
*/
protected $purifier;
/**
* @param string $oldText
* @param string $newText
* @param HtmlDiffConfig|null $config
*
* @return self
*/
public static function create($oldText, $newText, HtmlDiffConfig $config = null)
{
$diff = new self($oldText, $newText);
if (null !== $config) {
$diff->setConfig($config);
$this->initPurifier($config->getPurifierCacheLocation());
}
return $diff;
}
/**
* TableDiff constructor.
*
* @param string $oldText
* @param string $newText
* @param string $encoding
* @param array|null $specialCaseTags
* @param bool|null $groupDiffs
*/
public function __construct(
$oldText,
$newText,
$encoding = 'UTF-8',
$specialCaseTags = null,
$groupDiffs = null
)
{
parent::__construct($oldText, $newText, $encoding, $specialCaseTags, $groupDiffs);
$this->initPurifier();
}
/**
* Initializes HTMLPurifier with cache location
* @param null|string $defaultPurifierSerializerCache
* @return void
*/
protected function initPurifier($defaultPurifierSerializerCache = null)
{
$HTMLPurifierConfig = \HTMLPurifier_Config::createDefault();
// Cache.SerializerPath defaults to Null and sets
// the location to inside the vendor HTMLPurifier library
// under the DefinitionCache/Serializer folder.
if (!is_null($defaultPurifierSerializerCache)) {
$HTMLPurifierConfig->set('Cache.SerializerPath', $defaultPurifierSerializerCache);
}
$this->purifier = new \HTMLPurifier($HTMLPurifierConfig);
}
/**
* @return string
*/
public function build()
{
if ($this->hasDiffCache() && $this->getDiffCache()->contains($this->oldText, $this->newText)) {
$this->content = $this->getDiffCache()->fetch($this->oldText, $this->newText);
return $this->content;
}
$this->buildTableDoms();
$this->diffDom = new \DOMDocument();
$this->indexCellValues($this->newTable);
$this->diffTableContent();
if ($this->hasDiffCache()) {
$this->getDiffCache()->save($this->oldText, $this->newText, $this->content);
}
return $this->content;
}
protected function diffTableContent()
{
$this->diffDom = new \DOMDocument();
$this->diffTable = $this->newTable->cloneNode($this->diffDom);
$this->diffDom->appendChild($this->diffTable);
$oldRows = $this->oldTable->getRows();
$newRows = $this->newTable->getRows();
$oldMatchData = array();
$newMatchData = array();
/* @var $oldRow TableRow */
foreach ($oldRows as $oldIndex => $oldRow) {
$oldMatchData[$oldIndex] = array();
// Get match percentages
/* @var $newRow TableRow */
foreach ($newRows as $newIndex => $newRow) {
if (!array_key_exists($newIndex, $newMatchData)) {
$newMatchData[$newIndex] = array();
}
// similar_text
$percentage = $this->getMatchPercentage($oldRow, $newRow, $oldIndex, $newIndex);
$oldMatchData[$oldIndex][$newIndex] = $percentage;
$newMatchData[$newIndex][$oldIndex] = $percentage;
}
}
$matches = $this->getRowMatches($oldMatchData, $newMatchData);
$this->diffTableRowsWithMatches($oldRows, $newRows, $matches);
$this->content = $this->htmlFromNode($this->diffTable);
}
/**
* @param TableRow[] $oldRows
* @param TableRow[] $newRows
* @param RowMatch[] $matches
*/
protected function diffTableRowsWithMatches($oldRows, $newRows, $matches)
{
$operations = array();
$indexInOld = 0;
$indexInNew = 0;
$oldRowCount = count($oldRows);
$newRowCount = count($newRows);
$matches[] = new RowMatch($newRowCount, $oldRowCount, $newRowCount, $oldRowCount);
// build operations
foreach ($matches as $match) {
$matchAtIndexInOld = $indexInOld === $match->getStartInOld();
$matchAtIndexInNew = $indexInNew === $match->getStartInNew();
$action = 'equal';
if (!$matchAtIndexInOld && !$matchAtIndexInNew) {
$action = 'replace';
} elseif ($matchAtIndexInOld && !$matchAtIndexInNew) {
$action = 'insert';
} elseif (!$matchAtIndexInOld && $matchAtIndexInNew) {
$action = 'delete';
}
if ($action !== 'equal') {
$operations[] = new Operation(
$action,
$indexInOld,
$match->getStartInOld(),
$indexInNew,
$match->getStartInNew()
);
}
$operations[] = new Operation(
'equal',
$match->getStartInOld(),
$match->getEndInOld(),
$match->getStartInNew(),
$match->getEndInNew()
);
$indexInOld = $match->getEndInOld();
$indexInNew = $match->getEndInNew();
}
$appliedRowSpans = array();
// process operations
foreach ($operations as $operation) {
switch ($operation->action) {
case 'equal':
$this->processEqualOperation($operation, $oldRows, $newRows, $appliedRowSpans);
break;
case 'delete':
$this->processDeleteOperation($operation, $oldRows, $appliedRowSpans);
break;
case 'insert':
$this->processInsertOperation($operation, $newRows, $appliedRowSpans);
break;
case 'replace':
$this->processReplaceOperation($operation, $oldRows, $newRows, $appliedRowSpans);
break;
}
}
}
/**
* @param Operation $operation
* @param array $newRows
* @param array $appliedRowSpans
* @param bool $forceExpansion
*/
protected function processInsertOperation(
Operation $operation,
$newRows,
&$appliedRowSpans,
$forceExpansion = false
) {
$targetRows = array_slice($newRows, $operation->startInNew, $operation->endInNew - $operation->startInNew);
foreach ($targetRows as $row) {
$this->diffAndAppendRows(null, $row, $appliedRowSpans, $forceExpansion);
}
}
/**
* @param Operation $operation
* @param array $oldRows
* @param array $appliedRowSpans
* @param bool $forceExpansion
*/
protected function processDeleteOperation(
Operation $operation,
$oldRows,
&$appliedRowSpans,
$forceExpansion = false
) {
$targetRows = array_slice($oldRows, $operation->startInOld, $operation->endInOld - $operation->startInOld);
foreach ($targetRows as $row) {
$this->diffAndAppendRows($row, null, $appliedRowSpans, $forceExpansion);
}
}
/**
* @param Operation $operation
* @param array $oldRows
* @param array $newRows
* @param array $appliedRowSpans
*/
protected function processEqualOperation(Operation $operation, $oldRows, $newRows, &$appliedRowSpans)
{
$targetOldRows = array_values(
array_slice($oldRows, $operation->startInOld, $operation->endInOld - $operation->startInOld)
);
$targetNewRows = array_values(
array_slice($newRows, $operation->startInNew, $operation->endInNew - $operation->startInNew)
);
foreach ($targetNewRows as $index => $newRow) {
if (!isset($targetOldRows[$index])) {
continue;
}
$this->diffAndAppendRows($targetOldRows[$index], $newRow, $appliedRowSpans);
}
}
/**
* @param Operation $operation
* @param array $oldRows
* @param array $newRows
* @param array $appliedRowSpans
*/
protected function processReplaceOperation(Operation $operation, $oldRows, $newRows, &$appliedRowSpans)
{
$this->processDeleteOperation($operation, $oldRows, $appliedRowSpans, true);
$this->processInsertOperation($operation, $newRows, $appliedRowSpans, true);
}
/**
* @param array $oldMatchData
* @param array $newMatchData
*
* @return array
*/
protected function getRowMatches($oldMatchData, $newMatchData)
{
$matches = array();
$startInOld = 0;
$startInNew = 0;
$endInOld = count($oldMatchData);
$endInNew = count($newMatchData);
$this->findRowMatches($newMatchData, $startInOld, $endInOld, $startInNew, $endInNew, $matches);
return $matches;
}
/**
* @param array $newMatchData
* @param int $startInOld
* @param int $endInOld
* @param int $startInNew
* @param int $endInNew
* @param array $matches
*/
protected function findRowMatches($newMatchData, $startInOld, $endInOld, $startInNew, $endInNew, &$matches)
{
$match = $this->findRowMatch($newMatchData, $startInOld, $endInOld, $startInNew, $endInNew);
if ($match !== null) {
if ($startInOld < $match->getStartInOld() &&
$startInNew < $match->getStartInNew()
) {
$this->findRowMatches(
$newMatchData,
$startInOld,
$match->getStartInOld(),
$startInNew,
$match->getStartInNew(),
$matches
);
}
$matches[] = $match;
if ($match->getEndInOld() < $endInOld &&
$match->getEndInNew() < $endInNew
) {
$this->findRowMatches(
$newMatchData,
$match->getEndInOld(),
$endInOld,
$match->getEndInNew(),
$endInNew,
$matches
);
}
}
}
/**
* @param array $newMatchData
* @param int $startInOld
* @param int $endInOld
* @param int $startInNew
* @param int $endInNew
*
* @return RowMatch|null
*/
protected function findRowMatch($newMatchData, $startInOld, $endInOld, $startInNew, $endInNew)
{
$bestMatch = null;
$bestPercentage = 0;
foreach ($newMatchData as $newIndex => $oldMatches) {
if ($newIndex < $startInNew) {
continue;
}
if ($newIndex >= $endInNew) {
break;
}
foreach ($oldMatches as $oldIndex => $percentage) {
if ($oldIndex < $startInOld) {
continue;
}
if ($oldIndex >= $endInOld) {
break;
}
if ($percentage > $bestPercentage) {
$bestPercentage = $percentage;
$bestMatch = array(
'oldIndex' => $oldIndex,
'newIndex' => $newIndex,
'percentage' => $percentage,
);
}
}
}
if ($bestMatch !== null) {
return new RowMatch(
$bestMatch['newIndex'],
$bestMatch['oldIndex'],
$bestMatch['newIndex'] + 1,
$bestMatch['oldIndex'] + 1,
$bestMatch['percentage']
);
}
return null;
}
/**
* @param TableRow|null $oldRow
* @param TableRow|null $newRow
* @param array $appliedRowSpans
* @param bool $forceExpansion
*
* @return array
*/
protected function diffRows($oldRow, $newRow, array &$appliedRowSpans, $forceExpansion = false)
{
// create tr dom element
$rowToClone = $newRow ?: $oldRow;
/* @var $diffRow \DOMElement */
$diffRow = $this->diffDom->importNode($rowToClone->getDomNode()->cloneNode(false), false);
$oldCells = $oldRow ? $oldRow->getCells() : array();
$newCells = $newRow ? $newRow->getCells() : array();
$position = new DiffRowPosition();
$extraRow = null;