<?php if (!defined('PmWiki')) exit();
/*
 * xml4pmwiki - Include processed XML into PmWiki 2.x pages
 * Copyright (C) 2007 Jean-Fabrice
 * Portion of code Copyright 2005-2006 by D.Faure (dfaure@cpan.org)
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * http://www.pmwiki.org/wiki/Cookbook/Xml4pmwiki 
 */

$RecipeInfo['xml4pmwiki']['Version']='20070615';

if(PHP_VERSION >= 5) {
  function xslt_create() { return new XsltProcessor(); }
	function xslt_free($xsltproc) { unset($xsltproc); }
  function xslt_process($xsltproc, $xml_arg, $xsl_arg, 
                        $xslcontainer = null, $args = null, $params = null) {

    // Start with preparing the arguments
    $xml_arg = str_replace('arg:', '', $xml_arg);
    $xsl_arg = str_replace('arg:', '', $xsl_arg);

    // Load the xml document and the xsl template
    // creating instances of the DomDocument class
    $xml = DOMDocument::loadXML($args[$xml_arg]);
    $xsl = DOMDocument::loadXML($args[$xsl_arg]);

    // Load the xsl template
    $xsltproc->importStyleSheet($xsl);

    // Set parameters when defined
    if($params)
      foreach($params as $param => $value)
        $xsltproc->setParameter("", $param, $value);

    // Start the transformation
    $processed = $xsltproc->transformToXML($xml);

    // Put the result in a file when specified
    if($xslcontainer)
      return @file_put_contents($xslcontainer, $processed);
    else
      return $processed;
  }

}

if(!function_exists('file_get_contents')) {
  function file_get_contents($file) {
    $v = file($file);
    return ($v) ? implode('', $v) : false;
  }
}

if(!function_exists('file_put_contents')) {
  function file_put_contents($filename, $data, $file_append = false) {
    $fp = fopen($filename, (!$file_append ? 'w+' : 'a+'));
    if(!$fp)
      trigger_error('file_put_contents cannot write in file.', E_USER_ERROR);
    else {
      fputs($fp, $data);
      fclose($fp);
    }
  }
}

Markup ('xml4pmwiki', 'directives', '/\\(:xml4pmwiki (.*):\\)/e',
        "xml4pmwiki(\$pagename,ParseArgs(PSS('$1')))");

function xml4pmwiki($pagename,$args) {
	global $UploadFileFmt;
	foreach (array('xml', 'xsl') as $v) {
	  if(preg_match('/^Attach:(.*)/', $args[$v], $m)) {
	  	if(preg_match('!^(.*)/([^/]+)$!', $m[1], $match)) {
	      	  $pagename = MakePageName($pagename, $match[1]);
	          $path = $match[2];
	    } else $path = $m[1]; 
			$upname   = MakeUploadName($pagename, $path);
			$filepath = FmtPageName("$UploadFileFmt/$upname", $pagename);
			$xslt_args["/_$v"] = @file_get_contents($filepath);
	  }
	  elseif(preg_match('/^((?:https?|ftps?):\/\/.+)/', $args[$v], $m)) 
			$xslt_args["/_$v"] = @file_get_contents($m[1]); 
	  else 
			$xslt_args["/_$v"] = preg_replace('/(?:\s*\[@\s*|\s*@\]\s*)/', '', RetrieveAuthSection($pagename,$args[$v]));
	  if(!$xslt_args["/_$v"]) return Keep("<pre>$v data not found</pre>");
	}
	
	$debug      = @in_array('debug', $args['+']);
	$redoMarkup = ! @in_array('markup', $args['-']);
	$xslisutf8  = @in_array('xslisutf8', $args['']);
  if (!$xslisutf8) $xslt_args['/_xsl'] = utf8_encode($xslt_args['/_xsl']);
	unset($args['#'], $args['xml'], $args['xsl'], $args['+'], $args['-'], $args['']);

	$l = setlocale(LC_ALL,0);
	$xh     = xslt_create();
	$result = utf8_decode(xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $xslt_args, $args));
	xslt_free($xh);
	setlocale(LC_ALL,$l);
	
	if($debug) return Keep("<code><pre>".htmlentities($result)."</pre></code>");
	if($redoMarkup) return PRR(str_replace('<', '&lt;', $result));
	return Keep($result);
}