<?php
// This file tells DokuWiki that this plugin has a helper module
// It's optional in modern DW versions but still recommended
define('BEGIN_REPLACE_DELIMITER', '@');
define('END_REPLACE_DELIMITER', '@');

class helper_plugin_yatp extends DokuWiki_Plugin
{
    function getTemplateFile($name) {
        return (substr($name, 0, 1) == ":") || ($this->getConf('namespace') == '') ? substr($name, 1) : $this->getConf('namespace') . ":" . $name;
    }

    function getTemplate($pageName) {
		/**
		 * by default, a page from namespace specified in $conf['namespace'] will be loaded
		 * To override this, prepend a colon to $name
		**/
		$template = rawWiki($pageName);
        if (!$template) return false;
		$template = preg_replace('/<noinclude>.*?<\/noinclude>/s', '', $template);
		$template = preg_replace('/<includeonly>|<\/includeonly>/', '', $template);
		return $template;
	}

    /**
     * Handles the replacement array
     */
    function messageReplacers($replacers) {
        $r = [];
        if (is_null($replacers)) {
            $r['keys'] = null;
            $r['vals'] = null;
        } else if (is_string($replacers)) {
            if ( str_contains($replacers, '=') && (substr(trim($replacers), -1) != '=') ){
                list($k, $v) = explode('=', $replacers, 2);
                $r['keys'] = BEGIN_REPLACE_DELIMITER.trim($k).END_REPLACE_DELIMITER;
                $r['vals'] = trim(str_replace('\|', '|', $v));
            }
        } else if (is_array($replacers) ) {
            foreach($replacers as $rep) {
                if (str_contains($rep, '=') && (substr(trim($rep), -1) != '=') ){
                    list($k, $v) = explode('=', $rep, 2);
                    $r['keys'][] = BEGIN_REPLACE_DELIMITER.trim($k).END_REPLACE_DELIMITER;
                    if (trim($v)[0] == '"' and trim($v)[-1] == '"') {
                        $r['vals'][] = substr(trim(str_replace('\|','|',$v)), 1, -1);
                    } else {
                        $r['vals'][] = trim(str_replace('\|','|',$v));
                    }
                }
            }
        } else {
            // This is an assertion failure. We should NEVER get here.
            //die("FATAL ERROR!  Unknown type passed to syntax_plugin_yatp_template::massageReplaceMentArray() can't message syntax_plugin_yatp_template::\$replacers!  Type is:".gettype($r)." Value is:".$r);
            $r['keys'] = null;
            $r['vals'] = null;
        }
        return $r;
    }
}