<?php
/* 
   Copyright 2003, 2004 John Rankin john.rankin@affinity.co.nz

   This file turns a trail page into a published book of the contents, in a
   form suitable for printing. Adds a Printable Version to each browse page.

   Provides an "Include this page" checkbox and lists links as endnotes.

   Handles [[include: ... ]] directives.

*/
if ($action=="print" || $action=="publish") {
    $HTMLHeaderFmt .= 
      "<link rel='stylesheet' href='\$ScriptDir/styles/print.css' type='text/css' />";
    $PageHeaderFmt = "<p id='wikisubtitle'>From $WikiTitle</p>
       <h1 id='printheader'><a class='wikiword' href='\$PageUrl?action=print'>\$Groupspaced: \$Titlespaced</a></h1>
       <div id='publish'>";
    $PageFooterFmt = array("</div><div id='endnotes'>",
                           "function:PrintEndnotes #",
      "</div><p id='printfooter'>
       $[Retrieved from] &ldquo;$PageUrlFmt&rdquo;<br />
       $[Page last modified on \$LastModified]</p>");
    $GroupHeaderFmt = '$Group.GroupPrintHeader';
    $GroupFooterFmt = '$Group.GroupPrintFooter';
    $DoubleBrackets["/\\[\\[mailto:($UrlPathPattern)(.*?)\\]\\]/"] =
      "''$2'' [[[mailto:$1 $1]]]";
    $WikiPageExistsFmt = 
      "<a class='wikiword' href='\$PageUrl?action=print'>\$LinkText</a>";
    $WikiPageCreateFmt = 
      "<a class='nonexistent' href='\$PageUrl?action=print'>\$LinkText</a>";
    $WikiPageCreateSpaceFmt =
      "<a class='nonexistent' href='\$PageUrl?action=print'>\$LinkText</a>";
    $UrlLinkTextFmt = "<cite>\$LinkText</cite> [<b>\$Url</b>]";
    $FmtUrlLink = 'FmtUrlLinkPublish';
    $TrailLinkPattern = 
      "(?:($GroupNamePattern)([\\/.]))?(($WikiWordPattern)|($FreeLinkPattern))";
    $DoubleBrackets["/&lt;&lt;\\|($TrailLinkPattern)\\|&gt;&gt;/"] = "$1";
    $DoubleBrackets["/\\^\\|($TrailLinkPattern)\\|\\^/"] = '';
    $DoubleBrackets["/&lt;\\|($TrailLinkPattern)\\|&gt;/"] = '';
    $InlineReplacements['/\\[\\[\\$Publish(.*?)\\]\\]/'] = '';
    $SpaceWikiWords = 1;
    $hide = 1;
} else
    $PageFooterFmt = str_replace("<br />",
    " - <a href='\$PageUrl?action=print' target='_blank'>$[Printable Version]</a><br />",
        $PageFooterFmt);
SDV($HandleActions['publish'],'HandlePublish');
$include = $HTTP_GET_VARS['include'];
SDV($HandlePublishFmt,array(&$HTMLStartFmt,&$PageHeaderFmt,
                            "wiki:$GroupHeaderFmt",
                            &$PublishList,
                            "wiki:$GroupFooterFmt",
                            &$PageFooterFmt,&$HTMLEndFmt));
SDV($PublishPageNotFoundFmt,'Page \'\'$Tlink\'\' does not exist.');
SDV($PublishPageNameFmt,"<a class='wikiword' href='\$PageUrl'>\$Titlespaced</a>:");
if (isset($EnablePathInfo) && !$EnablePathInfo) 
   SDV($PublishTagFmt,"<form class='publish' target='_blank' action='\$ScriptUrl' method='get'>
    \$PublishName<input type='hidden' name='pagename' value='\$PageName'>
    <input type='hidden' name='action' value='publish' />
    <input type='checkbox' name='include' value='include' />$[Include this page]
    <input type='submit' value='$[Publish]' /></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' />$[Include this page]
    <input type='submit' value='$[Publish]' /></form>");
SDV($InlineReplacements['/\\[\\[\\$Publish(nodate)?(:(.*?))?\\]\\]/e'],
   "FmtPublishName(\$GLOBALS['PublishTagFmt'],\$pagename,'\$3')");
$DoubleBrackets['/\\[\\[\\$Publish:(.*?)\\]\\]/e'] =
   'ValidatePublish("$pagename","$1");';
if (!isset($IncludeModifiedDate)) $IncludeModifiedDate = true;

function ValidatePublish($pagename,$publishpage) {
  global $GroupNamePattern,$PageTitlePattern;
  $delimiter = '/';
  if (preg_match("/^$GroupNamePattern([\\/.])$PageTitlePattern\$/",
      $publishpage,$match))
      $delimiter = $match[1];
  else
      $publishpage = FmtPageName('$Group',$pagename)."/$publishpage";
  if (PageExists($publishpage)) return "[[\$Publish:" . AsSpaced($publishpage) . "]]";
  else return str_replace($delimiter,"$delimiter{{",$publishpage) . "}} not found.";
}

function FmtPublishName($fmt,$pagename,$publishpage) {
  global $PublishPageNameFmt;
  if ($publishpage) {
     $publishpage = str_replace(" ","",$publishpage);
     $r = FmtPageName($PublishPageNameFmt,$publishpage);
  } else 
     $publishpage = $pagename;
  return str_replace('$PublishName',$r,FmtPageName($fmt,$publishpage));
}

function HandlePublish($pagename) {
  global $HandlePublishFmt,$TrailLinkPattern,$PublishPageNotFoundFmt;
  global $include,$HTMLTitle,$GCount,$LastModified,$IncludeModifiedDate;
  $trailname = FmtWikiLink('',$pagename,NULL,'PageName');
  $trailpage = ReadPage($trailname);
  if ($trailpage) {
    $LastModified = $trailpage['timefmt'];
    if (strstr($trailpage['text'],'[[$Publishnodate]]')) $IncludeModifiedDate = 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]);
          $depth[] = strlen($match[1]);
          if (preg_match("/^(\\[\\[)?($TrailLinkPattern)/",$match[2],$text)) {
              $pg = ($text[3]>'')?$text[2]: $trailgroup.'/'.$text[2];
              $pages[] = FmtWikiLink('',$pg,NULL,'PageName',$trailpage);
              if (preg_match("/^\\[\\[($TrailLinkPattern)((?:\\s.*?)\\]\\])/",
                               $match[2],$dbm))
                  $links[] = "[[".$pg.array_pop($dbm);
              else
                  $links[] = $pg;
          } elseif (!strstr($match[1],":")) {
              $pages[] = "textonly";
              $links[] = $match[2];
          }
      }
    }
    if (isset($include)) {
        $PublishList[] = "function:PrintThisPage $pagename";
    }
    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];
      for($j=1;$j<$depth[$i];$j++) $num .= "." . $counter[$j];
      $PublishList[] = "function:PrintText !$num $links[$i]";
      if ($pages[$i]!="textonly") {
          if (PageExists($pages[$i]))
		$PublishList[] = "function:PrintThisPage $pages[$i]";
          else {
              if (preg_match("/\\[\\[($TrailLinkPattern)\\s+/",$links[$i],$m)) {
                 $alias=str_replace("]]",")",str_replace($m[0],"(",$links[$i]));
                 $replname = "$m[1] $alias";
              } else $replname = $links[$i];
              $PublishList[] = 
                  "function:PrintText " . 
                  str_replace('$Tlink',$replname,$PublishPageNotFoundFmt);
          }
      }
    }
  }
  $GLOBALS['PublishList'] = $PublishList;
  $HTMLTitle = "Publish $pagename"; $GCount = 0;
  PrintFmt($pagename,$HandlePublishFmt);
}

function PrintThisPage($pagename,$wikipage=NULL) {
  global $IncludeModifiedDate;
  if (is_null($wikipage)) $wikipage=$pagename;
  if (PageExists($wikipage)) {
    $page = RetrieveAuthPage($wikipage,"read",false);
    $GLOBALS['pagename'] = $wikipage;
    PrintText($wikipage,PrepareText($wikipage,$page['text']));
    if ($IncludeModifiedDate) PrintText($wikipage,"\n\n(".$page['timefmt'].")");
    $GLOBALS['pagename'] = $pagename;
  }
}

function PrepareText($pagename,$text) {
  global $GroupNamePattern,$PageTitlePattern,$MaxIncludes,$BrowseDirectives;
  $inclcount=0;
  while ($inclcount<$MaxIncludes &&
      preg_match("/\\[\\[include:(.*?)\\]\\]/",$text,$match)) {
    $inclrepl=$match[0]; $inclname=$match[1]; $incltext='';
    if (!preg_match("/^$GroupNamePattern([\\/.])$PageTitlePattern\$/",
        $inclname))
      $inclname = FmtPageName('$Group',$pagename).".$inclname";
    $inclpage = RetrieveAuthPage($inclname,"read",false);
    if ($inclpage) $incltext=$inclpage['text'];
    $text = str_replace($inclrepl,$incltext,$text);
    $inclcount++;
  }
  Lock(0);
  foreach($BrowseDirectives as $p=>$s) {
    if (strstr($text,$p)) $text = str_replace($p,eval($s),$text);
  }
  return $text;
}

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

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

function FmtUrlLinkPublish($pat,$ref,$btext) {
  if (!is_null($btext)) { $ref = Endnote($ref); }
  return FmtUrlLink($pat,$ref,$btext);
}

?>