<?php if (!defined('PmWiki')) exit();
/**
  Even Simpler Page Rating for PmWiki
  Written by (2009) Petko Yotov http://5ko.fr

  This text is hereby released into the Public Domain.
 */

$RecipeInfo['Rating2']['Version'] = '20100216';

global $FmtPV, $EnableBasepageUpdate;
$FmtPV['$Rating2'] = '@$page["rating2"]';
$FmtPV['$Users'] = '@$page["users"]';


foreach(array('count', 'percent', 'diff', 'neg', 'pos', 'diffpad') as $v ) {
  $FmtPV["\$Rating2$v"] = "Rating2Stat(@\$page['rating2'], '$v')";
  if(IsEnabled($EnableBasepageUpdate, 0))
    $FmtPV["\$Users$v"] = "Rating2Stat(@\$page['users'], '$v')";

}
array_unshift($EditFunctions,'Rating2');
function Rating2( $pagename, &$page, &$new ) {
  global $EnablePost, $EnableBasepageUpdate;
  if (!$EnablePost) return;
  preg_match_all("/^\\s*[\\*#]+\\s*\\(([+-])+\\w*\\)/m", $new['text'], $m, PREG_PATTERN_ORDER);
  $ratings = array_count_values($m[1]);
  $pos = (@$ratings['+']>0)? "+{$ratings['+']}" :"";
  $neg = (@$ratings['-']>0)? "-{$ratings['-']}" :"";
  if( count($ratings) == 0 ) unset($new['rating2']);
  else $new['rating2'] = trim("$pos $neg");
  if(IsEnabled($EnableBasepageUpdate, 0))
    UpdateBasepageRating($pagename, @$new['rating2']);
}

## pmwiki.org's cookbook specific
function UpdateBasepageRating($pagename, $rating) {
  if ( substr($pagename, -6) !='-Users' ) return;
  $basename = substr($pagename, 0, -6);
  $base = RetrieveAuthPage($basename, "edit", false);
  if(@$base['text']>'' && @$base['users'] != $rating) {
    if( $rating>'') $base['users'] = $rating;
    else unset($base['users']);
    WritePage($basename, $base);
  }
}
function Rating2Stat($x, $what) {
  if(!$x) return;
  list($pos, $neg) = explode(' ', $x);
  $pos = intval($pos); $neg = intval($neg);
  $num = abs($pos)+abs($neg);
  switch ($what) {
    case "count":  return $num;
    case "percent": return round($pos/$num*100);
    case "diff": return $pos+$neg;
    case "diffpad": return sprintf("%05d", $pos+$neg);
    case "pos": return $pos;
    case "neg": return abs($neg);
  }
  return $x ; # shouldn't happen
}