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


class ToolsAPI
{
  
  public const TOOL_KURSUEBERSICHT_DOZ = 1;

  
  public const TOOL_KURSUEBERSICHT_TN = 2;

  
  public const TOOL_KURSPLANUNG_DOZ = 3;

  
  public const TOOL_WEBBASYS = 4;

  
  public const TOOL_RAUMBELEGUNG_HM = 5;

  
  public const TOOL_ANMELDUNGBUCHEN_MA = 6;

  
  public const TOOL_LEHRPLAN_DOZ = 7;

  
  public const TOOL_KURSPLANUNG_MA = 8;

  
  public const TOOL_VERTRAG_DOZ = 9;

  
  public const TOOL_KURSBEWERBUNG_DOZ = 10;

  
  public const TOOL_TEILNEHMERINFO_MA = 11;

  
  public const TOOL_DOZENTENINFO_MA = 12;

  
  public const TOOL_PERSDATA = 13;

  
  public const TOOL_ANMELDUNGBUCHEN_TN = 14;

  
  public const TOOL_KURSUEBERSICHT_MA = 15;

  
  public const TOOL_AKTUELLES = 16;

  
  public const TOOL_TWITTER = 17;

  
  public const TOOL_ANWESENHEIT_DOZ = 18;

  
  public const TOOL_RAUMANZEIGE = 19;

  
  public const TOOL_TN = 20;

  
  public const TOOL_KURSUEBERSICHT_FA = 21;

  
  public const TOOL_MITARBEITERUEBERSICHT_FA = 22;

  
  public const TOOL_NACHRICHT_AN_EINRICHTUNG = 23;

  
  public const TOOL_ANMELDUNGBUCHEN_FA = 24;

  
  public const TOOL_KURSVORSCHLAG_TN = 25;

  
  public const TOOL_PUNKTE_TN = 30;
  
  public const TOOL_MOB_FEEDBACK = 31;
  
  public const TOOL_KURSUEBERSICHT_HM = 32;
  
  public const TOOL_ADRESSINFO_MA = 33;
  
  public const TOOL_RAUMBELEGUNG_MA = 34;
  
  public const TOOL_RAUMRESERVIERUNG_HM = 35;

  
  public const TOOL_VORGESETZTER_TN = 36;

  
  public const TOOL_PORTRAIT_DOZ = 37;

  
  public const TOOL_HONORAR_DOZ = 38;

  
  public const TOOL_FACH_VERTRAG_DOZ = 39;

  
  public const TOOL_WEBVISITENKARTEN = 40;

  
  public const TOOL_KURSVORSCHLAG_MA = 41;

  
  public const TOOL_FEEDBACK_AUSWERTUNGEN_DOZ = 49;

  
  public const TOOL_FEEDBACK_AUSWERTUNGEN_MA = 50;

  
  public const TOOL_FEEDBACK_AUSWERTUNGEN_FA = 63;

  
  public const TOOL_KURSUEBERSICHT_VA = 51;
  
  public const TOOL_KURSVORSCHLAG_VA = 52;
  
  public const TOOL_ANMELDUNGBUCHEN_VA = 53;
  
  public const TOOL_KURSUEBERSICHT_ANDERER_VERANSTALTER_VA = 54;

  
  public const TOOL_TEILNEHMERINFO_VA = 58;
  
  public const TOOL_LEITER_MITARBEITER_ANDERER_VERANSTALTER_VA = 60;

  
  public const TOOL_DOKUMENTE_FA = 64;

  
  public const TOOL_DOKUMENTE_TN = 65;

  
  public const TOOL_DOKUMENTE_VA = 59;

  
  public const TOOL_DOKUMENTE_DOZ = 62;

  
  public const TOOL_DOZ_WUNSCHTERMINE = 69;

  
  public const TOOL_DOZ_URLAUBE = 70;

  
  public const TOOL_DOZ_SAMMELVERTRAEGE = 71;

  public function __construct()
  {
  }

  
  public static function isPersonWithoutMoodleCredentialsForElearningCourse($pPerson, $pKurs)
  {
    if (!($pKurs->elearningKursID > 0)) {
      return false;
    }
    if ($pPerson->name == '' || $pPerson->vorname == '' || $pPerson->email == '') {
      return true;
    }

    return false;
  }

  
  public static function isTnMoodleRegisterableOrAlreadyRegistered($pTn, $pKurs)
  {
    if (!WbPluginBasis::pluginExists(PLUGIN_MOODLE)) {
      return true;
    }
    if (!($pKurs->elearningKursID > 0)) {
      return true;
    }
    $soapMoodle = new SoapMoodle();
    
    
    if ($pTn->isTeilnehmerBeiELearningRegistriert() || !$soapMoodle->isEmailVorhanden($pTn->email->wert)) {
      return true;
    }

    return false;
  }

  
  public static function getCurrentToolId()
  {
    $url = URL::loadCurrent();
    $result = $url->getParameterValue('tool_id') ?? $url->getParameterValue('toolid');
    if (\is_null($result)) {
      throw new Exception('Ungültiger Zustand, kann ToolId nicht ermitteln');
    }

    return $result;
  }

  
  public static function getCurrentStammObject(\Kufer\Web\Classes\Identifier\Identifier $pAutorId)
  {
    $dbwUser = new DBWorkUser();
    $user = $dbwUser->getUser($pAutorId);
    $bearb = '';
    if ($user->ben != -1) {
      $dbwBearb = new DBWorkBASysUser();
      $bearb = $dbwBearb->getBASysUser($user->ben);
    } elseif ($user->dnr != -1) {
      $dbwBearb = new DBWorkDozenten();
      $bearb = $dbwBearb->getDozent($user->dnr);
    } elseif ($user->tnr != -1) {
      $dbwBearb = new DBWorkTeilnehmer();
      $bearb = $dbwBearb->getTeilnehm($user->tnr);
    } elseif ($user->anr != -1) {
      $dbwBearb = new DBWorkAdresse();
      $bearb = $dbwBearb->getAdresse($user->anr);
    } else {
      return false;
    }

    return $bearb;
  }

  
  public static function updateAndGetSelectedIds($pToolId = false)
  {
    return self::updateAndGetSelectedIdsByParams(
      RequestOperations::getVarValue('markerAction'),
      RequestOperations::getVarValue('idsToMark', ''),
      RequestOperations::getVarValue('idsToUnmark', ''),
      $pToolId
    );
  }

  
  public static function updateAndGetSelectedIdsByParams($pMarkerAction, $pIdsToMark, $pIdsToUnMark, $pToolId = false, $pTotalDataStr = 'totaldatastr_', $pSelectionSessionVarName = 'selnrstr_')
  {
    static $handled = false;
    $trenner = ':';
    $toolId = $pToolId;
    if ($toolId === false) {
      $toolId = self::getCurrentToolId();
    }
    $sessionVarname = $pSelectionSessionVarName . $toolId;
    $selectedIds = SessionOperations::getVarValueWTIntern($sessionVarname);
    if (StringOperations::strlen($selectedIds) > 0) {
      $selectedIds = explode($trenner, $selectedIds);
    } else {
      $selectedIds = array();
    }
    if (!$handled) { 
      if ($pMarkerAction == 'markiereAlle') {
        $selectedIds = self::getTotalData('', $toolId, $pTotalDataStr);
      } elseif ($pMarkerAction == 'loescheMarkierungen') {
        $selectedIds = array();
      } else {
        $neueIds = array();
        if ($pIdsToMark != '') {
          $neueIds = explode($trenner, $pIdsToMark);
        }
        $wegzunehmendeIds = array();
        if ($pIdsToUnMark != '') {
          $wegzunehmendeIds = explode($trenner, $pIdsToUnMark);
        }

        
        $selectedIds = array_merge($selectedIds, $neueIds);

        
        if (count($wegzunehmendeIds) > 0) {
          $countVorherSelektierteIds = count($selectedIds);
          $tmp = array();
          for ($i = 0; $i < $countVorherSelektierteIds; $i++) {
            if (!in_array($selectedIds[$i], $wegzunehmendeIds)) {
              $tmp[] = $selectedIds[$i];
            }
          }
          $selectedIds = $tmp;
        }

        
        $selectedIds = array_unique($selectedIds);
      }
      SessionOperations::setVarValueWTIntern($sessionVarname, implode($trenner, $selectedIds));
      $handled = true;
    }

    return $selectedIds;
  }

  public static function getEmailAdressForKennung($kennung)
  {
    $dbwUser = new DBWorkBASysUser();
    $user = $dbwUser->getBASysUserByKennung($kennung);

    return isset($user) ? $user->email : '';
  }

  public static function getEmailAdresseForID($pID)
  {
    $dbwUser = new DBWorkBASysUser();
    $user = $dbwUser->getBASysUser($pID);

    return isset($user) ? $user->email : '';
  }

  
  public static function getEmailAdressForKursMA($pKurs, $pToolId, $pPageId, $pMailAnMaAry = null, $pZielEmailAdresse = null)
  {
    $vhsEmail = self::getVhsEmail($pToolId, $pPageId, $pZielEmailAdresse);
    
    if ($pMailAnMaAry == null || ((!isset($pMailAnMaAry['VerwMa']) || !$pMailAnMaAry['VerwMa'])
                                   && (!isset($pMailAnMaAry['PlanMa']) || !$pMailAnMaAry['PlanMa']))) {
      
      return array('Einrichtung' => $vhsEmail);
    }


    
    if (isset($pMailAnMaAry['VerwMa']) && $pMailAnMaAry['VerwMa'] && isset($pMailAnMaAry['PlanMa']) && $pMailAnMaAry['PlanMa']) {
      $maKennungVerw = $pKurs->getVarValue('verwaltung_ma');
      $maKennungPla = $pKurs->getVarValue('hpm');
      if ($maKennungVerw == '' && $maKennungPla == '') {
        $retour = array('Einrichtung' => $vhsEmail);
      }
      
      elseif ($maKennungVerw != '' && $maKennungPla != '') {
        $dbwMa = new DBWorkBASysUser();
        $ma1 = $dbwMa->getBASysUserByKennung($maKennungVerw);
        $ma2 = $dbwMa->getBASysUserByKennung($maKennungPla);
        if ($ma1->email != '' && $ma2->email != '') {
          $retour = array('VerwMa' => $ma1->email, 'PlanMa' => $ma2->email);
        } elseif ($ma1->email != '') {
          $retour = array('VerwMa' => $ma1->email);
        } elseif ($ma2->email != '') {
          $retour = array('PlanMa' => $ma2->email);
        } else { 
          $retour = array('Einrichtung' => $vhsEmail);
        }
      }
      
      else {
        $dbwMa = new DBWorkBASysUser();
        if ($maKennungVerw != '') { 
          $ma = $dbwMa->getBASysUserByKennung($maKennungVerw);
        } else { 
          $ma = $dbwMa->getBASysUserByKennung($maKennungPla);
        }
        if ($ma->email != '') {
          if ($maKennungVerw != '') {
            $retour = array('VerwMa' => $ma->email);
          } else {
            $retour = array('PlanMa' => $ma->email);
          }
        } else {
          $retour = array('Einrichtung' => $vhsEmail);
        }
      }

      return $retour;
    } 

    
    $verwaltend = true;
    if (isset($pMailAnMaAry['VerwMa']) && $pMailAnMaAry['VerwMa']) {
      $maKennung = $pKurs->getVarValue('verwaltung_ma');
    } else {
      $maKennung = $pKurs->getVarValue('hpm');
      $verwaltend = false;
    }

    if ($maKennung != '') {
      $dbwMa = new DBWorkBASysUser();
      $ma = $dbwMa->getBASysUserByKennung($maKennung);
      if ($ma->email != '') {
        if ($verwaltend) {
          $retour = array('VerwMa' => $ma->email);
        } else {
          $retour = array('PlanMa' => $ma->email);
        }
      } else {
        $retour = array('Einrichtung' => $vhsEmail);
      }
    } else {
      $retour = array('Einrichtung' => $vhsEmail);
    }

    return $retour;
  }

  public static function getVhsEmail($pToolId, $pPageId, $pVhsMail)
  {
    $objSettings = ToolSettingsAPI::getToolSettings($pToolId);
    $vhsEmailTool = EmailOperations::getVarName4ToolEmailSetting($pToolId, $pPageId);
    if (is_null($pVhsMail)) {
      $vhsMail = isset($objSettings->{$vhsEmailTool}) ? $objSettings->{$vhsEmailTool} : '';
    } else {
      $vhsMail = $pVhsMail;
    }

    return EmailOperations::getToolEmailAddressForVhs($vhsMail);
  }

  
  public static function getEmailsEmpfaenger4Benachrichtigungen($pKurs, $pToolId, $pToolSectionId, $pMailAnAry, $pZielEmailAdresse = '')
  {
    $emails = array();

    if ($pMailAnAry['VerwMa'] || $pMailAnAry['PlanMa']) {
      $emails = array_merge($emails, \array_values(self::getEmailAdressForKursMA($pKurs, $pToolId, $pToolSectionId, $pMailAnAry, $pZielEmailAdresse)));
    }

    if ($pMailAnAry['Einrichtung']) {
      $emails[] = \EmailOperations::getToolEmailAddressForVhs($pZielEmailAdresse);
    }

    return array_unique($emails);
  }

  
  public static function getSenderEmailAddressAndName($pPerson, $pEmpfaenger = 'Einrichtung', $pEmailAbsender = null)
  {
    $replyEmail = '';
    $replyName = '';

    $allgeinstell = AllgSettingsAPI::getAllgSettings();

    $tool0Settings = ToolSettingsAPI::getToolSettings(0);
    $absenderPersonAnEmpfaenger = $pPerson->getVarName4EmailSenderSetting($pEmpfaenger);
    $absenderValue = isset($tool0Settings->{$absenderPersonAnEmpfaenger}) ? $tool0Settings->{$absenderPersonAnEmpfaenger} : '';
    $emailAndNameEinrichtung = self::getSenderEmailAdressAndNameEinrichtung($absenderValue);

    if ($absenderValue == 'Person') {
      $emailAndName = self::_getSenderEmailAdressAndNamePerson($pPerson);
    }

    if (!isset($emailAndName) || !self::_isEmailValid($emailAndName['email'])) {
      $emailAndName = $emailAndNameEinrichtung;
    }

    $email = $emailAndName['email'];
    $name = $emailAndName['name'];

    if (isset($pEmailAbsender) && self::_isEmailValid($pEmailAbsender)) {
      $email = $pEmailAbsender;
    }

    if ($allgeinstell->absenderAlsReplyTo && self::_isEmailValid($email)) {
      
      $replyEmail = $email;
      $replyName = $name;
      $email = $emailAndNameEinrichtung['email'];
      $name = $emailAndNameEinrichtung['name'];
    }

    return array('email' => $email, 'name' => $name, 'reply' => $replyEmail, 'replyname' => $replyName);
  }

  private static function _getSenderEmailAdressAndNamePerson($pPerson)
  {
    $email = '';
    $name = '';

    if (!is_null($pPerson)) {
      
      $email = (is_string($pPerson->email) ? $pPerson->email : $pPerson->email->wert);
      $name = $pPerson->getVarValue('vorname_name_ohne_komma');
    }

    return array('email' => $email, 'name' => $name);
  }

  public static function getSenderEmailAdressAndNameEinrichtung($pAbsender = '')
  {
    $allgSettings = AllgSettingsAPI::getAllgSettings();

    $toolSettings = ToolSettingsAPI::getToolSettings(0);

    if ($pAbsender === 'Abweichend' && self::_isEmailValid($toolSettings->abweichendeAbsenderEMailAdresse)) {
      $email = $toolSettings->abweichendeAbsenderEMailAdresse;
    } elseif (self::_isEmailValid($allgSettings->smtpadresse)) {
      $email = $allgSettings->smtpadresse;
    } else {
      $email = $allgSettings->vhsemail;
    }

    $name = $allgSettings->vhsname;

    return array('email' => $email, 'name' => $name);
  }

  private static function _isEmailValid($pEmail)
  {
    $validate = ValidierungBasis::getInstance();

    return (trim($pEmail) !== '' && $validate->isValidVar('email', $pEmail) === true);
  }

  
  public static function getTotalData($pDefault = '', $pToolId = false, $pTotalDataStr = 'totaldatastr_')
  {
    $toolId = $pToolId;
    if ($toolId === false) {
      $toolId = self::getCurrentToolId();
    }
    $string = SessionOperations::getVarValueWTIntern($pTotalDataStr . $toolId, $pDefault);
    if (StringOperations::strpos($string, ':') !== false) {
      return explode(':', $string);
    } else {
      return array($string);
    }
  }

  
  public static function setTotalData($pData, $pToolId = false)
  {
    $toolId = $pToolId;
    if ($toolId === false) {
      $toolId = self::getCurrentToolId();
    }
    if (!is_array($pData)) {
      SessionOperations::setVarValueWTIntern('totaldatastr_' . $toolId, $pData);
    } else {
      SessionOperations::setVarValueWTIntern('totaldatastr_' . $toolId, implode(':', $pData));
    }
  }

  
  public static function setHistoryEntry()
  {
    
    if (GetOperations::isDefined('nohistory')) {
      return;
    }

    $history = SessionOperations::getVarValueWTIntern('history', array());
    $getHistory = GetOperations::getVarValue('history', 'X');

    
    
    
    
    
    $excludeParams = array('wb__already__decoded'
      
    );

    $url = '';
    foreach ($_GET as $key => $value) {
      if (!in_array($key, $excludeParams)) {
        if (is_array($value)) {
          foreach ($value as $arVal) {
            $url .= '&' . $key . '[]=' . $arVal;
          }
        } else {
          $url .= "&$key=$value";
        }
      }
    }
    if (StringOperations::strlen($url) > 0) { 
      $url = StringOperations::substr($url, 1);

      
      
      
      

      
      
      $urlObj = new URL(URL::loadCurrent()->getUrlFull(true, false, false) . '?' . $url);
      foreach ($urlObj->getAllParameters() as $parameter => $value) {
        $s = new StringObj($parameter);
        if ($s->endsWith('_nohistory')) {
          $urlObj->removeParameter($parameter);
        }
      }

      
      $str = new StringObj();
      foreach ($urlObj->getAllParameters() as $parameter => $value) {
        if (is_array($value)) {
          foreach ($value as $arVal) {
            $str->add('&' . $parameter . '=' . $arVal);
          }
        } else {
          $str->add('&' . $parameter . '=' . $value);
        }
      }
      $url = $str->removeFirstChars(1)->toString();
    }

    
    $lastUrl = '-1';
    if (count($history) > 0) {
      $lastUrl = $history[count($history) - 1];
    }

    $urlObj = new URL(URL::loadCurrent()->getUrlFull(true, false, false) . '?' . $url);
    $lastUrlObj = new URL(URL::loadCurrent()->getUrlFull(true, false, false) . '?' . $lastUrl);

    
    if (is_numeric($getHistory) && count($history) > $getHistory) {
      
      
      if (!$urlObj->hasSameParameters($lastUrlObj)) {
        for ($i = 0; $i < $getHistory; $i++) {
          array_pop($history);
        }
        SessionOperations::setVarValueWTIntern('history', $history);
      }

      return;
    }

    
    if (GetOperations::isDefined('einstieg')) {
      $history = array();
    }

    
    
    if (($urlObj->hasParameter('showFormular') && $urlObj->getParameterValue('showFormular') == 'bescheinigung')
            || $urlObj->hasParameter('sendInfo')) {
      return;
    }

    
    
    
    if (!$urlObj->hasParameter('showFormular') && !$urlObj->hasParameter('showAbmeldung')) {
      
      $excludedParams = array('currentIndex', 'markerAction');
      
      if ($urlObj->getParameterValue('tool_id') == 18) {
        $excludedParams = array_merge($excludedParams, array('datum', 'ktid', 'action', 'nr', 'go_x', 'go_y'));
      }
      
      if ($urlObj->hasParameter('tool_id') == 5) {
        $excludedParams = array_merge($excludedParams, array('starttime', 'endtime', 'dateForm', 'showGraphic'));
      }
      $urlIdentical = $urlObj->hasSameParameters($lastUrlObj, $excludedParams);
      if ($urlIdentical) {
        array_pop($history);
      }
    }

    if ($lastUrl != $url) {
      $history[] = $url;
      SessionOperations::setVarValueWTIntern('history', $history);
    }
  }

  

  
  public static function getLastHistoryEntry()
  {
    return ToolsAPI::getHistoryEntry(1);
  }

  
  public static function getHistoryEntry($pBack)
  {
    $result = 'usertools.php';
    $history = SessionOperations::getVarValueWTIntern('history', array());
    if (count($history) > $pBack) {
      $result .= '?' . $history[count($history) - ($pBack + 1)];
      if (StringOperations::substr($result, -1, 1) !== '?') {
        $result .= '&';
      }
      $result .= 'history=' . $pBack;
    }

    return $result;
  }

  
  public static function findHistoryEntryWhereParameterNotExistsOrEqualsValue($pParameter, $pValue)
  {
    $ret = null;

    $history = SessionOperations::getVarValueWTIntern('history', array());

    foreach (array_reverse($history) as $historyEntry) {
      $urlstring = $historyEntry == '' ? 'http://www.mysite.de/usertools.php' : 'http://www.mysite.de/usertools.php?' . $historyEntry;
      $url = new URL($urlstring);

      if (!$url->hasParameter($pParameter)) {
        $ret = $historyEntry;
        break;
      }

      if ($url->getParameterValue($pParameter) == $pValue) {
        $ret = $historyEntry;
        break;
      }
    }

    return $ret;
  }

  
  public static function findLastHistoryEntryWhereParameterNotEqualsValue($pParameter, $pValue)
  {
    $ret = null;

    $history = SessionOperations::getVarValueWTIntern('history', array());

    foreach (array_reverse($history) as $historyEntry) {
      $urlstring = $historyEntry == '' ? 'http://www.mysite.de/usertools.php' : 'http://www.mysite.de/usertools.php?' . $historyEntry;
      $url = new URL($urlstring);

      if (!$url->hasParameter($pParameter)) {
        continue;
      }

      if ($url->getParameterValue($pParameter) != $pValue) {
        $ret = $historyEntry;
        break;
      }
    }

    return $ret;
  }

  
  public static function findLastHistoryEntryWhereParameterNotExistsOrNotEqualsValue($pParameter, $pValue, $pDepth = 1)
  {
    $ret = null;

    $history = SessionOperations::getVarValueWTIntern('history', array());
    $count = 0;
    foreach (array_reverse($history) as $historyEntry) {
      $urlstring = $historyEntry == '' ? 'http://www.mysite.de/usertools.php' : 'http://www.mysite.de/usertools.php?' . $historyEntry;
      $url = new URL($urlstring);

      if (!$url->hasParameter($pParameter)) {
        $ret = $historyEntry;
        break;
      }

      if ($url->getParameterValue($pParameter) != $pValue) {
        ++$count;
        if ($count == $pDepth) {
          $ret = $historyEntry;
          break;
        } else {
          $pValue = $url->getParameterValue($pParameter);
        }
      }
    }

    return $ret;
  }

  
  public static function findLastHistoryEntryWithoutParameter($pParameter)
  {
    $ret = null;

    $history = SessionOperations::getVarValueWTIntern('history', array());

    foreach (array_reverse($history) as $historyEntry) {
      $urlstring = $historyEntry == '' ? 'http://www.mysite.de/usertools.php' : 'http://www.mysite.de/usertools.php?' . $historyEntry;
      $url = new URL($urlstring);

      if (!$url->hasParameter($pParameter)) {
        $ret = $historyEntry;
        break;
      }
    }

    return $ret;
  }

  
  public static function getPreviousToolsectionLink($pDepth = 1)
  {
    $currentUrl = URL::loadCurrent();
    $currentUrl->setAllParameters(array());
    $currentUrl->setAnchor(null);
    

    $momentaneToolsectionId = RequestOperations::getVarValue('toolsection_id');

    $historyEntry = self::findLastHistoryEntryWhereParameterNotExistsOrNotEqualsValue('toolsection_id', $momentaneToolsectionId, $pDepth);

    if ($historyEntry) {
      $historyTemp = new URL('http://www.mysite.de/usertools.php?' . $historyEntry);

      $currentUrl->setAllParameters($historyTemp->getAllParameters());
      $currentUrl->setAnchor($historyTemp->getAnchor());
    }

    return $currentUrl->getUrlRelative();
  }

  
  public static function getPreviousToolsectionLinkWith($pToolsectionId)
  {
    if ($pToolsectionId == '') {
      throw new InvalidArgumentExceptionExtended('$pToolsectionId', $pToolsectionId, 'Der Parameter $pToolsectionId darf nicht null oder leer sein.');
    }

    if (!is_numeric($pToolsectionId)) {
      throw new InvalidArgumentExceptionExtended('$pToolsectionId', $pToolsectionId, 'Der Parameter $pToolsectionId muss numerisch sein.');
    }

    if ($pToolsectionId < 1) {
      throw new InvalidArgumentExceptionExtended('$pToolsectionId', $pToolsectionId, 'Der Parameter $pToolsectionId muss >= 1 sein.');
    }

    $currentUrl = URL::loadCurrent();
    $currentUrl->setAllParameters(array());
    $currentUrl->setAnchor(null);
    

    $historyEntry = self::findHistoryEntryWhereParameterNotExistsOrEqualsValue('toolsection_id', $pToolsectionId);

    if ($historyEntry) {
      $historyTemp = new URL('http://www.mysite.de/usertools.php?' . $historyEntry);

      $currentUrl->setAllParameters($historyTemp->getAllParameters());
      $currentUrl->setAnchor($historyTemp->getAnchor());
    }

    return $currentUrl->getUrlRelative();
  }

  
  public static function rechteAND($pRechteAry, $pToolId, $pCheckReadOnly = false)
  {
    if (SessionOperations::isAdmin()) {
      return true;
    }

    static $dbwSightsFields = null;
    if ($pCheckReadOnly && $dbwSightsFields === null) {
      $dbwSightsFields = new DBWorkSightsFields(1, true);
    }

    if (is_array($pRechteAry)) {
      $userId = SessionOperations::getUserIdentifier();
      foreach ($pRechteAry as $recht) {
        $readonly = false;
        if ($pCheckReadOnly) {
          $teilRechAry = explode('.', $recht);
          if (count($teilRechAry) == 2 && is_numeric($teilRechAry[0]) && is_numeric($teilRechAry[1])) {
            $field = $dbwSightsFields->getFieldBySightIdFieldId($teilRechAry[0], $teilRechAry[1]);
            $readonly = !$field->canedit;
          } 
        }

        if (\SecurityOperations::privilegAllowed($userId, $pToolId, $recht) != 2 || $readonly) {
          return false;
        }
      }
    }

    return true;
  }

  
  public static function rechteOR($pRechteAry, $pToolId, $pCheckReadOnly = false)
  {
    if (SessionOperations::isAdmin()) {
      return true;
    }

    static $dbwSightsFields = null;
    if ($pCheckReadOnly && $dbwSightsFields === null) {
      $dbwSightsFields = new DBWorkSightsFields(1, true);
    }

    if (is_array($pRechteAry)) {
      $userId = SessionOperations::getUserIdentifier();
      foreach ($pRechteAry as $recht) {
        $readonly = false;
        if ($pCheckReadOnly) {
          $teilRechAry = explode('.', $recht);
          if (count($teilRechAry) == 2 && is_numeric($teilRechAry[0]) && is_numeric($teilRechAry[1])) {
            $field = $dbwSightsFields->getFieldBySightIdFieldId($teilRechAry[0], $teilRechAry[1]);
            $readonly = !$field->canedit;
          } 
        }

        if (\SecurityOperations::privilegAllowed($userId, $pToolId, $recht) == 2 && !$readonly) {
          return true;
        }
      }
    }

    return false;
  }

  
  public static function hlGetUhrzeitHinterlegungsButton($pTyp, $pFieldID, $pMitJQ = false)
  {
    return
    '&nbsp;<a style="vertical-align: bottom; text-decoration: none;" href="#formular" '
    . 'onClick="window.open(\'hlindex.php?type=' . CleanOperations::cleanInt($pTyp) . '&amp;field=' . CleanOperations::cleanStringForJs($pFieldID) . ($pMitJQ ? '&amp;mitJQ=1' : '')
    . '\', \'_blank\', \'height=400, width=120, scrollbars=yes\');">' . "\n"
    . '<img border="0" src="layout/button_hinterlegung.gif" title="Hinterlegung öffnen"'
    . ' alt="Hinterlegung" />'
    . '</a>' . "\n";
  }

  
  public static function getJsFilterVorbereitung4Kurstage()
  {
    
    
    
    
    
    $result = 'registerNamespace("KuferTools.Filter");' . "\n";
    $result .= JsOperations::getDeclarationString('KuferTools.Filter.heute', DateTimeOperations::getDateByParam(0));
    $result .= JsOperations::getDeclarationString('KuferTools.Filter.morgen', DateTimeOperations::getDateByParam(1));
    $result .= JsOperations::getDeclarationString('KuferTools.Filter.diesewochevon', DateTimeOperations::getDateByParam(2));
    $result .= JsOperations::getDeclarationString('KuferTools.Filter.diesewochebis', DateTimeOperations::getDateByParam(3));
    $result .= JsOperations::getDeclarationString('KuferTools.Filter.naechstewochevon', DateTimeOperations::getDateByParam(4));
    $result .= JsOperations::getDeclarationString('KuferTools.Filter.naechstewochebis', DateTimeOperations::getDateByParam(5));
    $result .= JsOperations::getDeclarationString('KuferTools.Filter.diesermonatvon', DateTimeOperations::getDateByParam(6));
    $result .= JsOperations::getDeclarationString('KuferTools.Filter.diesermonatbis', DateTimeOperations::getDateByParam(7));
    $result .= JsOperations::getDeclarationString('KuferTools.Filter.naechstermonatvon', DateTimeOperations::getDateByParam(8));
    $result .= JsOperations::getDeclarationString('KuferTools.Filter.naechstermonatbis', DateTimeOperations::getDateByParam(9));

    return $result;
  }

  
  public static function getDataForCurrentPage($pTotalObjects, $pObjectsPerPage)
  {
    $count = 0;

    if (is_array($pTotalObjects)) {
      $count = count($pTotalObjects);
    } else {
      throw new Exception('Der Parameter $pTotalObjects muss ein Array sein!');
    }

    $currentIndex = 0;
    if ($pObjectsPerPage > 0 && $count > 0) {
      $maxIndex = ceil($count / $pObjectsPerPage) - 1;
      $currentIndex = RequestOperations::getVarValue('currentIndex', 1) - 1; 
      $currentIndex = $currentIndex < 0 ? 0 : $currentIndex;
      $currentIndex = $currentIndex > $maxIndex ? $maxIndex : $currentIndex;
    }
    $offset = $currentIndex * $pObjectsPerPage;
    $length = $pObjectsPerPage;

    return array_slice($pTotalObjects, $offset, $length);
  }

  
  public static function getUrlParamsForFile($pParams, $pToolId, $pFile = 'usertools.php', $pAnchor = '')
  {
    $params = self::getUrlParams($pParams, $pToolId);

    return $pFile . ($params != '' ? '?' : '') . $params . ($pAnchor != '' ? '#' . urlencode($pAnchor) : '');
  }

  
  public static function getUrlParams($pParams, $pToolId)
  {
    if (!is_array($pParams)) {
      return '';
    }
    $result = '';
    if (!isset($pParams['tool_id'])) {
      $result .= '&tool_id=' . $pToolId;
    }
    foreach ($pParams as $name => $value) {
      if ($value != '') {
        $result .= "&$name=" . urlencode($value);
      }
    }

    return StringOperations::substr($result, 1);
  }

  
  public static function getPersonenMobilNummerArray($pPersonenAry)
  {
    $ret = array();

    $dbWorkKommunikation = new DBWorkKommunikation();
    $dbWorkKommunikation->allkom = true;

    foreach ($pPersonenAry as $person) {
      $tmp = array();

      
      $personenKommunikationAry = $dbWorkKommunikation->getKommunikationByNrTypArt($person->id, $person->getKommType(), 'M');

      $tmp[0] = $person;
      $tmp[1] = array();
      foreach ($personenKommunikationAry as $personenKommunikation) {
        $tmp[1][$personenKommunikation->wert] = false; 
      }

      $ret[] = $tmp;
    }

    return $ret;
  }

  

  
  public static function buildValidLink($pLink, $pAddUrlStr = '')
  {
    
    
    $linkOhneAnchor = $pLink;
    $anchor = '';
    if (StringOperations::strpos($pLink, '#') != false) {
      $linkParts = explode('#', $pLink);
      $linkOhneAnchor = $linkParts[0];
      $anchor = $linkParts[1];
    }

    
    $url = new URL($linkOhneAnchor . $pAddUrlStr);
    
    if ($anchor != '') {
      $url->setAnchor($anchor);
    }
    
    $url->cleanParameter();
    
    return $url->getUrlRelative();
  }

  
  public static function getTabsAry($pToolId, \Kufer\Web\Classes\Identifier\Identifier $pUserId, $pPageId)
  {
    $tabsAry = array();

    $toolSettings = ToolSettingsAPI::getToolSettings($pToolId);
    
    isset($toolSettings->reiterBeschriftung) ?: $toolSettings->reiterBeschriftung = '';
    $reiterSeite = new ReiterSeite($pPageId, $toolSettings->reiterBeschriftung);
    
    $reiterKeyAry = $reiterSeite->getReiterKeysAry();

    $cntReiter = count($reiterKeyAry);

    $tabCntr = 1;
    for ($i = 0;$i < $cntReiter; $i++) {
      $tabname = $reiterKeyAry[$i];
      $reiterRecht = $reiterSeite->getRecht($tabname);

      
      
      if (\SecurityOperations::privilegAllowed($pUserId, $pToolId, $reiterRecht)) {
        $tabsAry[$tabname] = 'tabs-' . $tabCntr;
        $tabCntr++;
      }
    }

    
    return $tabsAry;
  }

  

  
  public static function getVorbelegungDatumVonBis($pToolId, $pIsKursKopie = false)
  {
    $prefix = '';
    if ($pIsKursKopie) {
      $prefix .= 'kurskopie_';
    }
    $toolSettings = ToolSettingsAPI::getToolSettings($pToolId);
    $result = array('von' => '', 'bis' => '');

    $aktuellesDatum = DateTimeOperations::getDateNow();
    
    if ($toolSettings->{$prefix . 'kursFilterKursbeginnVorbelegen'} === 'T' || ($toolSettings->{$prefix . 'kursFilterKursbeginnVorbelegen'} === false && $toolSettings->{$prefix . 'kursFilterVorbelegen'})) {
      if (($toolSettings->{$prefix . 'kursBegVon'}) !== '') {
        $result['von'] = DateTimeOperations::getNextDate($aktuellesDatum, $toolSettings->{$prefix . 'kursBegVon'});
      }
      if (($toolSettings->{$prefix . 'kursBegBis'}) !== '') {
        $result['bis'] = DateTimeOperations::getNextDate($aktuellesDatum, $toolSettings->{$prefix . 'kursBegBis'});
      }
    }
    
    elseif ($toolSettings->{$prefix . 'kursFilterKursbeginnVorbelegen'} === 'M') {
      if (isset($toolSettings->{$prefix . 'kursBegMonatVon'}) || empty($toolSettings->{$prefix . 'kursBegMonatVon'})) {
        $result['von'] = DateTimeOperations::changeMonth($aktuellesDatum, $toolSettings->{$prefix . 'kursBegMonatVon'}, true);
      }
      if (empty($toolSettings->{$prefix . 'kursBegMonatBis'})) {
        $result['bis'] = date('t.m.Y');
      } elseif (!empty($toolSettings->{$prefix . 'kursBegMonatBis'})) {
        $result['bis'] = DateTimeOperations::changeMonth($aktuellesDatum, $toolSettings->{$prefix . 'kursBegMonatBis'}, false);
      }
    }

    return $result;
  }

  
  public static function getUserUserGroups(\Benutzer $user): array
  {
    $return = array();
    if ($user->isEmpty()) {
      throw new Exception('Es ist momentan kein User eingeloggt.');
    }
    if ($user->tnr != -1) {
      $return[] = 'Teilnehmer';
    }
    if ($user->dnr != -1) {
      $return[] = 'Dozent';
    }
    if ($user->anr != -1) {
      $return[] = 'Hausmeister';
    }
    if ($user->ben != -1) {
      $return[] = 'Mitarbeiter';
    }
    if ($user->isAdmin()) {
      $return[] = 'Admin';
    }

    return $return;
  }

  
  public static function getPersonFromUser(\Benutzer $user, $pRefreshCache = false): ?\Personn
  {
    $usergroups = self::getUserUserGroups($user);
    if (empty($usergroups)) {
      return null;
    }

    switch ($usergroups[0]) {
      default: return null;
      case 'Dozent':
        $dbwDozenten = new \DBWorkDozenten();

        return $dbwDozenten->getDozent($user->getDnrIdentifier(), $pRefreshCache);
      case 'Teilnehmer':
        $dbwTeilnehmer = new DBWorkTeilnehmer();

        return $dbwTeilnehmer->getTeilnehm($user->getTnrIdentifier(), $pRefreshCache);
      case 'Hausmeister':
        $dbwHausmeister = new DBWorkAdresse();

        return $dbwHausmeister->getAdresse($user->getAnrIdentifier(), $pRefreshCache);
      case 'Mitarbeiter':
        $dbwMitarbeiter = new DBWorkBASysUser();

        return $dbwMitarbeiter->getBASysUser($user->getBenIdentifier());
    }
  }

  
  public static function getBezeichnungSingularForKurzBez(string $kurzbez): string
  {
    $sprachSettings = \SettingsFactory::getSettings(SprachSettingsObject::class);
    switch ($kurzbez) {
      default: throw new \InvalidArgumentException("$kurzbez hier nicht erwartet");
      case KURZ_FIRMA:
        return 'Firma';
      case KURZ_DOZENT:
        return $sprachSettings->Dozent['Singular']['Nominativ'];
      case KURZ_TEILNEHMER:
        return $sprachSettings->Teilnehmer['Singular']['Nominativ'];
      case KURZ_HAUSMEISTER:
        return 'HausmeisterIn';
      case KURZ_MITARBEITER:
        return 'MitarbeiterIn';
      case KURZ_VERANSTALTER:
        return 'VeranstalterIn';
    }
  }

  public static function getSuffixForKurzBez(string $kurzbez): string
  {
    return '(' . static::getBezeichnungSingularForKurzBez($kurzbez) . ')';
  }

  public static function getMenuTitleWithSuffix(int $toolId): string
  {
    switch ($toolId) {
      default:
        return static::getMenuTitle($toolId);
        
      case static::TOOL_KURSUEBERSICHT_DOZ:
        
      case static::TOOL_KURSPLANUNG_DOZ:
        
      case static::TOOL_LEHRPLAN_DOZ:
        
      case static::TOOL_VERTRAG_DOZ:
        
      case static::TOOL_KURSBEWERBUNG_DOZ:
        
      case static::TOOL_ANWESENHEIT_DOZ:
        return static::getMenuTitle($toolId) . ' ' . static::getSuffixForKurzBez(KURZ_DOZENT);

        
      case static::TOOL_KURSUEBERSICHT_TN:
      case static::TOOL_TN:
        
      case static::TOOL_ANMELDUNGBUCHEN_TN:
        
      case static::TOOL_PUNKTE_TN:
        return static::getMenuTitle($toolId) . ' ' . static::getSuffixForKurzBez(KURZ_TEILNEHMER);

        
      case static::TOOL_ANMELDUNGBUCHEN_MA:
        
      case static::TOOL_KURSPLANUNG_MA:
        
      case static::TOOL_TEILNEHMERINFO_MA:
        
      case static::TOOL_KURSUEBERSICHT_MA:
        
      case static::TOOL_DOZENTENINFO_MA:
        
      case static::TOOL_ADRESSINFO_MA:
        
      case static::TOOL_RAUMBELEGUNG_MA:
        
      case static::TOOL_KURSVORSCHLAG_MA:
        return static::getMenuTitle($toolId) . ' ' . static::getSuffixForKurzBez(KURZ_MITARBEITER);

        
      case static::TOOL_RAUMBELEGUNG_HM:
        
      case static::TOOL_KURSUEBERSICHT_HM:
        return static::getMenuTitle($toolId) . ' ' . static::getSuffixForKurzBez(KURZ_HAUSMEISTER);

        
      case static::TOOL_KURSUEBERSICHT_VA:
        
      case static::TOOL_KURSVORSCHLAG_VA:
        return static::getMenuTitle($toolId) . ' ' . static::getSuffixForKurzBez(KURZ_VERANSTALTER);
    }
  }

  
  public static function getMenuTitle(int $toolId): string
  {
    switch ($toolId) {
      default:
        throw new \InvalidArgumentException("Tool $toolId hier nicht berücksichtigt");
        
      case static::TOOL_KURSUEBERSICHT_DOZ:
        return 'meine Kurse';
        
      case static::TOOL_KURSPLANUNG_DOZ:
        return 'Kursplanung';
        
      case static::TOOL_LEHRPLAN_DOZ:
        return 'Lehrplan';
        
      case static::TOOL_VERTRAG_DOZ:
        return 'Vertr&auml;ge';
        
      case static::TOOL_KURSBEWERBUNG_DOZ:
        return 'Kursbewerbung';
        
      case static::TOOL_KURSUEBERSICHT_TN:
        return 'gebuchte Kurse';
        
      case static::TOOL_ANMELDUNGBUCHEN_MA:
        return 'Anmeldung';
        
      case static::TOOL_KURSPLANUNG_MA:
        return 'Kurse';
        
      case static::TOOL_TEILNEHMERINFO_MA:
        return 'Teilnehmerinfo';
        
      case static::TOOL_ANMELDUNGBUCHEN_TN:
        return 'Neue Anmeldung';
        
      case static::TOOL_KURSUEBERSICHT_MA:
        return 'Kurs&uuml;bersicht';
        
      case static::TOOL_RAUMBELEGUNG_HM:
        return 'Raumbelegung';
        
      case static::TOOL_ANWESENHEIT_DOZ:
        return 'Anwesenheiten';
        
      case static::TOOL_TWITTER:
        return 'Twitter';
        
      case static::TOOL_AKTUELLES:
        return 'aktuelle Nachrichten';
        
      case static::TOOL_DOZENTENINFO_MA:
        return 'Dozenteninfo';
        
      case static::TOOL_PERSDATA:
        return 'Pers&ouml;nliche Daten';
        
      case static::TOOL_RAUMANZEIGE:
        return 'was ist heute wo';
        
      case static::TOOL_TN:
        return 'meine Kurse';
        
      case static::TOOL_KURSUEBERSICHT_FA:
        return 'belegte Kurse';
        
      case static::TOOL_MITARBEITERUEBERSICHT_FA:
        return 'angemeldete Mitarbeiter';
        
      case static::TOOL_NACHRICHT_AN_EINRICHTUNG:
        return 'Nachricht an Einrichtung';
        
      case static::TOOL_ANMELDUNGBUCHEN_FA:
        return 'neue Anmeldung';
        
      case static::TOOL_KURSVORSCHLAG_TN:
        return 'Kursvorschlag';
        
      case static::TOOL_PUNKTE_TN:
        return 'Zertifikatsinformationen';
      case static::TOOL_MOB_FEEDBACK:
        return 'Feedback';
        
      case static::TOOL_KURSUEBERSICHT_HM:
        return 'Kursübersicht';
        
      case static::TOOL_ADRESSINFO_MA:
        return 'Adressinfo';
        
      case static::TOOL_RAUMBELEGUNG_MA:
        return 'Raumbelegung';
        
      case static::TOOL_RAUMRESERVIERUNG_HM:
        return 'Raumreservierung';
        
      case static::TOOL_VORGESETZTER_TN:
        return 'Vorgesetztenübersicht';
      case static::TOOL_PORTRAIT_DOZ:
        return 'Dozentenportrait';
      case static::TOOL_HONORAR_DOZ:
        return 'Honorarabrechnung';
        
      case static::TOOL_FACH_VERTRAG_DOZ:
        return 'Verträge';
        
      case static::TOOL_WEBVISITENKARTEN:
        return 'Webvisitenkarten';
        
      case static::TOOL_KURSVORSCHLAG_MA:
        return 'Kursvorschlag';
      case 42:
        return 'Teilnehmerübersicht';
      case 43:
        return 'Anmeldungen';
      case 44:
        return 'Dashboard';
      case 45:
        return 'Bayerischer Apothekertag';
      case 46:
        return 'Bayerischer Apothekertag';
      case 47:
        return 'Bayerischer Apothekertag';
      case 48:
        return 'Bayerischer Apothekertag';
      case 49:
        return 'Feedback-Auswertung';
      case 50:
        return 'Feedback-Auswertung';
      case 51:
        return 'Kursübersicht';
      case 52:
        return 'Kursvorschlag';
      case 53:
        return 'Anmeldung';
      case 54:
        return 'Kurse anderer Veranstalter';
      case 55:
        return 'Dozenteninfo';
      case 56:
        return 'Mein Veranstalter';
      case 57:
        return 'Frei definierbarer Menüpunkt';
      case 58:
        return 'Teilnehmerinfo';
      case 59:
        return 'Dokumente';
      case 60:
        return 'Leiter und Mitarbeiter anderer Veranstalter';
      case 61:
        return 'Kurse der Mitarbeiter';
      case 62:
        return 'Dokumente';
      case \ToolsAPI::TOOL_FEEDBACK_AUSWERTUNGEN_FA:
        return 'Feedback-Auswertung';
      case \ToolsAPI::TOOL_DOKUMENTE_FA:
        return 'Dokumente';
      case \ToolsAPI::TOOL_DOKUMENTE_TN:
        return 'Dokumente';
      case 66:
        return 'Raumreservierung';
      case 67:
        return 'Anmeldungen genehmigen';
      case \ToolsAPI::TOOL_DOZ_WUNSCHTERMINE:
        return 'Wunschtermine';
      case \ToolsAPI::TOOL_DOZ_URLAUBE:
        return 'Urlaube';
      case \ToolsAPI::TOOL_DOZ_SAMMELVERTRAEGE:
        return 'Sammelverträge';
      case \ToolsAPI::TOOL_WEBBASYS:
        return KUFERWEB;
    }
  }

  
  public static function getBezeichnungPluralForKurzBez(string $kurzbez): string
  {
    $sprachSettings = \SettingsFactory::getSettings(SprachSettingsObject::class);
    switch ($kurzbez) {
      default: throw new \InvalidArgumentException("$kurzbez hier nicht erwartet");
      case KURZ_FIRMA:
        return 'Firmen';
      case KURZ_DOZENT:
        return $sprachSettings->Dozent['Plural']['Nominativ'];
      case KURZ_TEILNEHMER:
        return $sprachSettings->Teilnehmer['Plural']['Nominativ'];
      case KURZ_HAUSMEISTER:
        return 'HausmeisterInnen';
      case KURZ_MITARBEITER:
        return 'MitarbeiterInnen';
      case KURZ_VERANSTALTER:
        return 'VeranstalterInnen';
    }
  }
}