<?php

# PLUGIN PREVIEW BY TEXTPATTERN.INFO


// NOTE

/*
    adi_webhook - Webhooker

    Written by Adi Gilbert

    Released under the GNU General Public License

    Version history:
    0.1        - initial release

    TODO:
    - admin view logfile
    - logfile management

*/

function adi_webhook($atts,$thing=NULL) {
// <txp:adi_webhook /> container tag
    
global $adi_webhook_debug;

    
extract(lAtts(array(
        
'name'        => '',        // (optional) URL var to trigger actions
        
'value'        => '',        // (optional) value of var
        
'method'    => 'post',    // 'post', 'get' or 'post,get'
        
'form'        => '',        // form to use if not in container mode
//         'log'        => 1,        // log file
        
'debug'        => 0,
    ),
$atts));

    
$adi_webhook_debug $debug;

    if (
array_key_exists('value',$atts) === FALSE$value NULL// NULL = "not looking for a match"

    
adi_webhook_log_rotate();
    
adi_webhook_write_log('****************************************');
    
adi_webhook_write_log($atts,'ATTRIBUTES');

    
// log contents of POST and GET
    
adi_webhook_write_log($GLOBALS['_POST'],'POST');
    
adi_webhook_write_log($GLOBALS['_GET'],'GET');

    
// var specified?
    
if ($name != '') {
        
$actual_value adi_webhook_get_var($name,$method,$value);
        if ((
$actual_value === FALSE) || ($actual_value === NULL)) return; // var not found OR value not match
    
}

    
// form or contained tags
    
$form = ($form) ? fetch_form($form) : $thing;

    
// walk the walk
    
return parse($form);
}

function 
adi_webhook_action($atts,$thing=NULL) {
// <txp:adi_webhook_action /> container tag
// effectively the same function as adi_webhook, except
//    - doesn't restart log
//    - doesn't dump POST/GET
//    - URL var is required
//    - uses global debug

    
extract(lAtts(array(
        
'name'        => '',        // (mandatory) URL var to trigger actions
        
'value'        => '',        // (optional) value of var
        
'method'    => 'post',    // 'post', 'get' or 'post,get'
        
'form'        => '',        // form to use if not in container mode
    
),$atts));

    if (
array_key_exists('value',$atts) === FALSE$value NULL// NULL = "not looking for a match"

    
adi_webhook_write_log($atts,'ATTRIBUTES');

    if (
$name == '') return; // must have a url var

    
$actual_value adi_webhook_get_var($name,$method,$value);

    if ((
$actual_value === FALSE) || ($actual_value === NULL)) return; // var not found OR value not match

    // form or contained tags
    
$form = ($form) ? fetch_form($form) : $thing;

    
// talk the talk
    
return parse($form);
}

function 
adi_webhook_variable($atts) {
// <txp:adi_webhook_variable /> tag
// returns value of supplied var

    
extract(lAtts(array(
        
'name'        => '',        // URL var to output
        
'method'    => 'post',    // 'post', 'get' or 'post,get'
    
),$atts));

    
adi_webhook_write_log($atts,'ATTRIBUTES');

    if (
$name == '') return; // must have a url var

    
$value adi_webhook_get_var($name,$method);

    if (
$value === FALSE) return; // var not found

    
adi_webhook_write_log("VAR FOUND $name VALUE=".$value);

    return 
$value;
}

function 
adi_webhook_if_variable($atts$thing=NULL) {
// <txp:adi_webhook_if_variable /> tag
// check if var exists (or var exists & value matches)

    
extract(lAtts(array(
        
'name'        => '',        // URL var to look for
        
'value'        => NULL,    // value of var to test
        
'method'    => 'post',    // 'post', 'get' or 'post,get'
    
),$atts));

    
adi_webhook_write_log($atts,'ATTRIBUTES');

    if (
$name == '') return; // must have a url var

    // do the do
    
if ($value === NULL) { // just check that var exists
        
$value adi_webhook_get_var($name,$method); // FALSE if not found
        
return parse(EvalElse($thing, ($value !== FALSE)));
    }
    else { 
// check that var found & value matches
        
$value adi_webhook_get_var($name,$method,$value); //  FALSE if not found, NULL if not match
        
return parse(EvalElse($thing, (($value !== FALSE) && ($value !== NULL))));
    }
}

function 
adi_webhook_log($atts) {
// <txp:adi_webhook_log /> tag
// write message to log

    
extract(lAtts(array(
        
'msg'        => '',        // the message
    
),$atts));

    
adi_webhook_write_log($msg);
}

function 
adi_webhook_get_var($supplied_var,$method,$value=NULL) {
// returns:    FALSE    - var not found
//            NULL    - value doesn't match
//            value    - var exists (and value matches)

    // methodical
    
$methods do_list($method); // create methods array
    
$methods array_intersect(array('post','get'),$methods); // validate list of methods & enforce 'post' first
    
$methods array_values($methods); // reindex
//     adi_webhook_write_log("** METHODS: ".implode(',',$methods)." **");

    // parse supplied variable name
    
if (strpos($supplied_var,'[') !== FALSE) { // supplied variable is array e.g. "data[merges][EMAIL]"
//         adi_webhook_write_log('*** SUPPLIED '.$supplied_var.' IS ARRAY');
        
preg_match("/(.*?)\[/"$supplied_var$matches);
        
$name $matches[1]; // the array name (e.g. "data")
        
preg_match_all("/\[([^\]]*)\]/"$supplied_var$matches); // the keys (e.g. "merges", "EMAIL")
    
}
    else 
// variable ordinaire
        
$name $supplied_var;

    
// search each method in turn for first occurrence of supplied variable (POST is always first)
    
foreach ($methods as $index => $method) {
        
adi_webhook_write_log("LOOKING FOR $name IN ".strtoupper($method));
        
$this_global $GLOBALS['_'.strtoupper($method)]; // i.e $_POST or $_GET
        // find required variable, & get value
        
if (isset($this_global[$name])) {
//              adi_webhook_write_log("**$method** ".$name.' IS SET');
            
$this_value $this_global[$name];
            if (
is_array($this_value)) {
//                  adi_webhook_write_log("**$method** ".$name.' IS ARRAY');
                
$key_str '';
                foreach (
$matches[1] as $key) {
                    
$key_str .= '['.$key.']';
                    if (isset(
$this_value[$key])) {
//                          adi_webhook_write_log("**$method** "."$name$key_str IS SET");
                        
$this_value $this_value[$key];
                        if (
is_array($this_value)) {
//                              adi_webhook_write_log("**$method** "."$name$key_str IS ARRAY");
                        
}
                        else {
                            
adi_webhook_write_log("VAR $name$key_str VALUE=".$this_value);
                            break;
                        }
                    }
                    else {
                        if (
$index == (count($methods)-1)) { // last method, so give up
                            
adi_webhook_write_log("VAR $name$key_str is NOT set");
                            return 
FALSE;
                        }
                        else
                            continue; 
// try next method
                    
}
                }
            }
            else {
                
adi_webhook_write_log("VAR $name VALUE=".$this_value);
            }
        }
        else {
            if (
$index == (count($methods)-1)) { // last method, so give up
                
adi_webhook_write_log("VAR $name NOT SET");
                return 
FALSE;
            }
            else
                continue; 
// try next method
        
}

        
// need to match a value?
        
if (($value !== NULL)) {
            if (
$this_value != $value) {
                
adi_webhook_write_log('NO MATCH');
                return 
NULL;
            }
            else
                
adi_webhook_write_log('VALUE MATCH');
        }

        return 
$this_value;
    }
}

function 
adi_webhook_write_log($msg,$prefix='?') {
// log message to file (and maybe output as well)
// logfile: TXP_TEMPDIR/adi_webhook.SECTION.DAY_NUM.log
    
global $prefs,$s,$adi_webhook_debug;

    
$logfile $prefs['tempdir'].'/adi_webhook.'.$s.'.'.get_pref('adi_webhook_log').'.log';

    
// get meaningful calling function
    
if (is_callable('debug_backtrace')) {
        
$backtrace debug_backtrace();
        
$function = isset($backtrace[1]['function']) ? $backtrace[1]['function'] : __FUNCTION__;
    }
    else
        
$function __FUNCTION__;

    
// give meaning to the unmeaningful
    
if ($function == "include"$function __FUNCTION__// plugin cache
    
if ($function == "eval"$function __FUNCTION__// plugin installed

    
if (is_array($msg)) // dump array values
        
$msg "$prefix ".print_r($msg,TRUE);

    
// full log entry
    
$log_entry date('Y-m-d H:i:s',time()+tz_offset()).' '.$function.": $msg\n";

    if (
$adi_webhook_debug)
        echo 
$log_entry.($adi_webhook_debug == br ''); // <br/> line break if debug = 2

    
file_put_contents($logfile,$log_entry,FILE_APPEND);
}

function 
adi_webhook_log_rotate() {
// rotate logfiles, if due
// logfile: TXP_TEMPDIR/adi_webhook.SECTION.DAY_NUM.log
    
global $prefs,$s;

    
$today_num date('w'); // today's day number (0 Sunday - 6 Saturday)
    
$current_num get_pref('adi_webhook_log','x'); // current log day number

    // today now tomorrow?
    
if ($today_num != $current_num) {
        
// preference today's log number
        
set_pref('adi_webhook_log',$prefs['adi_webhook_log']=$today_num,'adi_webhook_admin');
        
// delete old today logfile
          
$todays_logfile $prefs['tempdir'].'/adi_webhook.'.$s.'.'.$today_num.'.log';
          @
unlink($todays_logfile);
    }
}