<?php if (!defined('PmWiki')) exit();
/** Copyright 2009 Petko Yotov (5ko@5ko.fr)
    Partly based on the PITS.php script by Patrick Michaud
    Copyright 2004-2009 Patrick R. Michaud (pmichaud@pobox.com)

    This file is part of PITS (PmWiki Issue Tracking System), 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.
*/

function NewPITSEntry($group)
{
	foreach(ListPages("/^$group\\.\\d/") as $i)
		$issue = max(@$issue,intval(substr($i,5),10));
	return sprintf("$group.%05d",@$issue+1);
}
$FmtPV['$NewEntry'] = 'NewPITSEntry($group)';

$PmForm['NewEntry'] = 'saveto={$NewEntry} form=PITS.Templates#pitsnew '
	. 'fmt=PITS.Templates#addpost Created=' . date('Y-m-d') ;

$PmForm['ModEntry'] = 'saveto={*$FullName} form=PITS.Templates#pitsheader'
	. ' fmt=PITS.Templates#modpost Posted=' . date('Y-m-d') ;


$MB_Encoding = 'UTF-8';
$EditAttrFields = array();

include_once("$FarmD/scripts/author.php");
include_once("$FarmD/cookbook/pmform.php");


$HTMLStylesFmt['pits'] = "
	table.pitsheader { border: 1px solid #888888; }
	table.pitsheader td strong { padding-left: 1em; }
	table.pitsheader th { background-color:#f8f8f8; border-bottom: 1px solid #888888; }
	table.pitsheader th input {  color: red; font-weight: bold; }
	textarea.w100 { width:100%; }
	.wikimessage { color: red; }
	table.pitsheader input, table.pitsheader select, table.pitsheader textarea { border: 1px inset #cccccc; }

	dl.pits2 { font-size: 85%; color: #888888; clear:both;border-top: 1px solid #dddddd; }
	dl.pits2 dt { float:left; padding-right:0.5em; }
	dl.pits2 dd { margin-left: 10em; }
	dl.pits2 dd span.pri { display: block; float: left; width: 4em; }
	dl.pits2 dd strong { color: black; font-weight: normal; }
	dl.pits2 dd em { float: right; }

	.supheader { margin: 4px 0; background-color: #eeeeee; border-bottom: 2px solid black; padding:2px; }
";

Markup('selectvar', 'inline', "/\\(:selectvar (.*?)\\s*:\\)/e", "FmtSelectVar(PSS('$1'))");

Markup('pits2list','directives','/\\(:pits2list\\s*(.*?):\\)/e',
  "FmtPits2List('',\$pagename,array('q'=>PSS('$1')))");


function FmtSelectVar($args)
{
	$opt = ParseArgs($args);
	list($name, $options, $selected) = $opt[''];
	$options = preg_split("/, */", $options);
	$out = "<select name='$name'>";
	$found = 0;
	foreach($options as $v)
	{
		$s = '';
		if($v == $selected)
		{
			$found = 1;
			$s = " selected='selected'";
		}
		$out .= "<option value='$v'$s>$v</option>";
	}
	if(!$found && trim($selected)>"" )
		$out .= "<option value='{$selected}' selected='selected'>{$selected}</option>";
	$out .= "</select>";
	return $out;
}

## This function creates specialized ordering functions needed to
## (more efficiently) perform sorts on arbitrary sets of criteria.
function CreateOrderFunction($order) {
  global $MB_Encoding;
  $code = '';
  foreach(preg_split('/[\\s,|]+/',mb_strtolower($order, $MB_Encoding),-1,PREG_SPLIT_NO_EMPTY) 
      as $o) {
    if (substr($o,0,1)=='-') { $r='-'; $o=substr($o,1); }
    else $r='';
    if (preg_match('/\\W/',$o)) continue;
    $code .= "\$c=strcasecmp(@\$x['$o'],@\$y['$o']); if (\$c!=0) return $r\$c;\n";
  }
  $code .= "return 0;\n";
  return create_function('$x,$y',$code);
}
## FmtPits2List creates a table of PITS issues according to various
## criteria.
function FmtPits2List($fmt,$pagename,$opt) {
  global $AutoSuspendDaysInactive, $Now, $PITSCache, $MB_Encoding;
  SDV($AutoSuspendDaysInactive, 0);
  $opt = array_merge($opt,@$_REQUEST);
  $pitslist = ListPages('/^PITS\\.\\d+$/');

  $terms = preg_split('/((?<!\\S)[-+]?[\'"].*?[\'"](?!\\S)|\\S+)/',
    $opt['q'],-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
  foreach($terms as $t) {
    if (trim($t)=='') continue;
    if (preg_match('/([^\'":=]*)[:=]([\'"]?)(.*?)\\2$/',$t,$match))
      $opt[mb_strtolower($match[1], $MB_Encoding)] = $match[3]; 
  }
  $n=0; $plist=$out=array();
  foreach($pitslist as $p) {
    if(!isset($PITSCache[$p]) ){
      $page = ReadPage($p, READPAGE_CURRENT);
      preg_match_all("/(^|\n)([A-Za-z][^:]*):([^\n]*)/",$page['text'],$match);
      $fields = array();
      for($i=0;$i<count($match[2]);$i++) 
        $fields[mb_strtolower($match[2][$i], $MB_Encoding)] =
          htmlspecialchars($match[3][$i],ENT_QUOTES);
      $fields['time'] = $page['time'];

      foreach(array('statut', 'type', 'priorite') as $x){
        $fields["{$x}2"] = Priority2($pagename, $x, @$fields[$x]);
      }
      
      if($AutoSuspendDaysInactive && !preg_match("/\\b(résolu|confirmé|en cours)\\b/i", $fields['statut'])
        && $page['time']+ $AutoSuspendDaysInactive*86400 < $Now)
          $fields['statut'] .= ' (inactif)';
      
      $PITSCache[$p] = $fields;
    }
    else $fields = $PITSCache[$p];


    foreach(array('statut', 'type', 'priorite', 'sommaire' ) as $h) {
      if (!@$opt[$h]) continue;
      $found = $tested = 0;
      foreach(preg_split('/[ ,]/',$opt[$h]) as $t) {
        if ($t{0}!='-' && $t{0}!='!') { # status=closed,suspended OR
          $tested = 1;
          if (strpos(mb_strtolower(@$fields[$h], $MB_Encoding),mb_strtolower($t, $MB_Encoding))!==false)
            $found = 1;
            continue;
        } else # status=!closed,!suspended
           if (strpos(mb_strtolower(@$fields[$h], $MB_Encoding),
             mb_strtolower(substr($t,1), $MB_Encoding))!==false)
              continue 3;
      }
      if($tested && !$found) continue 2;
    }
    $plist[$n] = $fields;
    $plist[$n]['name'] = $p;
    $n++;
  }
  $cmp = CreateOrderFunction(@$opt['order'].',type2,-priorite2,statut2,-name');
  usort($plist,$cmp);
  $cnt = 0;
  foreach($plist as $p) {
    $cnt ++;
    $out[] = Keep(FmtPageName("<dl class='pits2'><dt><a class='pitslink' href='\$PageUrl' "
     ."title='$cnt. Date : {$p['date']}'>\$Name</a> : {$p['type']}</dt>",$p['name'])
     ."<dd><em title='Statut'>{$p['statut']}</em> "
     ."<span class='pri' title='Priorite'>{$p['priorite']}</span> "
     ." <strong>{$p['sommaire']}</strong></dd></dl>\n");
    if(@$opt['count'] && $cnt>$opt['count']) break;
  }
  return implode('',$out);
}

function Priority2($pagename, $x, $value)
{
  global $MB_Encoding;
    $tn = MakePageName($pagename, 'Templates');
    $fields = PageTextVar($tn, $x);
    $fields = preg_split("/, */", mb_strtolower($fields, $MB_Encoding));
    $found = array_search(mb_strtolower(trim($value), $MB_Encoding), $fields);
    if($found === false) return count($fields);
    return $found;
}