<?php
#
# HandleMSWord
# ============
#
#   Copyright 2007 Benjamin Wilson
#
#   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
#

SDV($EnableIgnoreLinks, 1);

$HandleActions['msword'] = 'HandleMSWord';
function HandleMSWord($pagename, $auth = 'read') {
  # handle display of a page
  global $DefaultPageTextFmt, $PageNotFoundHeaderFmt, $HTTPHeaders,
    $EnableHTMLCache, $NoHTMLCache, $PageCacheFile, $LastModTime, $IsHTMLCached,
    $FmtV, $HandleBrowseFmt, $PageStartFmt, $PageEndFmt, $PageRedirectFmt;
  $page = RetrieveAuthPage($pagename, $auth, true, READPAGE_CURRENT);
  if (!$page) Abort("?cannot read $pagename");
  PCache($pagename,$page);
  if (PageExists($pagename)) $text = @$page['text'];
  $wordname = preg_replace('/\./','-',$pagename);
  header("Content-Type: application/vnd.ms-word");
  header("Expires: 0");
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("content-disposition: attachment;filename=$wordname.doc");
  # We're purging links like mad here.
  if ($EnableIgnoreLinks) {
      $text = preg_replace("/\(:.?toc.*?:\)/",'',$text);
      $text = preg_replace("/\[\[.+?\|(.*?)\]\]/", '$1', $text);
      $text = preg_replace("/\[\[~(.*?)\]\]/", '$1', $text);
      $text = preg_replace("/\[\[(.*?)->.*?\]\]/", '$1', $text);
      $text = preg_replace("/\[\[(.*?)\]\]/", '$1', $text);
  }
  print "<html><body>";
  print MarkupToHTML($pagename, $text, $opt);
  print "</body></html>";
  HandleBrowse($pagename, $auth);
}