<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

class ContentSettings extends Content
{
  
  protected $settingConverter;
  protected $action;
  protected $configFile;

  public function __construct($pConfigFile = '')
  {
    $this->configFile = $pConfigFile;

    if ($pConfigFile == '') {
      $files = $this->settingConverter->getConfigFiles();
      if (count($files) > 0) {
        $this->configFile = $files[0]->fileName;
      }
    }
  }

  public function getContent()
  {
    SessionOperations::setVarValueIntern('messages', array());

    if (isset($_POST['savesettings'])) {
      $this->saveSettings();
    } elseif (isset($_POST['kopiesql'])) {
      $this->getsettingsFromSQL();
    }

    
    $smarty = $this->getSmarty();
    $fileName = $this->configFile;

    $multipart = false;

    $smarty->assign('groupname', $fileName);

    
    $sc = $this->settingConverter;
    $subGroupNames = $sc->getGroups($fileName);

    
    if (!defined('ADMIN_SHOW_PAGE')) {
      define('ADMIN_SHOW_PAGE', true);
    }

    $subGroups = array();
    $x = 0;
    foreach ($subGroupNames['subGroup'] as $name) {
      $arySubGroup = array();
      $arySettings = array();

      $subGroupSettings = $sc->getSettingsForGroup($fileName, $name);
      for ($i = 0; $i < count($subGroupSettings); $i++) {
        if (isset($subGroupSettings[$i]->additionalContent)) {
          $page = $subGroupSettings[$i]->additionalContent;
          $additionalContent = $page->getPage();
        } else {
          $additionalContent = '';
        }
        if ($subGroupSettings[$i]->config->requiresMultipart) {
          $multipart = true;
        }
        array_push($arySettings, array(
          'description' => $subGroupSettings[$i]->description,
          'descriptionWithColonMark' => $subGroupSettings[$i]->config->descriptionWithColonMark,
          'descriptionBeforeInput' => $subGroupSettings[$i]->descriptionBeforeInput,
          'beforeinput' => $subGroupSettings[$i]->beforeInput,
          'afterinput' => $subGroupSettings[$i]->afterInput,
          'additionalcontent' => $additionalContent,
          'input' => ($subGroupSettings[$i]->name == 'kopieKuferSQL') ? '' : $sc->getInput($subGroupSettings[$i]),
          'inputname' => StringOperations::strtolower((is_array($subGroupSettings[$i]->name)) ? implode(',', $subGroupSettings[$i]->name) : $subGroupSettings[$i]->name),
          'typename' => $subGroupSettings[$i]->config->typeName,
          'help' => $subGroupSettings[$i]->help,
          'classname' => $subGroupSettings[$i]->className,
          
          
          'allowNegative' => $subGroupSettings[$i]->config->allowNegative
        ));
      }

      $arySubGroup['subgroupname'] = $name;
      $arySubGroup['savebuttontitle'] = $subGroupNames['saveButtonTitle'][$x];
      $arySubGroup['hidesavebutton'] = $subGroupNames['hideSaveButton'][$x] ?? false;

      if (StringOperations::strlen($name) > 35) {
        $abbr = '';
        $str = explode(' ', $name);
        $len = count($str);
        for ($i = 0; $i < $len; $i ++) {
          $subtxt = StringOperations::strlen($str[$i]);
          $txt = StringOperations::strlen($abbr);

          if ($txt + $subtxt < 35) {
            $abbr .= $str[$i] .= '';
          } else {
            break;
          }
        }
        
        $arySubGroup['subgroupid'] = StringOperations::removeUmlaute($abbr);
      } else {
        $subGroupID = StringOperations::removeUmlaute($name);
        $arySubGroup['subgroupid'] = preg_replace('/[^a-z]*[^a-z0-9]+/', '', StringOperations::strtolower($subGroupID));
      }
      $arySubGroup['items'] = $arySettings;
      array_push($subGroups, $arySubGroup);

      $x++;
    }

    
    $smarty->assign('multipart', $multipart);
    $smarty->assign('noajaxpost', get_class($this) == 'ContentSettingsConstant' || get_class($this) == 'ContentSettingsDb' || $multipart === true);
    $smarty->assign('selflink', $this->getPageLink());
    $smarty->assign('groups', $subGroups);

    $statusAry = SessionOperations::getVarValueIntern('messages');

    $status = $statusMessage = '';
    foreach ($statusAry as $key => $value) { 
      $status = $key;
      $statusMessage = $value;
    }
    $smarty->assign('status', $status);
    $smarty->assign('messages', CleanOperations::cleanStringForHtml($statusMessage));

    return $smarty->fetch('settings/settingform.html');
  }

  protected function saveSettings()
  {
    if (isset($this->configFile)) {
      $sc = $this->settingConverter;
      $sc->saveSettingsByPost($this->configFile);
    }
  }

  protected function getsettingsFromSQL()
  {
    if (isset($this->configFile)) {
      $sc = $this->settingConverter;
      $sc->getSettingsFromConfig($this->configFile);
      $sc->kopieVonKuferSQL();
    }
  }
}

class ContentNavSettings extends ContentSubNavigation
{
  public function getNavItems()
  {
    $navItems = array();

    $item = new NavItem();
    $item->name = 'Suche';
    $item->objectName = 'ContentSettingSearch';
    array_push($navItems, $item);

    $item = new NavItem();
    $item->name = 'System';
    $item->objectName = $this->getObjectNameByAccess('settings', 'ContentSettingsSystem');
    $nav = new ContentNavSettingsSystem();
    $item->subItems = $nav->getNavItems();
    array_push($navItems, $item);

    $item = new NavItem();
    $item->name = 'Layout';
    $item->objectName = $this->getObjectNameByAccess('settings', 'ContentSettingsLayout');
    $nav = new ContentNavSettingsLayout();
    $item->subItems = $nav->getNavItems();
    array_push($navItems, $item);

    $item = new NavItem();
    $item->name = 'Konstanten';
    $item->objectName = $this->getObjectNameByAccess('settings', 'ContentSettingsConstant');
    $nav = new ContentNavSettingsConstant();
    $item->subItems = $nav->getNavItems();
    array_push($navItems, $item);

    $item = new NavItem();
    $item->name = 'Datenbankverbindung';
    $item->objectName = $this->getObjectNameByAccess('settings', 'ContentSettingsDb');
    $nav = new ContentNavSettingsDb();
    $item->subItems = $nav->getNavItems();
    array_push($navItems, $item);

    $item = new NavItem();
    $item->name = 'Plugins';
    $item->objectName = $this->getObjectNameByAccess('settings', 'ContentSettingsPlugin');
    $nav = new ContentNavSettingsPlugin();
    $item->subItems = $nav->getNavItems();
    if (!empty($item->subItems)) {
      array_push($navItems, $item);
    }

    return $navItems;
  }
}

abstract class ContentNavSettingsTemplate extends ContentSubNavigation
{
  protected $settingConverter;
  protected $contentClass;

  public function getNavItems()
  {
    $navItems = array();

    $files = $this->settingConverter->getConfigFiles();

    foreach ($files as $file) {
      $item = new NavItem();
      $item->name = $file->longName;
      $item->objectName = $this->contentClass;
      $item->objectParam = $file->fileName;
      if ($this instanceof ContentNavSettingsSystem) {
        $item->folder = 'system';
      } elseif ($this instanceof ContentNavSettingsConstant) {
        $item->folder = 'constants';
      } elseif ($this instanceof ContentNavSettingsLayout) {
        $item->folder = 'layout';
      } elseif ($this instanceof ContentNavSettingsDb) {
        $item->folder = 'db';
      }
      
      $item->hardlink = 'file_' . (isset($item->folder) ? $item->folder . '_' : '') . $file->fileName;
      array_push($navItems, $item);
    }

    return $navItems;
  }
}

class ContentNavSettingsLayout extends ContentNavSettingsTemplate
{
  public function __construct()
  {
    $this->settingConverter = new LibSettingLayout();
    $this->contentClass = 'ContentSettingsLayout';
  }
}

class ContentNavSettingsSystem extends ContentNavSettingsTemplate
{
  public function __construct()
  {
    $this->settingConverter = new LibSettingSystem();
    $this->contentClass = 'ContentSettingsSystem';
  }
}

class ContentNavSettingsConstant extends ContentNavSettingsTemplate
{
  public function __construct()
  {
    $this->settingConverter = new LibSettingConstant();
    $this->contentClass = 'ContentSettingsConstant';
  }
}

class ContentNavSettingsDb extends ContentNavSettingsTemplate
{
  public function __construct()
  {
    $this->settingConverter = new LibSettingDb();
    $this->contentClass = 'ContentSettingsDb';
  }
}


class ContentNavSettingsPlugin extends ContentNavSettingsTemplate
{
  public function __construct()
  {
    $this->settingConverter = new LibSettingPlugin();
    $this->contentClass = 'ContentSettingsPlugin';
  }

  
  public function getNavItems()
  {
    $data = new ContentSettingsPlugin();
    $plugins = $data->getPlugins();
    $navItems = array();

    foreach ($plugins as $plugin) {
      $dir = (StringOperations::strpos($plugin, 'epayment_') !== false) ? str_replace('epayment_', 'epayment' . DIRECTORY_SEPARATOR, $plugin) : $plugin;

      $fileName = WBPLUGIN_PATH . $dir . DIRECTORY_SEPARATOR . 'settings.xml';
      if (file_exists($fileName) && $xml = @simplexml_load_file($fileName)) {
        $item = new NavItem();
        $item->name = \StringOperations::utf8_decode($xml->general->name);
        $item->objectName = $this->contentClass;
        $item->objectParam = $plugin;
        array_push($navItems, $item);
      }
    }

    return $navItems;
  }
}

class ContentSettingsLayout extends ContentSettings
{
  public function __construct($pConfigFile = '')
  {
    $this->settingConverter = new LibSettingLayout();
    $this->action = 'settings_layout';
    parent::__construct($pConfigFile);
  }
}

class ContentSettingsSystem extends ContentSettings
{
  public function __construct($pConfigFile = '')
  {
    $this->settingConverter = new LibSettingSystem();
    $this->action = 'settings_system';
    parent::__construct($pConfigFile);
  }
}

class ContentSettingsConstant extends ContentSettings
{
  protected function saveSettings()
  {
    parent::saveSettings();
    
    $action = $this->getPageLink();
    $action = htmlspecialchars_decode($action);
    header('Location: ' . $action);
    die();
  }

  public function __construct($pConfigFile = '')
  {
    $this->settingConverter = new LibSettingConstant();
    $this->action = 'settings_constants';
    parent::__construct($pConfigFile);
  }
}

class ContentSettingsDb extends ContentSettings
{
  protected function saveSettings()
  {
    parent::saveSettings();
    
    $action = $this->getPageLink();
    $action = htmlspecialchars_decode($action);
    header('Location: ' . $action);
    die();
  }

  public function __construct($pConfigFile = '')
  {
    $this->settingConverter = new LibSettingDb();
    $this->action = 'settings_db';
    parent::__construct($pConfigFile);
  }
}



class ContentSettingsPlugin extends ContentSettings
{
  private $actPlugin = false;
  private $plugins = array();
  private $baseURL = 'index.php';

  
  private $actData;

  
  private $actDataSet;

  private $error = false;
  private $errorMessage = '';
  private $defaultError = 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.';
  private $initialized = false;

  
  protected $settingConverter;

  public function __construct($pPlugin = '')
  {
    $this->init($pPlugin);
    $this->action = 'settings_plugin';
  }

  public function getContent()
  {
    $out = '<div id="pluginSettings">';

    if ($this->error) {
      $out .= $this->getError();
    } else {
      switch (GetOperations::getVarValue('pa', false)) {
        default:
          $out .= $this->getListContent();
          break;
        case 'create':
          $out .= $this->getCreateContent();
          break;
        case 'edit':
          $out .= $this->getEditContent();
          break;
        case 'delete':
          $out .= $this->getDeleteContent();
          break;
      }
    }

    $out .= '</div>';
    if (!$this->settingConverter->hasOnlyOneDs()) {
      $out .= $this->getJavascript();
    }

    return $out;
  }

  
  private function getJavascript()
  {
    $out = '<script type="text/javascript">';

    
    $out .= '$(function($) {';

    
    $out .= '$(\'div#pluginSettings a\').click(function (event) {
      event.preventDefault();
      var link = $(this).prop(\'href\');
      loadContent(link);
    });';

    
    $out .= '});';

    $out .= '</script>';

    return $out;
  }

  
  private function readPlugins()
  {
    $dir = opendir(WBPLUGIN_PATH);
    if ($dir) {
      while ($actDir = readdir($dir)) {
        $dirPath = WBPLUGIN_PATH . $actDir;
        if (!is_dir($dirPath) || $actDir === '..' || $actDir === '.' || $actDir === '.svn') {
          continue;
        }

        $fileName = $dirPath . DIRECTORY_SEPARATOR . 'settings.xml';
        if (file_exists($fileName)) {
          $this->plugins[] = $actDir;
        }

        
        if ($actDir == 'epayment') {
          $ePaymentDir = opendir($dirPath);
          if ($ePaymentDir) {
            while ($actEPaymentDir = readdir($ePaymentDir)) {
              $ePaymentDirPath = $dirPath . DIRECTORY_SEPARATOR . $actEPaymentDir;

              if (!is_dir($ePaymentDirPath) || $actEPaymentDir === '..' || $actEPaymentDir === '.' || $actEPaymentDir === '.svn') {
                continue;
              }

              if (file_exists($ePaymentDirPath . DIRECTORY_SEPARATOR . 'settings.xml')) {
                $this->plugins[] = 'epayment_' . $actEPaymentDir;
              }
            }
          }
        }
      }
    } else {
      return false;
    }

    return true;
  }

  
  private function generateLink($pLabel, $pParams = array(), $pAttributes = array())
  {
    $attr = '';
    foreach ($pAttributes as $key => $val) {
      $attr .= ' ' . CleanOperations::cleanStringForHtml($key) . '="' . CleanOperations::cleanStringForHtml($val) . '"';
    }

    $cleanedLabel = CleanOperations::cleanStringForHtml($pLabel);

    return '<a href="' . $this->generateURL($pParams) . '" title="' . $cleanedLabel . '"' . $attr . '>' . $cleanedLabel . '</a>';
  }

  
  private function generateURL($pParams = array())
  {
    $params = $pParams;
    $paramString = '';

    foreach ($_GET as $key => $val) {
      if (!key_exists($key, $params) && $key != 'ajax' && $key != 'wb__already__decoded') {
        $params[$key] = GetOperations::getVarValue($key);
      }
    }

    if (is_array($params)) {
      foreach ($params as $k => $v) {
        if ($paramString == '') {
          $paramString .= '?' . $k . '=' . $v;
        } else {
          $paramString .= '&' . $k . '=' . $v;
        }
      }
    }

    return $this->baseURL . $paramString;
  }

  

  
  private function getListContent($pMsg = '')
  {
    $settings = $this->settingConverter->getSettings();
    $data = $this->settingConverter->getActData();

    if ($this->settingConverter->hasOnlyOneDs()) {
      return $this->getEditContent();
    }

    $content = '';

    if ($pMsg != '') {
      $content .= '<div class="status_ok">' . CleanOperations::cleanStringForHtml($pMsg) . '</div><br />';
    }

    $content .= '<h3>Datens&auml;tze des Plugins ' . $settings->general->name . '</h3>';

    $column = array('title' => 'name', 'description' => '', 'order' => '', 'order_type' => 'asc');

    foreach ((array)$settings->object as $key => $val) {
      if ($val->attributes()->title == 'true') {
        $column['title'] = $key;
      }

      if ($val->attributes()->description == 'true') {
        $column['description'] = $key;
      }

      if ($val->attributes()->order == 'true') {
        $column['order'] = $key;
        if ($val->attributes()->order_type != ''
             && ($val->attributes()->order_type == 'asc'
               || $val->attributes()->order_type == 'desc')) {
          $column['order_type'] = (string)$val->attributes()->order_type;
        }
      }
    }

    if ($column['order'] == '') {
      $column['order'] = $column['title'];
    }

    $content .= '<div class="heading">'
                  . '<div class="right">'
                    . $this->generateLink('Neu', array('pa' => 'create'), array('class' => 'create'))
                  . '</div>'
                  . '<div class="left">'
                    . $settings->object->{$column['title']}->name
                  . '</div>'
                . '</div>';
    $data = get_object_vars($data);

    if (!isset($data['element'])) {
      $data = array();
    } elseif (is_object($data['element'])) {
      $data[] = $data['element'];
      unset($data['element']);
    } else {
      $data = $data['element'];
    }

    usort($data, $this->build_sorter($column));

    $count = 0;
    foreach ($data as $val) {
      $class = ($count++ % 2 == 0) ? ' alt1' : ' alt2';
      $description = ($column['description'] !== '' && isset($val->{$column['description']}))
        ? '<div class="detail">' . $val->{$column['description']} . '</div>' : '';


      $content .= '<div class="row' . $class . '">'
          . '<div class="right">'
            . $this->generateLink('Datensatz bearbeiten', array('pa' => 'edit', 'dsid' => $val->attributes()->id), array('class' => 'edit img_button'))
            . $this->generateLink('Datensatz löschen', array('pa' => 'delete', 'dsid' => $val->attributes()->id), array('class' => 'delete img_button'))
          . '</div>'
          . '<div class="left">';
      $content .= (isset($val->{$column['title']})) ? $val->{$column['title']} : '';
      $content .= $description . '</div>'
        . '</div>';
    }

    return $content;
  }

  
  public function build_sorter($pSortInfo)
  {
    return function($a, $b) use ($pSortInfo) {
      if ($pSortInfo['order_type'] == 'desc') {
        return strnatcmp($b->{$pSortInfo['order']}, $a->{$pSortInfo['order']});
      } else {
        return strnatcmp($a->{$pSortInfo['order']}, $b->{$pSortInfo['order']});
      }
    };
  }

  
  private function getCreateContent()
  {
    if ($this->settingConverter->hasOnlyOneDs()) {
      return $this->getEditContent();
    }

    $sc = $this->settingConverter;
    if (PostOperations::isDefined('savesettings')) {
      $this->saveSettings();
      if ($sc->writeActDataToXML()) {
        return $this->getListContent('Daten erfolgreich erzeugt.');
      } else {
        $this->setError('Fehler beim Erstellen des Datensatzes');

        return $this->getError() . $this->getListContent();
      }
    }

    return $this->getFormForDataSet($sc->generateNewDataSet());
  }

  
  private function getEditContent()
  {
    $sc = $this->settingConverter;

    if (PostOperations::isDefined('savesettings')) {
      
      if (($this->saveSettings()) && (!$sc->hasOnlyOneDs())) {
        return $this->getListContent('Daten erfolgreich gespeichert.');
      } elseif (!$sc->hasOnlyOneDs()) {
        $this->setError('Fehler beim Speichern der Datensätze');

        return $this->getError() . $this->getListContent();
      } else {
        $content = '<div class="status_ok">Daten erfolgreich gespeichert</div><br />';

        return $content . $this->getFormForDataSet($sc->getActDataSet());
      }
    }

    return $this->getFormForDataSet($sc->getActDataSet());
  }

  
  private function getDeleteContent()
  {
    if ($this->settingConverter->hasOnlyOneDs()) {
      return $this->getEditContent();
    }

    $sc = $this->settingConverter;
    $sc->deleteActDataSet();

    if ($sc->writeActDataToXML()) {
      return $this->getListContent('Datensatz erfolgreich gelöscht.');
    } else {
      $this->setError('Fehler beim Löschen des Datensatzes');

      return $this->getError() . $this->getListContent();
    }
  }

  
  private function getFormForDataSet($pDataSet)
  {
    $sc = $this->settingConverter;
    $settings = $sc->getSettings();

    $subGroups = array();
    $settingsArray = array();

    foreach ($settings->object->children() as $key => $val) {
      $setting = new Setting();
      $setting->name = $key;
      $setting->value = isset($this->actDataSet->{$key}) ? $this->actDataSet->{$key} : '';

      $setting->description = \StringOperations::utf8_decode((string)$val->name);
      $setting->help = \StringOperations::utf8_decode((string)$val->help);
      $setting->beforeInput = (string)$val->beforeInput;
      $setting->afterInput = (string)$val->afterInput;
      $setting->subGroup = 'Einstellungen';
      $setting->config->loadConfiguration(constant($val->type->attributes()->name));
      foreach ($val->type->attributes() as $k => $v) {
        $setting->config->{(string)$k} = (string)$v;
      }
      foreach ($val->type->children() as $k => $v) {
        if ($k == 'items') {
          $newItems = array();
          $items = get_object_vars($v->children());

          if (is_array($items['item'])) {
            $itemAry = $items['item'];
          } else {
            $itemAry = array($items['item']);
          }

          foreach ($itemAry as $item) {
            $newItems[(string)$item->attributes()->value] = (string)$item->attributes()->content;
          }

          $setting->config->items = $newItems;
        }
      }

      $settingsArray[] = array(
        'description' => $setting->description,
        'descriptionWithColonMark' => $setting->config->descriptionWithColonMark,
        'descriptionBeforeInput' => $setting->descriptionBeforeInput,
        'beforeinput' => $setting->beforeInput,
        'afterinput' => $setting->afterInput,
        'additionalcontent' => '',
        'input' => $sc->getInput($setting),
        'inputname' => StringOperations::strtolower($setting->name),
        'typename' => $setting->config->typeName,
        'help' => $setting->help,
        'classname' => $setting->className
      );
    }

    if ($sc->hasOnlyOneDs()) {
      $arySubGroup['subgroupname'] = 'Bearbeiten der Daten des Plugins: ' . \StringOperations::utf8_decode($settings->general->name);
    } else {
      $arySubGroup['subgroupname'] = ($pDataSet->name != '') ? 'Bearbeiten des Datensatzes: ' . \StringOperations::utf8_decode($pDataSet->name) : 'Neuen Datensatz erstellen';
    }

    $arySubGroup['subgroupid'] = 'einstellungen';
    $arySubGroup['items'] = $settingsArray;
    array_push($subGroups, $arySubGroup);

    $smarty = $this->getSmarty();
    $smarty->assign('groupname', 'Bearbeiten des Datensatzes: ' . \StringOperations::utf8_decode($pDataSet->name));
    $smarty->assign('noajaxpost', get_class($this) == 'ContentSettingsConstant' || get_class($this) == 'ContentSettingsDb');
    $smarty->assign('selflink', $this->generateURL(array('dsid' => $pDataSet->attributes()->id)));
    $smarty->assign('groups', $subGroups);

    return $smarty->fetch('settings/settingform.html');
  }

  
  private function getError()
  {
    return '<div class="status_error">' . CleanOperations::cleanStringForHtml($this->errorMessage) . '</div>';
  }

  
  public function getPlugins()
  {
    return $this->plugins;
  }

  

  
  private function setError($pErrorMsg = '')
  {
    $this->error = true;
    $this->errorMessage = ($pErrorMsg !== '') ? $pErrorMsg : $this->defaultError;
  }

  
  protected function saveSettings()
  {
    $sc = $this->settingConverter;

    return $sc->saveSettingsFromPost();
  }

  
  private function init($pPlugin)
  {
    if ($this->initialized) {
      return;
    }

    $this->readPlugins();
    $this->initialized = true;


    $actPlugin = false;

    if (($pPlugin != '') && (in_array($pPlugin, $this->plugins))) {
      $actPlugin = $pPlugin;
    } else {
      $this->setError('Das ausgewählte Plugin konnte nicht gefunden werden');

      return;
    }

    $actPluginDir = (StringOperations::strpos($actPlugin, 'epayment_') !== false) ? str_replace('epayment_', 'epayment' . DIRECTORY_SEPARATOR, $actPlugin) : $actPlugin;

    $settingsPath = WBPLUGIN_PATH . $actPluginDir . DIRECTORY_SEPARATOR . 'settings.xml';
    $dataPath = WBPLUGIN_PATH . $actPluginDir . DIRECTORY_SEPARATOR . 'data.xml';

    $this->settingConverter = new LibSettingPlugin($settingsPath, $dataPath);

    if (!$this->settingConverter->load()) {
      $this->setError($this->settingConverter->getError());

      return;
    }

    $this->actData = $this->settingConverter->getActData();
    $this->actDataSet = $this->settingConverter->getActDataSet();

    $this->actPlugin = $actPlugin;
  }
}


class ContentSettingSearch extends Content
{
  private $navItems;

  
  protected function getAttributeForConfigFile($pConfigFile, $pAttribute, $pIsMenu = false)
  {
    if (!isset($this->navItems)) {
      $navSettings = new ContentNavSettings();
      $this->navItems = $navSettings->getNavItemsProcessed();
    }
    foreach ($this->navItems as $item) {
      foreach ($item->subItems as $subItem) {
        if ($subItem->objectParam == $pConfigFile->fileName && $subItem->folder == $pConfigFile->folderName) {
          if ($pIsMenu) {
            return $item->{$pAttribute};
          } else {
            return $subItem->{$pAttribute};
          }
        }
      }
    }

    throw new Exception('Die Einstellung ' . $pConfigFile->longName . ' ist im Navigationsmenü nicht enthalten!');
  }

  protected function getLibSettings()
  {
    return new LibSetting();
  }

  protected function getTitle($configFile)
  {
    return $configFile->longName;
  }

  public function getContent()
  {
    $lib = $this->getLibSettings();
    $smarty = $this->getSmarty();
    $searchword = SessionOperations::getVarValueIntern('admin_settingsearchword', '');
    $searchword = trim(PostOperations::getVarValue('settingsearch_searchword', $searchword));
    SessionOperations::setVarValueIntern('admin_settingsearchword', $searchword);

    
    $smarty->assign('start', $searchword != '');
    if ($searchword != '') {
      $configFiles = $lib->searchSetting($searchword);
      $menuItems = $this->addMenuTitleToConfigFiles($configFiles);
      
      $menus = array();
      $configs = array();
      $subGroups = array();
      $settings = array();
      $count = 0;
      
      foreach ($menuItems as $key => $menuItem) {
        array_push($menus, $key);
        
        foreach ($menuItem as $configFile) {
          if (!key_exists($key, $configs)) {
            $configs[$key] = array();
          }
          array_push($configs[$key], array(
            'title' => $this->getTitle($configFile),
            'key' => $configFile->folderName . $configFile->longName,
            'link' => $this->getAttributeForConfigFile($configFile, 'link')
          ));
          
          foreach ($configFile->settingsObjects as $setting) {
            $key2 = $configFile->folderName . $configFile->longName;
            $key3 = $configFile->folderName . $configFile->longName . $setting->subGroup;
            if (!key_exists($key2, $subGroups)) {
              $subGroups[$key2] = array();
            }
            if (!in_array(array('title' => $setting->subGroup, 'key' => $key3), $subGroups[$key2])) {
              array_push($subGroups[$key2], array(
                'title' => $setting->subGroup,
                'key' => $key3
              ));
            }

            if (!key_exists($key3, $settings)) {
              $settings[$key3] = array();
            }
            array_push($settings[$key3], $setting->description);
            $count++;
          }
        }
      }
      $smarty->assign('count', $count);
      $smarty->assign('menus', $menus);
      $smarty->assign('configs', $configs);
      $smarty->assign('subgroups', $subGroups);
      $smarty->assign('settings', $settings);
    }

    $smarty->assign('selflink', $this->getPageLink());
    $smarty->assign('searchword', CleanOperations::cleanStringForHtml($searchword));

    return $smarty->fetch('settings/setting_search.html');
  }

  private function addMenuTitleToConfigFiles($pConfigFiles)
  {
    $configFilesWithMenu = array();
    foreach ($pConfigFiles as $configFile) {
      $key = $this->getAttributeForConfigFile($configFile, 'name', true);
      if (!key_exists($key, $configFilesWithMenu)) {
        $configFilesWithMenu[$key] = array();
      }
      array_push($configFilesWithMenu[$key], $configFile);
    }

    return $configFilesWithMenu;
  }
}