<?php if (!defined('PmWiki')) exit();
/**
  LocalTimes extension for PmWiki
  Fetches all changes to a page from the RecentChanges listings
  Written by (c) Petko Yotov 2011-2020 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 3 of the License, or
  (at your option) any later version. See pmwiki.php for full details
  and lack of warranty.
*/
# Version date
$RecipeInfo['LocalTimes']['Version'] = '20201220';

SDV($TimeCurrent, strftime($TimeFmt, $Now));
SDV($LastTimesHours, 48);

foreach($RecentChangesFmt as $k=>$v)
  $RecentChangesFmt[$k] = str_replace('$CurrentTime',
    '[[{$Group}.{$Name}?action=diff#diff$Now|$TimeCurrent]] %item prev$PrevModifiedTime%', $v);

if(@$_GET['nolt']==''
  && ($action=="diff" || strpos($pagename, 'RecentChanges')!==false)) {
    SDVA($HTMLFooterFmt, array('LocalTimes' => '<script type="text/javascript"
      src="$FarmPubDirUrl/localtimes.js" data-hours="$LastTimesHours"></script>'));
}

SDVA($HTMLStylesFmt, 
  array('localtimes'=>'.ltplus{cursor:pointer; opacity:.3; font-weight:bold; padding: 0 .3em;}
  .ltplus:hover{color: white; background: blue; opacity: 1;}
  .ltreload {filter:alpha(opacity=20); opacity:0.2; cursor: pointer;}
  .ltnew{background-color: #ffa;}'));
SDVA($HandleActions, array('lasttimes'=> 'HandleLastTimes'));
SDVA($HandleAuth, array('lasttimes'=> 'read'));

function HandleLastTimes($pagename, $auth='read') {
  global $LastTimesHours, $Now, $TimeFmt, $Charset;
  $since = $Now - $LastTimesHours*60*60;
  
  $page = RetrieveAuthPage($pagename, $auth, false, $since);
  
  $list = preg_grep('/^(csum|author):(\\d+)$/', array_keys($page));
  
  $changes = array();
  foreach($list as $v) {
    list($key, $stamp) = explode(':', $v);
    if($stamp == $page['time']) continue;
    
    $changes[$stamp][$key] = $page[$v];
    
  }
  
  $html = '';
  foreach($changes as $k=>$a) {
    $stamp = intval($k);
    $time = strftime($TimeFmt, $stamp);
    $author = $a['author'] ? $a['author'] : '?';
    $csum = str_replace(array('$'), array('&#036'), PHSC(@$a['csum']));
    
    $html .= "<li><a href='{\$PageUrl}?action=diff#diff$stamp'>$time</a> $[by] $author: $csum</li>";
  }
  
  $html = FmtPageName($html, $pagename);
  
  header("Content-Type: text/html; charset=$Charset");
  die($html);
}

function PrevModifiedTime($pagename, $page, $new) {
  global $PrevModifiedTime;
  $PrevModifiedTime = $page['time'];
}

array_unshift($EditFunctions, "PrevModifiedTime");