<?php
/* 
   Copyright 2003, 2004, 2005 John Rankin john.rankin@affinity.co.nz
   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 file turns a trail page into a published book of the contents, in a
   form suitable for printing. Enhances Printable View on each browse page.

*/
Markup('red','>links','/\(:(redirect)\s+(.*?):\)/','<em>$1s to $2</em>');
if ($action=="print" || $action=="publish") {
    $EnablePrint = 0;
    $ActionSkin[$action] = 'publish';
    $ActDescription = ($action=='print') ? 'last modified' : 'collection published';
    $GroupHeaderFmt = '(:include $Group.GroupPrintHeader:)(:nl:)';
    $GroupFooterFmt = '(:nl:)(:include $Group.GroupPrintFooter:)';
    $LinkPageExistsFmt = 
      "<a class='wikilink' href='\$PageUrl?action=print'>\$LinkText</a>";
    $LinkPageCreateFmt = 
      "<a class='createlinktext' href='\$PageUrl?action=print'>\$LinkText</a>";
    $LinkPageCreateSpaceFmt = $LinkPageCreateFmt;
    $UrlLinkTextFmt = "<cite>\$LinkText</cite> [<b>\$LinkUrl</b>]";
    $oLinkUrlFunction = $LinkFunctions['http:'];
    $LinkFunctions['http:'] = 'LinkIMapPublish';
    Markup('[[mail','<[[|',
"/\[\[mailto:([^\s$UrlExcludeChars]*[^\s.,?!$UrlExcludeChars])\s*\|\s*(.*?)\]\]/e",
      "Addressee('$2') . ' [' . 
      Keep(Makelink(\$pagename,'mailto:$1','$1'),'L') . ']'");
    Markup('<<|','<links','/&lt;&lt;\\|([^|]+|\\[\\[(.+?)\\]\\])\\|&gt;&gt;/e',
        "MakeTrailHome(\$pagename,'$1')");
    Markup('<|','><<|','/&lt;\\|([^|]+|\\[\\[(.+?)\\]\\])\\|&gt;/','');
    Markup('^|','<links','/\\^\\|([^|]+|\\[\\[(.+?)\\]\\])\\|\\^/','');
    Markup('pub','>links','/\(:\*?publish(nodate)?(\s+(.*?))?:\)/','');
    Markup('sect','inline','/\[\[#pub(\d+(?:\.\d+)*)\]\]\1&ensp;/',
        '[[#pub$1]]<span class=\'section\'>$1&ensp;</span>');
    $SpaceWikiWords = 2;
    $PDFImgFmt = '';
    if ($action=='print') $HandleActions['print'] = 'HandleBrowse';
    else $FmtP['/\\$LastModified/e'] = '$GLOBALS[\'CurrentTime\']';

} 
$needle = isset($_GET['needle']) ? $_GET['needle'] : '';
if ($needle!='') {
    SDV($HandleActions['publish'],'HandleSearchPublish');
    $haystack = $_GET['haystack'];
    $pagearray = @$_GET['pagearray'];
    $PrintHeaderFmt = 'Selected Search Results';
    $SearchForFmt = "<h4>$[SearchFor]</h4>";
} else {
    SDV($HandleActions['publish'],'HandlePublish');
    $include = isset($_GET['include']) ? $_GET['include'] : '';
    if (@$_GET['plain']) $NumberPages = false;
    $PrintHeaderFmt = "<a class='wikilink' href='\$PageUrl?action=print'>\$Group: \$Name</a>";
    $SearchForFmt = '';
}
SDV($HandlePublishFmt,array(&$PageStartFmt,
                            'markup:(:groupheader:)',
                            &$PublishList,
                            'markup:(:groupfooter:)',
                            &$PageEndFmt));
SDV($PublishPageNotFoundFmt,'Page \'\'$Tlink\'\' does not exist.');
SDV($PublishPageUnauthorisedFmt,'Not authorised to read page \'\'$Tlink\'\'.');
SDV($PublishPageNameFmt,"<a class='wikilink' href='\$PageUrl'>\$Title</a>:");
SDV($PublishPageStyleFmt,"<input type='hidden' name='plain' value='plain' />");
SDV($PublishTagFmt,"<form class='publish' target='_blank' action='\$ScriptUrl' method='get'>
    \$PublishName<input type='hidden' name='n' value='\$FullName' />
    <input type='hidden' name='action' value='publish' />\$PublishStyle
    <input type='submit' value='$[Publish]' />
    <input type='checkbox' name='include' value='include' checked />$[Include this index page]</form>");
/*
SDV($PublishTagFmt,"<form class='publish' target='_blank' action='\$PageUrl' method='get'>
    \$PublishName<input type='hidden' name='action' value='publish' />
    <input type='checkbox' name='include' value='include' checked />$[Include this page]
    <input type='submit' value='$[Publish]' /></form>");
*/
Markup('pub','<links','/\(:(\*)?publish(nodate)?(?:\s+(.*?))?:\)/e',
   "Keep(FmtPublishName(\$GLOBALS['PublishTagFmt'],\$pagename,'\$1','\$3'))");
Markup('pubpg','directives','/\(:(\*)?publish\s+(.*?):\)/e',
    "ValidatePublish(\$pagename,'$1',PSS('$2'))");
SDV($IncludeModifiedDate,true);
SDV($NumberPages,true);
SDVA($LinkCleanser, array(
    '/`\..*?$/' => '...',
    "/\\[\\[([^|\\]]+)\\|(.*?)\\s*\\]\\]($SuffixPattern)/e" =>
            "MakeLink(\$pagename,PSS('$1'),PSS('$2'),'$3','\$LinkText')",
    "/\\[\\[([^\\]]+?)\\s*-+&gt;\\s*(.*?)\\]\\]($SuffixPattern)/e" =>
            "MakeLink(\$pagename,PSS('$2'),PSS('$1'),'$3','\$LinkText')",
    '/\\[\\[#([A-Za-z][-.:\\w]*)\\]\\]/' => "",
    "/\\[\\[(.*?)\\]\\]($SuffixPattern)/e" =>
            "MakeLink(\$pagename,PSS('$1'),NULL,'$2','\$LinkText')",
    '/[\\[\\{](.*?)\\|(.*?)[\\]\\}]/' => '$1',
    "/`(($GroupPattern([\\/.]))?($WikiWordPattern))/" => '$1'
            ));

function ValidatePublish($pagename,$style,$publishpage) {
  global $GroupPattern,$NamePattern;
  $delimiter = '/';
  if (preg_match("/^$GroupPattern([\\/.])$NamePattern\$/",
      $publishpage,$match))
      $delimiter = $match[1];
  else
      $publishpage = FmtPageName('$Group',$pagename)."/$publishpage";
  if (PageExists($publishpage)) 
      return '(:'.$style.'publish '.$publishpage.':)';
  else return "[[$publishpage]] not found.";
}

function FmtPublishName($fmt,$pagename,$style,$publishpage) {
  global $PublishPageNameFmt,$PublishPageStyleFmt;
  $s = ($style) ? $PublishPageStyleFmt : '';
  if ($publishpage) {
     $publishpage = str_replace(" ","",$publishpage);
     $r = FmtPageName($PublishPageNameFmt,$publishpage);
     $fmt = str_replace('this','that',$fmt);
  } else {
     $r = '';
     $publishpage = $pagename;
  }
  return str_replace('$PublishName',$r,str_replace('$PublishStyle',$s,
    FmtPageName($fmt,$publishpage)));
}

function HandlePublish($pagename) {
  global $SuffixPattern,$GroupPattern,$WikiWordPattern,$LinkWikiWords;
  global $SpaceWikiWords,$AsSpacedFunction,$SpaceWikiWordsFunction;
  global $HandlePublishFmt,$PublishPageNotFoundFmt;
  global $include,$GCount,$IncludeModifiedDate,$NumberPages;
  SDV($SpaceWikiWordsFunction,$AsSpacedFunction);
  $trailname = $pagename;
  $trailpage = ReadPage($pagename,"read");
  if ($trailpage) {
    if (strstr($trailpage['text'],'publishnodate:)')) $IncludeModifiedDate = false;
#    if (strstr($trailpage['text'],'(:*publish')) $NumberPages = false;
    $trailgroup = FmtPageName('$Group',$trailname);
    foreach(explode("\n",$trailpage['text']) as $x) {
      if (preg_match("/^T?([#*:]+)\\s*(.*)/",$x,$match)) {
          $match[1] = str_replace(':#',':',$match[1]);
          if ($LinkWikiWords) $match[2] = 
    preg_replace("/^($GroupPattern([\\/.]))?($WikiWordPattern)/e",
    "'[[$1'.(($SpaceWikiWords)?$SpaceWikiWordsFunction('$3'):'$3').']]'", $match[2]);
          $match[2] = 
    preg_replace("/\\[\\[([^\\]]*)->([^\\]]*)\\]\\]/",'[[$2|$1]]',$match[2]);
          if (preg_match("/^(\\[\\[([^|]*?)(\\|.*?)?\\]\\]($SuffixPattern))/",
      $match[2],$m)) {
            $depth[] = strlen($match[1]);
            $pages[] = MakePageName($trailname,$m[2]);
            $links[] = $m[1];
          } elseif (!strstr($match[1],":")) {
            $match[2] = preg_replace('/`\\..*?$/','',$match[2]);
            if ($match[2]!='') {
                $depth[] = strlen($match[1]);
                $pages[] = "textonly";
                $links[] = $match[2];
            }
          }
      }
    }
#    if ($include) $PublishList[] = "function:PrintThisPage $pagename";
    $counter = array(); $predepth= 0;
    for($i=0;$i<count($pages);$i++) {
      @$counter[$depth[$i]-1]++;
      $num = $counter[0];
      for($j=$depth[$i];$j<$predepth;$j++) $counter[$j] = 0;
      $predepth = $depth[$i];
      $size = 0;
      for($j=1;$j<$depth[$i];$j++) { $num .= "." . $counter[$j]; $size++; }
      if ($size>3) $size=3;
      
preg_match("/^\\[\\[([^\\]\\|]*?)(?:\\|([^\\]]*?))?\\]\\]($SuffixPattern)$/",
$links[$i],$l);
$toc[] = "[[#pub$num|".(($pages[$i]=="textonly") ? 
  CleanText($trailname,$links[$i]) :
  MakeLink($trailname,$l[1],(($l[2]) ? $l[2] : NULL),(($l[3]) ? $l[3] : NULL),
  '$LinkText')).']]';

      $num = $NumberPages ? "[[#pub$num]]$num&ensp; " : "[[#pub$num]]";
      $s = str_repeat('-',$size);
      $PublishList[] = "<div class='pagehead$depth[$i]'>";
      if ($size==0) $PublishList[] = "markup:!$num$links[$i]";
      else $PublishList[] = "markup:![$s$num$links[$i]$s]";
      $PublishList[] ='</div>';
      if ($pages[$i]!="textonly") {
          if (PageExists($pages[$i])) 
	       	  $PublishList[] = "function:PrintThisPage $pages[$i]";
          else {
              $replname = MakeLink($trailname,$links[$i],NULL,NULL,'$LinkText');
              if (MakeLink($trailname,"[[$replname]]",NULL,NULL,'$PageName')==$pages[$i])
                $replname = $links[$i];
              else $replname = "[[".$pages[$i]."]] ($replname)";
              $PublishList[] = 
                  "markup:" . 
                  str_replace('$Tlink',$replname,$PublishPageNotFoundFmt);
          }
      }
    }
  }

### trial toc
if ($include) {
    $count = 0;
    foreach(explode("\n",$trailpage['text']) as $x) {
      if (preg_match("/^(T?[#*:]+\\s*)(.*)/",$x,$match)) {
          if ($LinkWikiWords) $match[2] = 
    preg_replace("/^($GroupPattern([\\/.]))?($WikiWordPattern)/e",
    "'[[$1'.(($SpaceWikiWords)?$SpaceWikiWordsFunction('$3'):'$3').']]'", $match[2]);
          $match[2] = 
    preg_replace("/^\\[\\[([^\\]]*)->([^\\]]*)\\]\\]/",'[[$2|$1]]',$match[2]);
          if (preg_match("/^(\\[\\[([^|]*?)(\\|.*?)?\\]\\]($SuffixPattern))/",
      $match[2],$m)) {
            $x = $match[1].str_replace($m[1],$toc[$count],$match[2]);
            $count++;
          } elseif (!strstr($match[1],":")) {
            $ltext = preg_replace('/`\\..*?$/','',$match[2]);
            if ($ltext!='') {
                $x = $match[1].str_replace($ltext,$toc[$count],$match[2]);
                $count++;
            }
          }
      }
    $line[] = $x;
    }
    array_unshift($PublishList,array('markup:[[#pubtop]]',
        'function:PrintText '.implode("\n",$line)));
} else array_unshift($PublishList,'markup:[[#pubtop]]');
###

  $GLOBALS['PublishList'] = $PublishList;
  $GCount = 0;
  PrintFmt($pagename,$HandlePublishFmt);
}

function HandleSearchPublish($pagename) {
  global $HandlePublishFmt,$GCount;
  global $needle,$haystack,$pagearray;
  for($i=0;$i<count($pagearray);$i++) {
    $PublishList[] = "markup:![[".$pagearray[$i]."]]";
    $PublishList[] = "function:PrintThisPage $pagearray[$i]";
  }
  if (count($pagearray)==0) $PublishList[] = "<h3>$[No pages selected]</h3>";
  $GLOBALS['PublishList'] = $PublishList;
  $GLOBALS['Needle'] = $needle;
  $GLOBALS['Haystack'] = $haystack;
  $GCount = 0;
  PrintFmt($pagename,$HandlePublishFmt);
}

function CleanText($pagename,$text) {
  global $LinkCleanser;
  foreach ($LinkCleanser as $p => $c) $text = preg_replace($p,$c,$text);
  return $text;
}

function MakeTrailHome($pagename,$trailname) {
  global $SpaceWikiWords,$AsSpacedFunction,$SpaceWikiWordsFunction;
  global $GroupPattern,$WikiWordPattern;
  if (preg_match('/^\\[\\[(.+?)(-&gt;|\\|)(.+?)\\]\\]$/', $trailname, $m)) 
    $trailname = ($m[2] == '|') ? $m[3] : $m[1];
  else
    $trailname = preg_replace("/^($GroupPattern([\\/.]))?($WikiWordPattern)/e",
    "'$1'.(($SpaceWikiWords)?$SpaceWikiWordsFunction('$3'):'$3')",$trailname);
  return "[[#pubtop | $trailname]]";
}

function PrintText($pagename,$text) {
  echo MarkupToHTML($pagename,$text);
}

function PrintThisPage($pagename,$wikipage=NULL) {
  global $IncludeModifiedDate,$PublishPageUnauthorisedFmt,$TimeFmt;
  if (is_null($wikipage)) $wikipage=$pagename;
  $page = RetrieveAuthPage($wikipage,"read",false);
  if ($page) {
    $GLOBALS['pagename'] = $wikipage;
    SetInterMapUrls($wikipage);
    echo MarkupToHTML($wikipage,$page['text']);
    if ($IncludeModifiedDate) 
      echo MarkupToHTML($wikipage,"\n\n(".strftime($TimeFmt,$page['time']).")");
    $GLOBALS['pagename'] = $pagename;
  } else echo MarkupToHTML($wikipage,
            str_replace('$Tlink',$wikipage,$PublishPageUnauthorisedFmt));
}

function SetInterMapUrls($page) {
  global $UploadUrlFmt,$UploadPrefixFmt,$InterMapUrls;
  $InterMapUrls['Attach'] = 
        FmtPageName("$UploadUrlFmt$UploadPrefixFmt$1",$page);
}

function PrintEndnotes($pagename,$urltext) {
  $etext = Endnote('',$urltext);
  if ($etext!="") echo MarkupToHTML($pagename,$etext);
}

function Endnote($imap,$urltext) {
  static $endcount, $endtext;
  if ($urltext == "#") {
     $r = "$endtext";
     if ($endcount>0) $r = "!Links\n$r";
     $endcount = 0;
     $endtext = '';
  } else {
     $endcount++;
     $r = "<a href='#end$endcount'>$endcount</a>";
     $urltext = str_replace('&amp;','&',stripslashes($urltext));
     $txt = preg_replace('/^\\/\\/(.*?)\\/?$/',"$1",$urltext);
     $endtext .= "# [[#end$endcount]] [[$imap$urltext | $txt]]\n";
  }
  return $r;
}

function LinkIMapPublish($pagename,$imap,$path,$title,$txt,$fmt=NULL) {
  global $ImgExtPattern,$UrlLinkTextFmt,$oLinkUrlFunction;
  if (strstr("$imap$path",$txt) || preg_match("/$ImgExtPattern\$/",$path)) 
      return $oLinkUrlFunction($pagename,$imap,$path,$title,$txt,$fmt);
  return str_replace('$LinkUrl',Endnote($imap,$path),
            str_replace('$LinkText',$txt,$UrlLinkTextFmt));
}

function Addressee($name) {
  global $WikiWordPattern;
  $r = preg_replace("/($WikiWordPattern)/","`$1",$name);
  return "<em>$r</em>";
}

?>
