<?php if (!defined('PmWiki')) exit();
/* 
  RebuildRC: Recent Changes regeneration for Pmwiki
  
  Copyright 2018-2019 Petko Yotov pmwiki.org/petko
  
  This file 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 3 of the License, or
  (at your option) any later version.
*/

$RecipeInfo['RebuildRC']['Version'] = '20191125';

SDVA($HandleActions, array('rebuild-rc' => 'RebuildRC'));

function RebuildRC($pagename) {
  global $RecentChangesFmt, $PCache, $TimeFmt, $CurrentTime, $AuthorLink, $Author,
  $ChangeSummary, $RebuildRCPattern, $FmtPV, $WikiDir, $PageStartFmt, $PageEndFmt;
  
  $page = RetrieveAuthPage($pagename, 'admin', true, READPAGE_CURRENT);
  if(!$page) Abort('No permissions to rebuild RecentChanges.');

  $out = "markup:* Getting list of pages...\n";

  SDV($RebuildRCPattern, '*.*,-*.RecentChanges,-*.AllRecentChanges');
  $allpages = ListPages($RebuildRCPattern);
  sort($allpages);
  
  $pagearr = array();
  $rcarr = array();

  $out .= "** Reading and caching ".count($allpages)." pages...\n";

  for($i=0; $i<count($allpages); $i++) {
    $pn = $allpages[$i];
    $page = ReadPage($pn, READPAGE_CURRENT);
    $pagearr[$pn] = @$page['time'];
    PCache($pn, $page);
  }
  arsort($pagearr, SORT_NUMERIC);

  $out .= "* Rebuiling RecentChanges pages for ".count($allpages)." pages...\n";

  foreach($pagearr as $pn=>$time) {
    if(!$pn) continue;
    $FmtPV['$CurrentTime'] = "strftime(\$GLOBALS['TimeFmt'], $time)";
    $Author = @$PCache[$pn]['author'];
    $FmtPV['$AuthorLink'] = ($Author) ? "'[[~$Author]]'" : '"?"';
    $FmtPV['$ChangeSummary'] = "@\$PCache['$pn']['csum']";

    $seen = array();
    foreach($RecentChangesFmt as $rcfmt=>$pgfmt) {
      $rcname = FmtPageName($rcfmt,$pn);  if (!$rcname) continue;
      $pgtext = FmtPageName($pgfmt,$pn);  if (!$pgtext) continue;

      if ( @$seen[$rcname]++) continue;

      @$rcarr[$rcname] .= "$pgtext\n";
    }
  }

  $out .= "* Writing RecentChanges...\n";

  foreach($rcarr as $rcname=>$rctext) {
    $page = $new = ReadPage($rcname);
    $new['text'] = $rctext;
    PostPage($rcname, $page, $new);
    $out .= "** Written [[$rcname]] ([[$rcname?action=diff|diff]])\n";
  }
  $out .= "Done.\n";

  $fmt = array(&$PageStartFmt, &$out, &$PageEndFmt);
  PrintFmt($pagename, $fmt);
}