<?php  if(!defined('PmWiki')) exit();

/*

  Most recently viewed / most popular/ less popular pages

  A shameless copy of PostRecentChanges but runs on each access
  to the wiki, in any action: view, edit, print and any other.

  Runs trough PostConfig, set at the bottom  of this recipe.

  Keeps most accessed/viewed pages on top, and those that are 
  not accessed as much at the bottom, it does not keep a list
  with all pages, just those pages accessed at least one time

  *****
  *
  *  Copyright 2018 Carlos A. Bonamigo <cabsec.pmwiki@gmail.com>
  *
  *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  *****

*/

$RecipeInfo['RecentViews']['Version']  =  '20180319';

SDV($RecentViewsFmt , array(
  '$SiteGroup.AllRecentViews' => 
    '* [[{$Group}.{$Name}]]  . . . $CurrentTime $[by] $AuthorLink: [=$ChangeSummary=]',
  '$Group.RecentViews' =>
    '* [[{$Group}/{$Name}]]  . . . $CurrentTime $[by] $AuthorLink: [=$ChangeSummary=]'
));
SDV($RVDelimPattern,$RCDelimPattern);
SDV($RVLinesMax,$RCLinesMax);

function PostRecentViews($pagename,$Fmt=null) {
  global $RecentViewsFmt, $RVDelimPattern, $RVLinesMax;

  if ($Fmt==null) $Fmt = $RecentViewsFmt;
  foreach($Fmt as $rvfmt=>$pgfmt) {
    $rvname = FmtPageName($rvfmt,$pagename); if (!$rvname) continue;
    $pgtext = FmtPageName($pgfmt,$pagename); if (!$pgtext) continue;
    if ($pagename == $rvname) return;
    if (@$seen[$rvname]++) continue;
    $rvpage = ReadPage($rvname);
    $rvelim = preg_quote(preg_replace("/$RVDelimPattern.*$/",' ',$pgtext),'/');
    $rvpage['text'] = preg_replace("/^.*$rvelim.*\n/m", '', @$rvpage['text']);
    if (!preg_match("/$RVDelimPattern/",$rvpage['text'])) 
      $rvpage['text'] .= "$pgtext\n";
    else
      $rvpage['text'] = preg_replace("/([^\n]*$RVDelimPattern.*\n)/",
        str_replace("$", "\\$", $pgtext) . "\n$1", $rvpage['text'], 1);
    if (@$RVLinesMax > 0) 
      $rvpage['text'] = implode("\n", array_slice(
          explode("\n", $rvpage['text'], $RVLinesMax + 1), 0, $RVLinesMax));
    WritePage($rvname, $rvpage);
  }
}


$PostConfig['PostRecentViews'] = "300";