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


class Exportadapter
{
  
  public $export;

  
  public $varlist;

  
  public $resultlist;
  
  public $filestream = '';

  
  public $assoc = false;

  
  public function __construct($pAssoc = false)
  {
    $this->assoc = $pAssoc;
    $this->initiate();
    if (isset($this->export)) {
      $this->export->assoc = $pAssoc;
    }
  }

  
  public function initiate()
  {
  }

  
  public function initiateResultlist()
  {
    $this->resultlist = array();
  }

  
  public function initiateVarList()
  {
    $this->varlist = array();
  }

  
  public function getVarNames($inputstr)
  {
    $this->initiateVarList();
    $this->varlist = $this->returnVarNames($inputstr);
  }

  
  public function returnVarNames($inputstr)
  {
    $ary = array();
    $endpos = 0;
    do {
      $startpos = StringOperations::strpos($inputstr, '{%', $endpos);
      if ($startpos !== false && $startpos >= $endpos) {
        $endpos = StringOperations::strpos($inputstr, '%}', $startpos + 2);
        $varname = StringOperations::substr($inputstr, $startpos + 2, $endpos - ($startpos + 2));
        if (!$this->varInArray($varname, $ary)) { 
          array_push($ary, $varname);
        }
        $endpos += 2;
      } else {
        $endpos = false;
      }
    } while ($endpos);

    return $ary;
  }

  
  public function varInArray($pVarname, $pAry)
  {
    if (static::permanentVarUpdate($pVarname)) {
      return false;
    } else {
      return in_array($pVarname, $pAry);
    }
  }

  
  public function fillVars($str, $index = '')
  {
    return $this->fillVarsByVariableList($str, $this->varlist);
  }

  
  public static function sollVariableHtmlEncodedWerden($varname)
  {
    
    if (! (defined('ISKUFERTOOLS_RESPONSIVE') && ISKUFERTOOLS_RESPONSIVE)) {
      return false;
    }

    switch ($varname) {
      default: return true;
      case 'js_files':
      case 'js_declarations':
      case 'k_jsdeclarations':
      case 'css_filescss':
      case 'view_buttons':
        
        
      case 'column_label':
      case 'column_trimmed_label':
      case 'column_feld':
      case 'column_wert':
      case 'column_old_feld':
      case 'column_old_wert':
      case 'columndiff_old_feld':
      case 'columndiff_old_wert':
      case 'view_blaettern':
      case 'page_blaettern':
      case 'news_optionen_benutzergruppen':
      case 'news_optionen_fachbereiche':
      case 'filter_kategorieOptionen':
      case 'filter_sonderKategorieOptionen':
      case 'filter_aussenstellenOptionen':
      case 'filter_gebaeudeOptionen':
      case 'filter_kursOrteOptionen':
      case 'filter_fachbereicheOptionen':
      case 'filter_kennzeichenOptionen':
      case 'filter_nichtKennzeichenOptionen':
      case 'filter_semesterOptionen':
      case 'filter_zielgruppenOptionen':
      case 'filter_bezirkOptionen':
      case 'filter_einsatzbezirkOptionen':
      case 'filter_gemeindeOptionen':
      case 'filter_veranstalterBezirkOptionen':
      case 'filter_veranstalterGemeindeOptionen':
      case 'filter_branchenOptionen':
      case 'filter_faecherOptionen':
      case 'filter_mitarbeiterKennungOptionen':
      case 'filter_kursauswahl1Optionen':
      case 'filter_kursauswahl2Optionen':
      case 'filter_kursauswahl3Optionen':
      case 'filter_kursauswahl4Optionen':
      case 'filter_kursauswahl5Optionen':
      case 'filter_kursauswahl6Optionen':
      case 'filter_kursauswahl7Optionen':
      case 'filter_kursauswahl8Optionen':
      case 'filter_kursauswahl9Optionen':
      case 'filter_kursauswahl10Optionen':
      case 'filter_kursauswahl11Optionen':
      case 'filter_kursauswahl12Optionen':
      case 'filter_kursauswahl13Optionen':
      case 'filter_kursauswahl14Optionen':
      case 'filter_kursauswahl15Optionen':
      case 'filter_kursauswahl16Optionen':
      case 'filter_dsOptionen':
      case 'filter_zbOptionen':
      case 'filter_statusOptionen':
      case 'pw_meldung':
      case 'pw_status':
      case 'news_inhalt':
      case 'news_titel':
      case 'persDaten_freeField':
      case 'upload_status_erfolg':
      case 'upload_status_fehler':
      case 'k_status_erfolg':
      case 'k_status_fehler':
      case 'k_status_warnung':
      case 'k_status_info':
      case 'persDaten_status_erfolg':
      case 'persDaten_status_fehler':
      case 'persDaten_status_info':
      case 'kt_status_erfolg':
      case 'kt_status_fehler':
      case 'kt_kursAnpassenDialog':
      case 'k_kursAnpassenDialog':
      case 'kt_informiereTnDialog':
      case 'menu_text':
        
      case 'ls_stammblattEinstellungen':
      case 'ls_lehrplanEinstellungen':
      case 'ls_lehrplantabelleEinstellungen':
        
      case 'ls_zeitpunkte_output':
        
      case 'ls_zeitspanne_options':
        
      case 'ls_kwMonat_options':
      case 'ls_auswahl_checked':
      case 'ls_auswahl_input_enabled':
        
      case 'ls_druckbereich_format_disabled':
      case 'ls_druckbereich_format_checked':
      case 'ls_kurstage_disabled':
      case 'ls_zahljahr_disabled':
        
      case 'ls_einstelloption_checked':
      case 'ls_einstelloption_enabled':
        
      case 'ls_tndarstellung_checked':
      case 'ls_spanordnung_checked':
      case 'ls_kopfbereich_checked':
      case 'ls_bemerkung_checked':
      case 'ls_showfusszeile_checked':
      case 'ls_druckbereich_auffuellen_checked':
      case 'ls_druckbereich_auffuellart_checked':
      case 'ls_umfang_checked':
      case 'ls_sortierung_checked':
      case 'ls_fusszeilenbold_checked':
      case 'liste_headerTitle':
      case 'liste_bezeichnung':
      case 'liste_infoText':
      case 'liste_infoTextTitel':
        
      case 'hon_vertragstext':
      case 'kt_kursort_hinterlegung':
      case 'loginAnf_status':
      case 'loginAnf_hinweis':
      case 'ls_spanordnung_disabled':
      case 'ls_tndarstellung_disabled':
      case 'ls_kopfbereich_disabled':
      case 'ls_bemerkung_disabled':
      case 'ls_showfusszeile_disabled':
      case 'ls_druckbereich_auffuellen_disabled':
      case 'ls_druckbereich_auffuellart_disabled':
      case 'ls_druckformat_hidden':
      case 'ls_uhrzeitHlButton':
      case 'kursplanung_status_fehler':
      case 'kursplanung_status_erfolg':
      case 'kursplanung_text_pflichtfeld_checkbox':
      case 'verh_dozSelectOptions':
      case 'verh_verhaltenSelectOptions':
      case 'view_reiter':
      case 'anw_feedback_link':
      case 'anw_warning_message':
      case 'anw_extra':
      case 'k_buttons':
      case 'k_reiterButtons':
      case 'kort_reiterButtons':
      case 't_reiterButtons':
      case 'doz_reiterButtons':
      case 'adr_reiterButtons':
      case 'kurs_info':
      case 'news_buttons':
      case 'panel_buttons':
      case 'page_buttons':
      case 'panel_body':
      case 'panel_title':
      case 'stdplan_wochen':
      case 'stdplan_kalenderJahr':
      case 'stdplan_schablonen':
      case 'page_fehlermeldung':
      case 'doz_fachbereichliste':

        
      case 'tnanmeld_categoryList':
      case 'tnanmeld_aussenstellen':
        
      case 'anmelde_Kursdata':
      case 'anmelde_kurse':
      case 'anmelde_weitereTN':
      case 'button_title':
      case 'b_faecher':
      case 'historiekrit_label':
      case 'historiekrit_feld':
      case 'k_hlbemerkungRows':
      case 'k_anmeldeartOptions':
      case 'mehrfach_geschlechtAuswahl':
      case 'k_nachlassHlButton':
      case 'k_beginn_dat_wotagkurz':
      case 'k_ende_dat_wotagkurz':

      case 'anmeld_msgSuccess':
      case 'anmeld_msgInfo':
      case 'anmeld_msgFehler':
      case 'anmeld_newTnMsgSuccess':
      case 'anmeld_newTnMsgInfo':
      case 'anmeld_newTnMsgFehler':
      case 't_newTnMsgSuccess':
      case 't_newTnMsgInfo':
      case 't_newTnMsgFehler':
      case 'tninfo_statusMsg':
      case 'tninfo_statusMsgInfo':
      case 'tninfo_statusMsgFehler':
      case 'doz_newDozMsgSuccess':
      case 'doz_newDozMsgInfo':
      case 'doz_newDozMsgFehler':
      case 'hon_dozTypButtonScript':
      case 'hon_benutzerButtonScript':
      case 'kt_uhrzeitHlButtonBeg':
      case 'kt_uhrzeitHlButtonEnd':
      case 'kt_kursorteHlButton':
      case 'kt_ausfallOptions':
      case 'kt_dozentenOptions':
      case 'k_linkZuKursdetails':
      case 'kt_linkZuKursdetails':
      case 'k_statusMsg':
      case 'terminplan_auswahl_monat':
      case 'terminplan_auswahl_jahr':
      case 'terminplan_auswahl_quartal':
      case 'b_prio_select':
      case 'k_tnListeScript':
      case 'b_data4StornoScript':
      case 'anmeld_jsData':
      case 'pktzert_message_success':
      case 'pktzert_message_error':
      case 'page_freitext':
      case 'raumrs_ansprechOptions':
      case 'raumrs_raumOptions':
        
      case 'noten_hinweisMsg':
      case 'bkbvtn_tnzbzg_optionen':
      case 'button_no_collapse_buttons':
      case 'feedbackfrage_bemerkung':
      case 'anmelde_dseCheckbox':
      case 'anmelde_dseCheckboxAkzeptiert':
      case 'anmelde_dseAufforderung':
      case 'akt_inhalt':
      case 'k_hl_button_einnahmen_ausgaben_posten':
      case 'portrait_status_erfolgreich':
      case 'portrait_status_info':
      case 'portrait_status_fehler':
      case 'k_bemerkung':
      case 'onlineKontoBeantr_status':
      case 'k_material':
      case 'dialog_jahr_optionen':
      case 'kt_hlIlUnitDialogJs':
      case 'kt_hlIlStufeDialogJs':
      case 'kt_hlIlKeypointDialogJs':
      case 'kt_hlLwHausarbeitDialogJs':
      case 'sys_kufertools_statusmeldungen':
      case 'status_message':
      case 'k_dozentenOptionen':
      case 'k_hinterlegungUhrzeitenMitPause':
      case 'k_hinterlegungBestuhlung':
      case 'kt_statusRaum':
      case 'k_weitereteilnehmerliste_mail':
      case (\preg_match('/^([a-z]+_)?emailInfoStatusHtml/i', $varname) === 1):
      case (\preg_match('/^([a-z]+_)?emailWarningStatusHtml/i', $varname) === 1):
      case (\preg_match('/^([a-z]+_)?emailErrorStatusHtml/i', $varname) === 1):
      case (preg_match('/^tbest_.*/i', $varname) === 1):
      case 'feedback_anzeigeText':
      case 'feedback_unter_ueberschrift':
      case 'feedback_frageBezeichnung':
      case 'feedback_bogenAnzeigeText':
      case 'feedback_fragenAnzeigeText':
      case 'feedback_bemerkungsLabelText':
      case 'entry_sperrzeit_kollisionen_html':
      case 'htmlRaumGrafik':
      case 'htmllegende':
      case 'urlaubsplanung_hlgrund':
      case 'li_add_to_login_link':
      case 'loginAnf_textFreiesPflichtfeldHTML':
      case 'sys_captcha_kufertools':
        return false;
    }
  }

  
  public static function sollVariableHtmlPurifiedWerden($varname)
  {
    if (! (defined('ISKUFERTOOLS_RESPONSIVE') && ISKUFERTOOLS_RESPONSIVE)) {
      return false;
    }

    switch ($varname) {
      default:
        $tool0Settings = ToolSettingsAPI::getToolSettings(0);
        if ($tool0Settings->filterAllHtmlFields) {
          return static::istOptionalPurifiedVariable($varname);
        } else {
          return false;
        }
        
      case 'news_inhalt':
      case 'news_titel':
      case 'persDaten_freeField':
      case 'k_status_erfolg':
      case 'k_status_fehler':
      case 'k_status_warnung':
      case 'k_status_info':
      case 'persDaten_status_erfolg':
      case 'persDaten_status_fehler':
      case 'persDaten_status_info':
      case 'kt_status_erfolg':
      case 'kt_status_fehler':
      case 'panel_body':
      case 'feedbackfrage_bemerkung':
      case 'k_bemerkung':
      case 'k_material':
      case 'sys_kufertools_statusmeldungen':
      case 'status_message':
      case 'panel_title':
      case 'k_weitereteilnehmerliste_mail':
      case (preg_match('/^tbest_.*/i', $varname) === 1):
      case 'feedback_anzeigeText':
      case 'feedback_unter_ueberschrift':
      case 'feedback_frageBezeichnung':
      case 'feedback_bogenAnzeigeText':
      case 'feedback_fragenAnzeigeText':
      case 'feedback_bemerkungsLabelText':
        return true;
    }
  }

  public static function istOptionalPurifiedVariable($varname)
  {
    switch ($varname) {
      default: return false;
      case 'kurs_info': return true;
    }
  }

  private function stripParam($variable)
  {
    $positionDoppelpunkt = StringOperations::strpos($variable, ':');
    if ($positionDoppelpunkt === false) {
      return $variable;
    } else {
      return StringOperations::substr($variable, 0, $positionDoppelpunkt);
    }
  }

  
  public function fillVarsByVariableList($str, $pVars)
  {
    $nonPermanentVars = array();
    for ($i = 0; $i < count($pVars); $i++) {
      $var = $pVars[$i];
      $value = $this->export->getVarValue($var);

      $varnameMitDatamodul = $this->stripParam($var);
      if (static::sollVariableHtmlEncodedWerden($varnameMitDatamodul)) {
        $value = CleanOperations::cleanStringForHtml($value);
      } elseif (static::sollVariableHtmlPurifiedWerden($varnameMitDatamodul)) {
        $value = CleanOperations::cleanStringContainingHtml($value);
      }

      if (static::permanentVarUpdate($var)) {
        $str = $this->replaceVar($var, $value, $str);
      } else {
        $nonPermanentVars['{%' . $var . '%}'] = $value;
      }
    }

    return \StringOperations::str_fast_parallel_replace($str, $nonPermanentVars);
  }

  
  protected function replaceVar($var, $value, $str)
  {
    if (!static::permanentVarUpdate($var)) {
      
      $str = str_replace(
        '{%' . $var . '%}',               
        $value, 
        $str                                    
      );
    } else {
      
      $str = substr_replace(
        $str,                                   
        $value, 
        strpos($str, '{%' . $var . '%}'), 
        strlen('{%' . $var . '%}')        
      );                                        
    }

    return $str;
  }

  
  public static function permanentVarUpdate($pVarname)
  {
    switch ($pVarname) {
      case 'sys_alternate': return true;
      default: return false;
    }
  }

  
  public function parseScripts($parsetext)
  {
    $str = $parsetext;

    
    
    
    
    $str = preg_replace(
      '&{§IF§}\\s*{§VALUE1§}\\s*?(.*)\\s*?{/§VALUE1§}\\s*{§EQUAL§}(.*){/§EQUAL§}\\s*{§VALUE2§}\\s*?(.*)\\s*?{/§VALUE2§}\\s*{§THEN§}(.*){/§THEN§}\\s*{§ELSE§}(.*){/§ELSE§}\\s*{§END§}&sU',
      '(§IF§)("$1" $2 "$3") {$4} else {$5}',
      $str
    );

    $str = preg_replace(
      '&{§DISPLAY§}\\s*?(.*)\\s*?{/§DISPLAY§}&sU',
      '(§IF§)("$1" == "") { style="display: none;"} else {}',
      $str
    );

    

    if (StringOperations::stripos($str, '(§foreach') !== false) {
      $str = $this->compileForeachTag($str);
    }



    
    
    
    
    
    

    static $cache = array();
    if (!isset($cache[$str])) {
      $scanner = new EasyHtmlScript2($str);
      $cache[$str] = $scanner->scan();
    }
    $str = $cache[$str]->getContent($this);

    return $str;
  }

  
  public function parseScriptsForDatamodulArray($parsetext, $datamodulArray)
  {
    $this->export->initiate();
    $this->export->exportresults = $datamodulArray;
    $this->export->actualset = 0;

    return $this->parseScripts($parsetext);
  }

  private function compileForeachTag($pString)
  {
    $data = get_object_vars($this->export->exportresults[$this->export->actualset]);
    $engine = new ForeachTemplateEngine($data);

    return $engine->process($pString);
  }

  
  public function replaceVarNames()
  {
    if ($this->assoc) {
      
      
      $this->replaceVarNamesAssoc();
    } else {
      $this->initiateResultlist();
      for ($i = 0; $i < $this->export->resultCount(); $i++) {
        if ($this->export->selectResultSet($i)) {
          
          $parsedStream = $this->parseScripts($this->filestream);
          
          
          $this->getVarNames($parsedStream);
          
          array_push($this->resultlist, $this->fillVars($parsedStream));
          
        }
      }
    }
  }

  public function replaceVarNamesAssoc()
  {
    $this->initiateResultlist();

    $exportResults = $this->export->exportresults;
    foreach ($exportResults as $key => $result) {
      if ($this->export->selectResultSet($key)) {
        
        $parsedStream = $this->parseScripts($this->filestream);
        
        
        $this->getVarNames($parsedStream);
        
        array_push($this->resultlist, $this->fillVars($parsedStream));
        
      }
    }
  }

  
  public function setSightInfo($pName, $pValue)
  {
    
    $this->export->setSightInfo($pName, $pValue);
  }

  
  public function addSightInfo($pName, $pValue)
  {
    $this->export->addSightInfo($pName, $pValue);
  }

  
  public function getSightInfo($pName)
  {
    
    return $this->export->getSightInfo($pName);
  }

  
  public function renderTemplate($pTemplate, $pData, $pGlue = "\n")
  {
    $this->export->initiate();
    $this->export->exportresults = $pData;
    $this->export->setNrOfMainBodyElements(count($pData));
    $this->filestream = $pTemplate;
    $this->replaceVarNames();
    if (count($this->resultlist) > 0) {
      return implode($pGlue, $this->resultlist);
    } else {
      return '';
    }
  }

  
  public function setBlaetternInfo($pBlInfo)
  {
    $this->export->setBlaetternInfo($pBlInfo);
  }
}