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

  include_once dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'constants.php';

  SecurityOperations::setCookieDomainFromSettings();


abstract class CmsAnb
{
  public static function getAnbindung()
  {
    if (WORDPRESS_CMS_USED) {
      return new WordpressAnb();
    } elseif (TYPO3_CMS_USED) {
      return new Typo3_Anb();
    } else {
      return new NoCmsAnb();
    }
  }

  public static function isCmsUsed()
  {
    return WORDPRESS_CMS_USED || TYPO3_CMS_USED;
  }

  abstract public function rewriteUrl(URLParameterBasis $urlparam): string;

  abstract public function getKuferWebUrl();

  abstract public function includeJs(string $handle, string $cssPath): void;

  abstract public function includeCss(string $handle, string $jsPath): void;

  abstract public function getKursCanonicalLink($knr, $kursname): string;

  
  protected function _start($pMitBuffer = true)
  {
    CodingOperations::encodeEingaben();
    if ($pMitBuffer) {
      ob_start();
    }
  }

  
  protected function _end($pMitBuffer = true, $pStringToConvert = '')
  {
    if ($pMitBuffer) {
      $actString = ob_get_contents();
      ob_end_clean();
    }

    if ($pStringToConvert !== '' || $actString === false) {
      $actString = $pStringToConvert;
    }

    if (!CodingOperations::areInternalAndExternalEncodingEqual()) {
      $actString = $this->encode_utf8_recursive($actString);
    }

    \Kufer\Web\Classes\CronJob\CronJobHandler::handleCronjobInSeparateShell();

    return $actString;
  }

  
  protected function encode_utf8_recursive($pData)
  {
    $out = $pData;
    if (is_array($pData)) {
      foreach ($pData as $k => $v) {
        if (is_array($v) || is_object($v)) {
          $out[$k] = $this->encode_utf8_recursive($v);
        } else {
          $out[$k] = CodingOperations::encodeAnzeige(true, $v);
        }
      }
    } elseif (is_object($pData)) {
      $out = clone $pData;
      foreach ($pData as $k => $v) {
        if (is_array($v) || is_object($v)) {
          $out->{$k} = $this->encode_utf8_recursive($v);
        } else {
          $out->{$k} = CodingOperations::encodeAnzeige(true, $v);
        }
      }
    } else {
      $out = CodingOperations::encodeAnzeige(true, $pData);
    }

    return $out;
  }

  
  public function get()
  {
    ob_start();

    require BASEDIR . 'webbasys' . DIRECTORY_SEPARATOR . 'index.php';
    $content = ob_get_contents();

    ob_end_clean();

    return $content;
  }

  
  public function getSysVar($pVarName, $pConf)
  {
    $this->_start();

    $expCalc = new ExportCalculation();
    $result = $expCalc->getVarValue4System($pVarName);

    return $this->_end(false, $result);
  }

  public function getWarenkorb()
  {
    Hooks::getInstance()->loadPluginHooks();

    
    
    $urlparam = new URLParameterAnmeldungArt();
    if (isset($urlparam->kathaupt) && ($urlparam->kathaupt == 5)
        && isset($urlparam->anmart, $urlparam->schritt)) {
      switch ($urlparam->anmart) {
        case 1:
          if ($urlparam->schritt == 4) {
            return '';
          }
          break;
        default: 
          if ($urlparam->schritt == 5) {
            return '';
          }
          break;
      }
    }

    $this->_start();

    $dbwwarenkorb = new DBWorkWarenkorbKurseWB();
    $urlparam = new URLParameterWarenkorb();

    $rueckFrage = false;
    if (isset($urlparam->askWarenkorb) && $urlparam->askWarenkorb == true) {
      $toolsettings = ToolSettingsAPI::getToolSettings(4);
      if (!(($toolsettings->addKurs2WarenkorbAction == ADDKURS2WARENKORBACTIONEMPTY)
          || $toolsettings->hotel)) {
        $urlparam = new URLParameterWKNachfrage();
        if ($dbwwarenkorb->EntryCount() > 0) {
          $rueckFrage = true;
        }
      }
    }

    
    $encodeRequest = new EncodeCharset4RequestAndResponse();
    $urlparam->knradd = $encodeRequest->encode($urlparam->knradd);
    $urlparam->knrdel = $encodeRequest->encode($urlparam->knrdel);

    

    IndexOperations::interpretWK($urlparam);

    $warenkorb = $dbwwarenkorb->getEntries();

    $dmWarenkorbMenu = new DataMenuBasis(new URLParameterNavigation());

    if (!is_null($warenkorb) && count($warenkorb) > 0) {
      $ary = array();
      foreach ($warenkorb as $wEntry) {
        array_push($ary, $wEntry->kurs);
      }
      $dmWarenkorbMenu->dataarrayheader = array(new Datamodul());
      $dmWarenkorbMenu->dataarraybody = $ary;
      $dmWarenkorbMenu->dataarrayfooter = array(new Datamodul());
      $dmWarenkorbMenu->showsightcomplete(146, new ExpKursuebersicht());
    } else {
      $dmWarenkorbMenu->dataarraynodata = array(new Datamodul());
      $dmWarenkorbMenu->getsight(146);
      $dmWarenkorbMenu->shownodata();
    }

    return $this->_end();
  }

  public function getVerlauf()
  {
    $this->_start(false);


    $datamenu = new DataMenuVerlauf(new URLParameterBasis());

    return $this->_end(false, $datamenu->getContent());
  }

  
  public function doInteressenbekundung($conf)
  {
    $this->_start();
    require $conf['pfad'] . 'webbasys/auth.php';

    return $this->_end();
  }

  
  public function getKalender($conf)
  {
    $this->_start();
    require $conf['pfad'] . 'webbasys/kalender.php';

    return $this->_end();
  }

  
  public function getAsListe($conf)
  {
    $this->_start(false);

    $sight = new DataMenuAussenstellenUebersichtListe(new URLParameterBasis());

    return $this->_end(false, $sight->getContent());
  }

  
  public function getFdSicht($number, $conf)
  {
    $this->_start();

    $this->doTnLoginIfNecessary();
    IndexOperations::interpretML(new URLParameterMerkliste());

    
    $datamenuName = 'DataMenuFreeSight' . $number;
    if (!class_exists($datamenuName)) {
      return $this->_end(true, '<span style="color:#ff0000;">Eine frei definierbare Sicht mit der Nummer "' . $number . '" existiert nicht!</span>');
    }


    $urlparameter = new URLParameterWarenkorb();
    $datamenu = new $datamenuName($urlparameter);
    $datamenu->content();

    return $this->_end();
  }

  
  protected function doTnLoginIfNecessary()
  {
  }

  
  public function getDemnaechst($conf)
  {
    $this->_start();
    require $conf['pfad'] . 'webbasys/demnaechst.php';

    $content = ob_get_contents();
    ob_end_clean();
    

    return $content;
  }

  
  public function getDemnaechstSeparat($conf)
  {
    $this->_start(false);

    $sight = new DataMenuDemnaechstMenueSeparat(new URLParameterBasis());

    return $this->_end(false, $sight->getContent());
  }

  
  public function getEinzelKursCMS($conf)
  {
    $this->_start(false);
    $urlparameter = new URLParameterNavigation();
    $urlparameter->knr = $conf['einzelKursCMS'];
    $einzelKursCMS = new DataMenuDetailsEinzelKursCms($urlparameter);

    return $this->_end(false, $einzelKursCMS->getContent());
  }

  
  public function getKurshighlights($conf)
  {
    $this->_start(false);
    $urlparam = new URLParameterNavigation();

    if (isset($conf['auswahlKategorie'])) {
      
      $parts = explode(':', $conf['auswahlKategorie']);
      if (count($parts) > 1 && is_numeric($parts[1]) && $parts[1] > 0) {
        $urlparam->katid = $parts[1];
      }
    }

    $sight = new DataMenuKursHighlights($urlparam);

    return $this->_end(false, $sight->getContent());
  }

  
  public function getKurshighlightsNachKategorie($conf)
  {
    $this->_start(false);
    $urlparam = new URLParameterNavigation();

    if (isset($conf['auswahlKategorie'])) {
      
      $parts = explode(':', $conf['auswahlKategorie']);
      if (count($parts) > 1 && is_numeric($parts[1]) && $parts[1] > 0) {
        $urlparam->katid = $parts[1];
      }
    }

    $sight = new DataMenuKursHighlightsKategorie($urlparam);

    return $this->_end(false, $sight->getContent());
  }

  
  public function getStartendeKurse($conf)
  {
    $this->_start(false);
    $urlparam = new URLParameterNavigation();

    
    if (isset($conf['auswahlKategorie']) && (!isset($conf['additionalParams']) || $conf['additionalParams'] == '')) {
      
      $parts = explode(':', $conf['auswahlKategorie']);
      if (count($parts) > 1 && is_numeric($parts[1]) && $parts[1] > 0) {
        $urlparam->katid = $parts[1];
      }
    }

    $sight = new DataMenuStartendeKurse($urlparam);

    return $this->_end(false, $sight->getContent());
  }

  
  public function getKuendigung($conf)
  {
    $this->_start(false);

    $sight = \Kufer\Web\Webbasys\Includee\Datamenu\Kuendigung\DataMenuKuendigungFactory::getDataMenu(new URLParameterNavigation());

    return $this->_end(false, $sight->getContent());
  }

  
  public function getSonderkategorienOrHighlights($conf)
  {
    $this->_start(false);
    $urlparam = new URLParameterNavigation();

    if (isset($conf['auswahlKategorie'])) {
      
      $parts = explode(':', $conf['auswahlKategorie']);
      if (count($parts) > 1 && is_numeric($parts[1]) && $parts[1] > 0) {
        $urlparam->katid = $parts[1];
      }
    }

    $sight = \Kufer\Web\Webbasys\Includee\Datamenu\DataMenuKurseSonderkategorieOderHighlights::getDataMenu($urlparam);

    return $this->_end(false, $sight->getContent());
  }

  public function getTnLogin($conf)
  {
    $this->_start(false);

    $sight = new DataMenuLogin(new URLParameterBasis());

    return $this->_end(false, $sight->getContent());
  }

  
  public function validateTnLogin($conf)
  {
    $this->_start(false);

    $loginApi = new LoginApi();
    $loginApi->validateTnLogin();
  }

  public function getWTLogin($conf)
  {
    $this->_start(false);

    $sight = new DataMenuWebToolsLogin(new URLParameterBasis());

    return $this->_end(false, $sight->getContent());
  }

  
  public function getKlickpfad($conf)
  {
    $this->_start();

    IndexOperations::setHistory();

    $kathauptapi = new KathauptAPI();
    $tmpurlparam = new URLParameterNavigation();
    $dm = $kathauptapi->getDatamenuByKathaupt($tmpurlparam->kathaupt, $tmpurlparam);
    $retour = $dm->getClickPath();

    $retour = $this->_end(false, $retour);
    $this->_end();

    return $retour;
  }

  public function getNavMenu($conf)
  {
    $this->_start();


    $kathauptapi = new KathauptAPI();
    $tmpurlparam = new URLParameterNavigation();
    $dm = $kathauptapi->getDatamenuByKathaupt($tmpurlparam->kathaupt, $tmpurlparam);

    $dm->leftmenu();

    return $this->_end();
  }

  public function getRss($conf)
  {
    $this->_start();
    require $conf['pfad'] . 'webbasys/rss.php';

    return $this->_end();
  }

  
  public function getStichworte($conf, $numberTags, $pLinkId = false)
  {
    $this->_start(false);

    require_once $conf['pfad'] . 'classes/db/DBWorkStichwort.php';
    $ary = array();

    $urlparam = new URLParameterSuche();
    $dbw = new DBWorkHLStichwort();
    $stichworte = $dbw->getStichworteHLCloud();


    $linkId = ($pLinkId !== false) ? $pLinkId : GetOperations::getVarValue('id');
    $linkBase = './index.php?id=' . $linkId;

    foreach ($stichworte as $stichwort) {
      
      $stichwort->stichwort = $this->_end(false, $stichwort->stichwort);
      
      $urlparam->kathaupt = 18;
      $urlparam->suchesetzen = 'false';
      $urlparam->implodeSettings();
      $such_teil = '&kfs_stichwort_schlagwort=' . urlencode($stichwort->stichwort);
      $groesse = $stichwort->cloud_groesse == 0 ? 15 : $stichwort->cloud_groesse;

      $item = array();
      $item['title'] = $stichwort->stichwort;
      $item['size'] = $groesse;
      $item['priority'] = $stichwort->cloud_prio;
      if (SEARCHENGINE_FUNCTIONS === true) {
        $item['url'] = SeoApi::rewriteUrlparameter($urlparam->stream);
        $item['url'] .= $such_teil;
        $item['url'] = $linkBase . '&' . str_replace('&amp;', '&', $item['url']);
      } else {
        $item['url'] = $linkBase . '&urlparameter=' . $urlparam->stream;
        $item['url'] .= 'kfs_stichwort_schlagwort%3A' . urlencode($stichwort->stichwort);
      }

      array_push($ary, $item);
    }

    return $ary;
  }

  
  public function kursSearch($pSuchbegriff)
  {
    if (!CodingOperations::areInternalAndExternalEncodingEqual()) {
      $encoding = new EncodeCharset4RequestAndResponse();
      $pSuchbegriff = $encoding->encode($pSuchbegriff);
    }

    $filter = FilterFactory::getFilterClass(false);
    $pSuchbegriff = $filter->filterString('kfs_stichwort', $pSuchbegriff);
    $dbwkurse = new DBWorkKurseINetAktivFilterMinimal();

    $dbwkurse->setOrderByValues(new URLParameterNavigation());

    $dbwkurse->newSearch();

    $dbwkurse->fromobject->stichworte = $pSuchbegriff;
    $dbwkurse->fromobject->stichwortFindetSchlagwort = true;
    $settings = ToolSettingsAPI::getToolSettings(4);
    $dbwkurse->fromobject->semester = $settings->semlist;

    if ($settings->stichwortFindetDozent) {
      $dbwkurse->fromobject->stichwortFindetDoz = true;
    }

    if ($settings->stichwortFindetKategorienbezeichnung) {
      $dbwkurse->fromobject->stichwortFindetKategorienbezeichnung = true;
    }

    $kursids = $dbwkurse->getKursebyCategoryLimit(
      -1,
      new Kurs(),
      9999,
      true
    );

    return WBKursStore::getKurseByIdArray($kursids);
  }

  
  public function kursSearchAndExport($pSuchbegriff, $pTemplate)
  {
    $data = $this->kursSearch($pSuchbegriff);
    if (count($data) === 0) {
      return '';
    } else {
      $export = new ExpKursuebersicht();
      $result = $export->renderTemplate($pTemplate, $data);

      return $this->_end(false, $result);
    }
  }

  
  public function getKategorien($pKatId = 0, $pKatTyp = 1)
  {
    $this->_start(false);


    $dbw = new DBWorkCategories();
    $tool4Settings = ToolSettingsAPI::getToolSettings(4);

    if ($pKatId != 0) {
      $category = $dbw->getCategoryStructured($pKatId, $tool4Settings->showEmptyCategories);

      if (DBWorkBASysSettings::isKornwestheimEbz()) {
        $category->subCategories = $this->filterKategorien4Kornwestheim($category->subCategories);
      }

      return $this->_end(false, $category->subCategories);
    } else {
      return $this->_end(false, $dbw->getCategoriesByTypeStructured($pKatTyp, $tool4Settings->showEmptyCategories));
    }
  }

  
  private function filterKategorien4Kornwestheim($kategorien)
  {
    $stammhoererTnr = SessionOperations::getCurrentStammhoererTnr();
    if (!is_numeric($stammhoererTnr) || $stammhoererTnr <= 0) {
      return array();
    }

    $dbwZsaBkBvTn = new DBWorkZsaBkBvTn(1, true);
    $zielbereichIds = $dbwZsaBkBvTn->getZielbereichIdsByTnrAndTyp($stammhoererTnr, array('TN'));

    return array_filter($kategorien, function($cat) use ($zielbereichIds) {
      return in_array($cat->id, $zielbereichIds);
    });
  }

  
  public function getFeedback($conf)
  {
    if (class_exists('URLParameterFeedBack')) {
      $this->_start();
      $urlparameter = new URLParameterFeedBack();
      if ($urlparameter->kathaupt == '') {
        $kathaupt = 822;
      } else {
        $kathaupt = $urlparameter->kathaupt;
      }
      switch ($kathaupt) {
        default:
          return false;
        case 821:
          $dm = DataMenuFeedBackFactory::getDataMenuFeedBackFormular($urlparameter);
          break;
        case 822:
          $dm = new DataMenuFeedBackCode($urlparameter);
          break;
        case 823:
          $dm = new DatamenuFeedbackFrageBogen($urlparameter);
          break;
      }
      $dm->content();

      return $this->_end();
    } else {
      return '';
    }
  }

  public function getKurshighlightsSlider($conf)
  {
    $this->_start(false);

    
    $sight = new DataMenuKursHighlightsSlider(new URLParameterBasis(), $conf['selectWeighting']);

    return $this->_end(false, $sight->getContent());
  }

  public function getKursTeaser($conf)
  {
    $this->_start(false);

    
    $knr = isset($conf['courseNumber']) ? $conf['courseNumber'] : $conf['einzelKursCMS'];
    $sight = new DataMenuKursTeaser(new URLParameterBasis(), $knr);

    return $this->_end(false, $sight->getContent());
  }

  public function isFrontendUserLoggedIn()
  {
    return false;
  }

  public function init()
  {
  }

  public function exit()
  {
  }
}