<?php if (!defined('PmWiki')) exit();
# vim: set ts=4 sw=4 et:
##
##        File: MiscMX.php
##     Version: 2008-09-20
##      SVN ID: $Id: MiscMX.php 233 2008-09-19 22:07:36Z pbowers $
##      Status: alpha
##      Author: Peter Bowers
## Create Date: May 5, 2008
##   Copyright: 2008, Peter Bowers
##
## Each of these MXes is WikiSh compatible but not WikiSh dependent.  If you
## have WikiSh installed then you can take advantage of pipes, output 
## redirection, option setting via -x and --opt and --opt:val, etc.  If WikiSh
## is not installed then you must set options by opt=val syntax and you will
## miss some of the other capabilities, but you will still be able to use them
## as a simple MX.
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License, Version 2, as
## published by the Free Software Foundation.
## http://www.gnu.org/copyleft/gpl.html
## 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.
##

$RecipeInfo['MiscMX']['Version'] = '2008-09-20';

$MarkupExpr["preg_quote"] = 'preg_quote($args[0])'; 

# Crypt()
# OPTIONS
#  --salt:<salt>
$MarkupExpr["crypt"] = 'MiscCrypt($pagename, @$argp, @$args)'; 
function MiscCrypt($pagename, $opt, $args)
{
    #echo "pre opt=". print_r($opt, true) . "<br>\n";
	if (defined('WikiSh')) WikiShCompatible($pagename, $opt, $args);
    #echo "post args=". print_r($args, true) . "<br>\n";
    #echo "post opt=". print_r($opt, true) . "<br>\n";
    #echo "post salt=$opt[salt]<br>\n";
    #echo "IN: " . implode(" ", $args) . ", OUT=" . ($opt['salt'] ? crypt(implode(" ", $args), $opt['salt']) : crypt(implode(" ", $args))) . "<br>\n";
    if ($opt['salt'])
        $rtn = crypt(implode(" ", $args), $opt['salt']);
    else
        $rtn = crypt(implode(" ", $args));
	if (defined('WikiSh')) return(wshPostProcess($pagename, $opt, (array)$rtn)); 
	else return($rtn);
}

# OPTIONS:
# -l  ltrim()
# -r  rtrim()
$MarkupExpr["trim"] = 'MiscTrim($pagename, @$argp, @$args)'; 
function MiscTrim($pagename, $opt, $args)
{
	if (defined('WikiSh')) WikiShCompatible($pagename, $opt, $args);
    if ($opt['l'])
        $rtn = ltrim($args[0]);
    elseif ($opt['r'])
        $rtn = rtrim($args[0]);
    else
        $rtn = trim($args[0]);
	if (defined('WikiSh')) return(wshPostProcess($pagename, $opt, (array)$rtn));
	else return($rtn);
}

# OPTIONS:
#  -f|--file -- do a hash of the file (singular) instead of the string
#     -note that only a single file can be hashed - subsequent args will be 
#     (silently) ignored
#  --raw     -- pass true as the 3rd option to hash()
#  (other WikiSh options like --xargs, --stdout, --encrypt, --decrypt, etc.)
# Arg#1 = name of algorithm (md5, sha1, etc.)
$MarkupExpr["hash"] = 'MiscHash($pagename, @$argp, @$args)'; 
function MiscHash($pagename, $opt, $args)
{
	if (defined('WikiSh')) WikiShCompatible($pagename, $opt, $args);
    $algo = array_shift($args);
    if (@$opt['f'] || @$opt['file']) {
        if (defined('WikiSh')) $page = ShReadPage($pagename, $opt, $arg[0]);
        else $page = RetrieveAuthPage($args[0], 'read', false);
        $val = $page['text'];
    } else {
        $val = implode(" ", $args);
    }
    $rtn = hash($algo, $val, (@$opt['raw']));
	if (defined('WikiSh')) return(wshPostProcess($pagename, $opt, (array)$rtn)); 
	else return($rtn);
}

# {(hash_hmac [OPTIONS] <algorithm> <data>)}
# OPTIONS:
#  -f|--file -- do a hash of the file (singular) instead of the string
#     -note that only a single file can be hashed - subsequent args will be 
#     (silently) ignored
#  --raw     -- pass true as the 3rd option to hash()
#  --key:KEY -- the key (required!)
#  (other WikiSh options like --xargs, --stdout, --encrypt, --decrypt, etc.)
# Arg#1 = name of algorithm (md5, sha1, etc.)
$MarkupExpr["hash_hmac"] = 'MiscHashHmac($pagename, @$argp, @$args)'; 
function MiscHashHmac($pagename, $opt, $args)
{
	if (defined('WikiSh')) WikiShCompatible($pagename, $opt, $args);
    if (!isset($opt['key'])) {
        if (defined('WikiSh')) WikiShStdErr($pagename, $opt, "ERROR: MiscHashHmac: No KEY specified.");
        else echo "ERROR: MiscHashHmac: No KEY specified<br>\n";
        return('');
    }
    $algo = array_shift($args);
    if (@$opt['f'] || @$opt['file']) {
        if (defined('WikiSh')) $page = ShReadPage($pagename, $opt, $arg[0]);
        else $page = RetrieveAuthPage($args[0], 'read', false);
        $val = $page['text'];
    } else {
        $val = implode(" ", $args);
    }
    #echo "hash_hmac: algo=$algo, val=$val, key=$opt[key]<br>\n";
    $rtn = hash_hmac($algo, $val, $opt['key'], (@$opt['raw']));
	if (defined('WikiSh')) return(wshPostProcess($pagename, $opt, (array)$rtn)); 
	else return($rtn);
}

$MarkupExpr["crc32"] = 'MiscCrc32($pagename, @$argp, @$args)'; 
function MiscCrc32($pagename, $opt, $args)
{
	if (defined('WikiSh')) WikiShCompatible($pagename, $opt, $args);
	$rtn = sprintf("%u", crc32(implode(" ", $args)));
	if (defined('WikiSh')) return(wshPostProcess($pagename, $opt, (array)$rtn));
	else return($rtn);
}
$MarkupExpr["base64_encode"] = 'MiscBase64_Encode($pagename, @$argp, @$args)'; 
function MiscBase64_Encode($pagename, $opt, $args)
{
	if (defined('WikiSh')) WikiShCompatible($pagename, $opt, $args);
	$rtn = base64_encode(implode(" ", $args));
    if (defined('WikiSh')) {
        wdbg(3, "Base64_Encode: returning \"$rtn\" via wshPostProcess");
        return(wshPostProcess($pagename, $opt, (array)$rtn)); 
    } else {
        wdbg(3, "Base64_Encode: returning \"$rtn\" directly");
        return($rtn);
    }
}
$MarkupExpr["base64_decode"] = 'MiscBase64_Decode($pagename, @$argp, @$args)'; 
function MiscBase64_Decode($pagename, $opt, $args)
{
	if (defined('WikiSh')) WikiShCompatible($pagename, $opt, $args);
	$rtn = base64_decode(implode(" ", $args));
	if (defined('WikiSh')) return(wshPostProcess($pagename, $opt, (array)$rtn));
	else return($rtn);
}
$MarkupExpr["makepagename"] = 'MiscMakePageName($pagename, @$argp, @$args)'; 
function MiscMakePageName($pagename, $opt, $args)
{
	if (defined('WikiSh')) WikiShCompatible($pagename, $opt, $args);
	$rtn = MakePageName($opt['REFPAGE']?$opt['REFPAGE']:$pagename, implode(" ", $args));
	if (defined('WikiSh')) return(wshPostProcess($pagename, $opt, (array)$rtn));
	else return($rtn);
}

$MarkupExpr["writeptv"] = 'MiscWritePTV($pagename, @$argp, @$args)';
function MiscWritePTV($pagename, $opt, $args)
{
    if (!defined('toolbox')) {
        echo "The MX WritePTV depends on the cookbook toolbox.php which is not installed.  Aborting.<br>\n";
        return(false);
    }
    if (defined('WikiSh')) {
        WikiShCompatible($pagename, $opt, $args);
        # If vars were specified var=${var} then must expand vars in $opt
        foreach ($opt as $k => $v) {
            wshExpandVars($pagename,$opt,$v);
            $opt[$k] = $v;
        }
    }
    if (isset($opt['fmt']))
        $fmt = $opt['fmt'];
    dbg(1, "opt[]=",$opt['']);
    dbg(1, "opt:", $opt);
    dbg(1, "args:", $args);
    if (!$args[0]) {
        # Let's just go away quietly...
        dbg(4, "MiscWritePTV: WARNING: No page specified");
        return(false);
    }
    # Get rid of the [] and the [#] elements...
    $newopt = array_diff_key($opt, array(''=>0, '#'=>0, 'fmt'=>0));
    $newopt = str_replace('\n', "\n", $newopt);
    dbg(1, "newopt:", $newopt);
    if (writeptv($pagename, $args[0], array_keys($newopt), $newopt, $fmt))
        return('');
    else
        return("ERROR: WritePTV Failed");
}