<?php if (!defined('PmWiki')) exit();
/**
  FuseEdit - Combine successive minor edits in page histories
  Written by (c) Petko Yotov 2022 www.pmwiki.org/Petko

  This text is written for PmWiki; 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. See pmwiki.php for full details
  and lack of warranty.
*/
$RecipeInfo['FuseEdit']['Version'] = '20220118';


array_splice($EditFunctions, array_search('PostPage', $EditFunctions), 0, 'FuseEdit');

function FuseEdit($pagename, &$page, &$new) {
  global $Now, $ChangeSummary, $EnablePost, $Author, $EnableRCDiffBytes;
  if (!$EnablePost) return;
  if (@$_POST['diffclass'] !== 'minor') return;
  if ($page['agent'] != @$_SERVER['HTTP_USER_AGENT']) return;
  if ($page['host'] != $_SERVER['REMOTE_ADDR']) return;
  if ($page['author'] != @$Author) return;
  
  $time = $page['time'];
  $text = $page['text'];
  
  $x = preg_grep("/^diff:$time:/", array_keys($page));
  if (!$x) return;
  $lastdiffkey = array_shift($x);
  
  RestorePage($pagename,$page,$page,$lastdiffkey);
  
  if ($text != $page['text']) {
    # We remove the last diff, but keep the record in the page file, 
    # it may be needed for stats, troubleshooting, security;
    # diffclass=hidden hides the entry from ?action=diff (from 2.3.0)
    $_POST['diffclass'] = '';
    $newkey = preg_replace('/:[^:]*$/', ':hidden', $lastdiffkey);
    unset($new[$lastdiffkey]);
    $new[$newkey] = '';
    $new["csum:$time"] = XL('[Edit fused with more recent]') 
      . ' ' . $new["csum:$time"];

    if (IsEnabled($EnableRCDiffBytes, 0)) {
      $bytes = strlen($new['text']) - strlen($page['text']);
      if ($bytes>=0) $bytes = "+$bytes";
      $ChangeSummary = rtrim($ChangeSummary) . " ($bytes)";
      $new["csum:$Now"] = $new['csum'] = $ChangeSummary;
    }
  }
}