<?php 
/**
 * @package plugin
 * @copyright (c) Kufer Software Konzeption, Loisachstrasse 4, D-84453 Mühldorf
 */

/**
 * Beispiel für ein Markerinclude
 * Müsste mit diesem Namen im Ordner kuferweb/plugins/xy/ liegen
 * $pfad ist der Pfad zum Template, falls es sich um eine lokale Datei / Kopie handelt, muss $local auf true gesetzt werden
 * Die Funktion replaceRelativeLinks() muss oft an die individuellen Gegebenheiten des Templates angepasst werden, damit die 
 * Pfade zu den unterschiedlichen externen Ressourcen korrekt angepasst werden.

 */


class WbPluginmimarbachhul extends WbPluginBasis {
    function getContent($pUrlParam) {
        return 'Diese Nutzung ist in diesem Plugin nicht vorgesehen';
    }

    /**
     * @var string Pfad zum Template
     */
    //private $pfad = 'https://hul.landwirtschaft-bw.de/pb/,Lde/Startseite/Seminarverwaltung';
    private $pfad = 'https://fortbildung-hul.lgl-bw.de/hul/webbasys/layout/marker.html';
    
    /**
     * @var bool Ist bei lokalen Templates auf true zu setzen
     */
    //private $local = false;
    private $local = false;

    /**
     * @var string Manche Kunden schützen das Template gegen automatisierten Downloads durch Bots - hier kann ein eigener Useragent helfen
     */
    private $useragent = 'KuferWEB MarkerInclude';

    /**
     * @var string Host, auf den die relativen Links und Actions zeigen
     */
    private $host = 'https://hul.landwirtschaft-bw.de/';
    /**
     * @var string Host, auf dem die Medien (Bilder, ...) zu finden sind, wohl meist gleich $host
     */
    private $medienhost = 'https://hul.landwirtschaft-bw.de/';


    private $marker1 = '<link rel="stylesheet"';
    private $marker2 = '</head>';
	private $kuferMarker = '<p>##KurseMarbach</p>';
    private $marker4 = '</body>';

    private $fileContent;

    public function __construct($pSettingsDir = false,$pPluginName = false) {
        parent::__construct($pSettingsDir, $pPluginName);
        //$this->pfad = dirname(__FILE__).'/../../webbasys/layout/marker.html';//Der Server beim LGL scheint mit dem BASEDIR oben ein Problem zu haben.
    }

    private function replaceRelativeLinks($pString) {
        $result = $pString;
        //$result = str_replace('href="/', 'href="'.CleanOperations::cleanStringForHtml($this->medienhost), $result);
		                       
        //$result = str_replace('<base href="https://www.landwirtschaft-bw.info/pb/site/pbs-bw-new/resourceCached/233/templates/base.txt" />', '', $result);
		
        $result = str_replace('href="/', 'href="'.$this->medienhost, $result);
        $result = str_replace('src="/', 'SRCVAR1', $result);
        $result = str_replace('src="http://', 'SRCVAR2', $result);
        $result = str_replace('src="https://', 'SRCVAR3', $result);
        $result = str_replace('src="', 'src="'.$this->host, $result);
        $result = str_replace('SRCVAR1', 'src="'.$this->medienhost, $result);
        $result = str_replace('SRCVAR2', 'src="http://', $result);
        $result = str_replace('SRCVAR3', 'src="https://', $result);
		
        $result = str_replace('href="//', 'hrefPROT', $result);
        $result = str_replace('href="http://', 'hrefPRO2', $result);
        $result = str_replace('href="https://', 'hrefPRO3', $result);
        $result = str_replace('href="&', 'hrefPRO4', $result);
        $result = str_replace('href="', 'href="'.$this->host, $result);
        $result = str_replace('hrefPROT', 'href="//', $result);
        $result = str_replace('hrefPRO2', 'href="http://', $result);
        $result = str_replace('hrefPRO3', 'href="https://', $result);
        $result = str_replace('hrefPRO4', 'href="&', $result);

        return $result;
    }

    /**
     * @param string $pVarname
     * @param array(string) $pParams
     * @return string
     */
    function getVarValue($pVarname, $pParams, $pDatamodul = null) {

        //für Verallgemeinerung: Syntax: {%plugin_<Pluginname>_<Variablenname>;[:Parameter1,Parameter2]%}
        //Andere Variablen wohl mit %%..%%

        $kuferMarker = $this->kuferMarker;

        $this->fileContent = $this->getFileContent();

        switch ($pVarname) {
            //Zu Debugging Zwecken: wird überhaupt was (sinnvolles) gefunden
            case 'fc':
                //echo $this->replaceRelativeLinks($fileContent);
                return $this->fileContent;
            case 'partcss':
            case 'part1':
                //Start bis zur ersten CSS Datei
                $posFirstCss = \StringOperations::stripos($this->fileContent, $this->marker1);
                if ($posFirstCss === false) {
                    return 'Fehler: Änderung in der HTML Struktur (PreCSS)';
                } else {
                    $result = substr($this->fileContent, 0, $posFirstCss);
                }
                return $result;
            case 'parthead':
            case 'part2':
                //erste CSS Datei bis unmittelbar vor </head>
                $result = $this->getSection($this->marker1, $this->marker2, 'Link Stylesheet', 'schließendes Head Tag');
                return $result;

            case 'partmarker':
            case 'part3':
                //</head> bis KuferMarker
                $result = $this->getSection($this->marker2, $this->kuferMarker, 'Head', 'KuferMarker');
                return $result;

            case 'partbody':
            case 'part4':
                //KuferMarker bis vor </body>
                $result = $this->getSection($this->kuferMarker, $this->marker4, 'KuferMarker', 'Body', true);
                return $result;

            case 'partende':
            case 'part5':
                //hinter Body
                $posBodyEnd = strpos($this->fileContent, $this->marker4);
                if ($posBodyEnd === false) {
                    return 'Fehler: Änderung in der HTML Struktur (Body)';
                }
                $result = substr($this->fileContent, $posBodyEnd);
                return $result;
        }
        return '';
    }

    private function getFileContent() {
        static $fileContent = null;
        if (is_null($fileContent)) {
            $data = '';
            if (!$this->local //&& CURL_USE
            ) {
                if (!function_exists('curl_init'))  {
                  die('CURL ist auf diesem Web-Server nicht installiert!');
                }
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

                if ($this->useragent != '') {
                   curl_setopt($ch, CURLOPT_USERAGENT, $this->useragent);
                }

                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                if (CURL_PROXYSERVER != '') curl_setopt($ch, CURLOPT_PROXY, CURL_PROXYSERVER);
                curl_setopt($ch, CURLOPT_URL, $this->pfad);
                $data = curl_exec($ch);
                curl_close($ch);
            } else {
                $data = file_get_contents($this->pfad);
            }


            $fileContent = \StringOperations::utf8_decode($data);
			if ($fileContent[0] === '?') {
			  $fileContent = substr($fileContent, 1);//erstes Zeichen wegschneiden, von irgendwoher kommt da ein "?"
			}
			$fileContent = $this->replaceRelativeLinks($fileContent);
            //$fileContent = $data;//Test wegen der fehlenden Icons
        }
        return $fileContent;
    }

    /**
     * Liefert den Inhalt zwischen $pStart und $pEnd
     */
    private function getSection($pStart, $pEnd, $pBemStart = '', $pBemEnd = '', $pOhneStart = false) {
        if ($pStart === '') {
            $posStart = 0;
        }
        else {
            $posStart = \StringOperations::stripos($this->fileContent, $pStart);
            if ($posStart === false) {
                return 'Fehler: Änderung in der HTML Struktur'.($pBemStart !== ''?" ($pBemStart)":'');
            }
            if ($pOhneStart) {
                $posStart += \StringOperations::strlen($pStart);
            }
        }
        $posEnd = \StringOperations::strpos($this->fileContent, $pEnd);
        if ($posEnd === false) {
            return 'Fehler: Änderung in der HTML Struktur'.($pBemEnd !== ''?" ($pBemEnd)":'');
        }
        $result = \StringOperations::substr($this->fileContent, $posStart, $posEnd - $posStart);
        return $result;
    }
}
?>
