text:
<?php

// include class.secure.php to protect this file and the whole CMS!
if (defined('WB_PATH')) {
  if (defined('LEPTON_VERSION'))
    include(WB_PATH.'/framework/class.secure.php');
}
else {
  $oneback = "../";
  $root = $oneback;
  $level = 1;
  while (($level < 10) && (!file_exists($root.'/framework/class.secure.php'))) {
    $root .= $oneback;
    $level += 1;
  }
  if (file_exists($root.'/framework/class.secure.php')) {
    include($root.'/framework/class.secure.php');
  }
  else {
    trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
  }
}
// end include class.secure.php

require_once (WB_PATH . '/modules/' . basename(dirname(__FILE__)) . '/initialize.php');
require_once (WB_PATH . '/include/captcha/captcha.php');
require_once (WB_PATH . '/modules/kit_form/class.frontend.php');

class marketFrontend {

  const request_main_action = 'rma';
  const request_account_action = 'raa';
  const request_market_action = 'mar';

  const action_market = 'mar';
  const action_account = 'acc';
  const action_category = 'cat';
  const action_default = 'def';
  const action_check_form = 'acf';
  const action_login = 'alo';
  const action_overview = 'ove';
  const action_logout = 'out';
  const action_advertisement = 'ad';
  const action_advertisement_add = 'aaa';
  const action_advertisement_check = 'aaac';

  const session_temp_vars = 'mtv';

  private $page_link = '';
  private $img_url = '';
  private $template_path = '';
  private $error = '';
  private $message = '';
  private $media_path = '';
  private $media_url = '';
  private $use_lepton_auth = false; // Authentication via LEPTON user interface

  const param_preset = 'preset';
  const param_lepton_groups = 'lepton_groups';
  const param_switch = 'switch';

  private $params = array(
    self::param_preset => 1,
    self::param_lepton_groups => '',
    self::param_switch => ''
  );

  private $tab_main_navigation_array = array(
    self::action_market => market_tab_market,
    self::action_account => market_tab_account
  );

  private $tab_account_navigation_array = array(
    self::action_overview => market_tab_overview,
    self::action_advertisement_add => market_tab_new_advertisement,
    self::action_account => market_tab_account,
    self::action_logout => market_tab_logout
  );

  protected $switchKITidea = false;

  public function __construct() {
    global $kitLibrary;
    global $dbMarketCfg;
    $url = '';
    $_SESSION['FRONTEND'] = true;
    $kitLibrary->getPageLinkByPageID(PAGE_ID, $url);
    $this->page_link = $url;
    $this->template_path = WB_PATH . '/modules/' . basename(dirname(__FILE__)) . '/htt/' . $this->params[self::param_preset] . '/' . KIT_MARKET_LANGUAGE . '/';
    $this->img_url = WB_URL . '/modules/' . basename(dirname(__FILE__)) . '/images/';
    date_default_timezone_set(tool_cfg_time_zone);
    $this->media_path = WB_PATH . MEDIA_DIRECTORY . '/' . $dbMarketCfg->getValue(dbMarketCfg::cfgAdImageDir) . '/';
    $this->media_url = str_replace(WB_PATH, WB_URL, $this->media_path);
  } // __construct()

  public function getParams() {
    return $this->params;
  } // getParams()

  public function setParams($params = array()) {
    global $database;

    $this->params = $params;
    $this->template_path = WB_PATH . '/modules/' . basename(dirname(__FILE__)) . '/htt/' . $this->params[self::param_preset] . '/' . KIT_MARKET_LANGUAGE . '/';
    if (!file_exists($this->template_path)) {
      $this->setError(sprintf(form_error_preset_not_exists, '/modules/' . basename(dirname(__FILE__)) . '/htt/' . $this->params[self::param_preset] . '/' . KIT_MARKET_LANGUAGE . '/'));
      return false;
    }
    // if LEPTON group is set, authenticate via LEPTON USER
    if (!empty($this->params[self::param_lepton_groups])) {
      $gs = explode(',', $this->params[self::param_lepton_groups]);
      $grps = array();
      foreach ($gs as $g) {
        $g = trim($g);
        if (!empty($g)) {
          echo "g:$g";
          $SQL = sprintf("SELECT group_id FROM %sgroups WHERE name='%s'", TABLE_PREFIX, trim($g));
          if (false === ($id = $database->get_one($SQL))) {
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(market_error_lepton_group_invalid, $g)));
            return false;
          }
          $grps[] = $id;
          $this->use_lepton_auth = true;
        }
      }
      $this->params[self::param_lepton_groups] = implode(',', $grps);
    }
    else {
      $this->use_lepton_auth = false;
    }
    // if SWITCH is set check for specials...
    if (!empty($this->params[self::param_switch])) {
      $sw = explode(',', $this->params[self::param_switch]);
      if (in_array('kit_idea', $sw) || in_array('kitidea', $sw)) {
        // set switch for kitIdea
        $this->setSwitchKITidea(true);
      }
    }
    return true;
  } // setParams()

  /**
   *
   * @return the $switchKITidea
   */
  protected function getSwitchKITidea() {
    return $this->switchKITidea;
  }

  /**
   *
   * @param boolean $switchKITidea
   */
  protected function setSwitchKITidea($switchKITidea) {
    $this->switchKITidea = $switchKITidea;
  }

  /**
   * Set $this->error to $error
   *
   * @param STR $error
   */
  public function setError($error) {
    $this->error = $error;
  } // setError()

  /**
   * Get Error from $this->error;
   *
   * @return STR $this->error
   */
  public function getError() {
    return $this->error;
  } // getError()

  /**
   * Check if $this->error is empty
   *
   * @return BOOL
   */
  public function isError() {
    return (bool) !empty($this->error);
  } // isError

  /**
   * Reset Error to empty String
   */
  public function clearError() {
    $this->error = '';
  }

  /**
   * Set $this->message to $message
   *
   * @param STR $message
   */
  public function setMessage($message) {
    $this->message = $message;
  } // setMessage()

  /**
   * Get Message from $this->message;
   *
   * @return STR $this->message
   */
  public function getMessage() {
    return $this->message;
  } // getMessage()

  /**
   * Check if $this->message is empty
   *
   * @return BOOL
   */
  public function isMessage() {
    return (bool) !empty($this->message);
  } // isMessage

  /**
   * Gibt das gewuenschte Template zurueck
   *
   * @param STR $template
   * @param ARRAY $template_data
   */
  public function getTemplate($template, $template_data) {
    global $parser;
    try {
      $result = $parser->get($this->template_path . $template, $template_data);
    } catch (Exception $e) {
      $this->setError(sprintf(form_error_template_error, $template, $e->getMessage()));
      return false;
    }
    return $result;
  } // getTemplate()

  private function setTempVars($vars = array()) {
    $_SESSION[self::session_temp_vars] = http_build_query($vars);
  } // setTempVars()

  private function getTempVars() {
    if (isset($_SESSION[self::session_temp_vars])) {
      parse_str($_SESSION[self::session_temp_vars], $vars);
      foreach ($vars as $key => $value) {
        if (!isset($_REQUEST[$key])) $_REQUEST[$key] = $value;
      }
      unset($_SESSION[self::session_temp_vars]);
    }
  } // getTempVars()

  private function createFileName($filename, $extension, $width, $height) {
    $filename = page_filename($filename);
    return sprintf('%s_%d_%d.%s', $filename, $width, $height, $extension);
  } //

  private function createTweakedFile($filename, $extension, $file_path, $new_width, $new_height, $origin_width, $origin_height) {
    switch ($extension) :
      case 'gif' :
        $origin_image = imagecreatefromgif($file_path);
        break;
      case 'jpeg' :
      case 'jpg' :
        $origin_image = imagecreatefromjpeg($file_path);
        break;
      case 'png' :
        $origin_image = imagecreatefrompng($file_path);
        break;
      default :
        // unsupported image type
        return false;
    endswitch
    ;

    // create new image of $new_width and $new_height
    $new_image = imagecreatetruecolor($new_width, $new_height);
    // Check if this image is PNG or GIF, then set if Transparent
    if (($extension == 'gif') or ($extension == 'png')) {
      imagealphablending($new_image, false);
      imagesavealpha($new_image, true);
      $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
      imagefilledrectangle($new_image, 0, 0, $new_width, $new_height, $transparent);
    }
    imagecopyresampled($new_image, $origin_image, 0, 0, 0, 0, $new_width, $new_height, $origin_width, $origin_height);

    $new_file = $this->createFileName($filename, $extension, $new_width, $new_height);
    $new_file = dirname($file_path) . '/' . $new_file;
    // Generate the file, and rename it to $newfilename
    switch ($extension) :
      case 'gif' :
        imagegif($new_image, $new_file);
        break;
      case 'jpg' :
      case 'jpeg' :
        imagejpeg($new_image, $new_file);
        break;
      case 'png' :
        imagepng($new_image, $new_file);
        break;
      default :
        // unsupported image type
        return false;
    endswitch
    ;
    if (!chmod($new_file, 0755)) {
      $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_chmod, basename($new_file))));
    }
    return $new_file;
  } // createTweakedFile()

  /**
   * Verhindert XSS Cross Site Scripting
   *
   * @param
   *          REFERENCE ARRAY $request
   * @return ARRAY $request
   */
  public function xssPrevent(&$request) {
    if (is_string($request)) {
      $request = html_entity_decode($request);
      $request = strip_tags($request);
      $request = trim($request);
      $request = stripslashes($request);
    }
    return $request;
  } // xssPrevent()

  /**
   * GENERELLER ACTION HANDLER FUER DEN MARKTPLATZ
   *
   * @return STR result
   */
  public function action() {
    // temporaere Variablen in $_REQUESTs umschreiben...
    $this->getTempVars();

    $html_allowed = array();
    foreach ($_REQUEST as $key => $value) {
      if (!in_array($key, $html_allowed)) {
        $_REQUEST[$key] = $this->xssPrevent($value);
      }
    }
    $action = isset($_REQUEST[self::request_main_action]) ? $_REQUEST[self::request_main_action] : self::action_default;

    switch ($action) :
      case self::action_account :
        // Zum persoenlichen KONTO wechseln
        return $this->show_main(self::action_account, $this->accountAction());
      case self::action_default :
      default :
        // Anzeige des OEFFENTLICHEN MARKTPLATZ
        return $this->show_main(self::action_market, $this->marketAction());
    endswitch
    ;
  } // action

  /**
   * Ausgabe des formatierten Ergebnis mit Navigationsleiste
   * (Kleinanzeigen/Konto)
   *
   * @param STR $action - aktives Navigationselement
   * @param STR $content - Inhalt
   *
   * @return STR dialog
   */
  public function show_main($action, $content) {
    $navigation = array();
    foreach ($this->tab_main_navigation_array as $key => $value) {
      $navigation[] = array(
        'active' => ($key == $action) ? 1 : 0,
        'url' => sprintf('%s%s%s=%s', $this->page_link, (strpos($this->page_link, '?') === false) ? '?' : '&', self::request_main_action, $key),
        'text' => $value
      );
    }
    $data = array(
      'WB_URL' => WB_URL,
      'navigation' => $navigation,
      'error' => ($this->isError()) ? 1 : 0,
      'content' => ($this->isError()) ? $this->getError() : $content
    );
    return $this->getTemplate('body.htt', $data);
  } // show()

  /**
   * Action Handler fuer das KONTO DES BESUCHERS
   */
  public function accountAction() {
    global $kitContactInterface;

    $action = isset($_REQUEST[self::request_account_action]) ? $_REQUEST[self::request_account_action] : self::action_default;

    if (!$this->accountIsAuthenticated()) {
      $action = self::action_login;
    }

    switch ($action) :
      case self::action_logout :
        $kitContactInterface->logout();
      // wichtig: kein break, direkt den login Dialog anzeigen!
      case self::action_login :
        $this->setTempVars(array(
          self::request_main_action => self::action_account
        ));
        $result = $this->accountLoginDlg();
        // Login ist noch nicht erfolgreich
        if (is_string($result)) return $result;
        // Fehler ...
        if (is_bool($result) && ($result == false)) return false;
        // nach erfolgreichem Login die Uebersicht anzeigen
        return $this->accountShow(self::action_overview, $this->accountOverview());
      case self::action_account :
        return $this->accountShow(self::action_account, $this->accountAccountDlg());
      case self::action_advertisement_add :
        return $this->accountShow(self::action_advertisement_add, $this->accountAdvertisementAdd());
      case self::action_advertisement_check :
        return $this->accountShow(self::action_advertisement_add, $this->accountAdvertisementCheck());
      case self::action_default :
      default :
        return $this->accountShow(self::action_overview, $this->accountOverview());
    endswitch
    ;
  } // accountAction()

  /**
   * Ausgabe des formatierten Ergebnis mit Navigationsleiste (Konto)
   *
   * @param
   *          action - aktives Navigationselement
   * @param
   *          content - Inhalt
   *
   * @return ECHO RESULT
   */
  public function accountShow($action, $content) {
    $navigation = array();
    foreach ($this->tab_account_navigation_array as $key => $value) {
      if ($this->getSwitchKITidea() && (($key == self::action_account) || ($key == self::action_logout))) continue;
      $navigation[] = array(
        'active' => ($key == $action) ? 1 : 0,
        'url' => sprintf('%s%s%s', $this->page_link, (strpos($this->page_link, '?') === false) ? '?' : '&', http_build_query(array(
          self::request_main_action => self::action_account,
          self::request_account_action => $key
        ))),
        'text' => $value
      );
    }
    $data = array(
      'WB_URL' => WB_URL,
      'navigation' => $navigation,
      'error' => ($this->isError()) ? 1 : 0,
      'content' => ($this->isError()) ? $this->getError() : $content
    );
    return $this->getTemplate('body.account.htt', $data);
  } // accountShow()

  private function accountIsAuthenticated() {
    global $kitContactInterface;
    global $dbMarketCfg;
    global $wb;
    global $dbRegister;
    global $database;

    if ($this->use_lepton_auth && $wb->is_authenticated()) {
      // authenticate via LEPTON
      if (!isset($_SESSION['GROUPS_ID']) || empty($this->params[self::param_lepton_groups])) {
        $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, market_error_lepton_group_missing));
        return false;
      }
      // unset KIT session vars...
      unset($_SESSION[kitContactInterface::session_kit_aid]);
      unset($_SESSION[kitContactInterface::session_kit_key]);
      unset($_SESSION[kitContactInterface::session_kit_contact_id]);

      $lepton_groups = explode(',', $_SESSION['GROUPS_ID']);
      $market_groups = explode(',', $this->params[self::param_lepton_groups]);
      foreach ($lepton_groups as $lepton_group) {
        if (in_array($lepton_group, $market_groups)) {
          // ok - LEPTON user is authenticated, now switch him to KIT ...
          $contact_id = -1;
          $status = -1;
          $email = $_SESSION['EMAIL'];
          if (!$kitContactInterface->isEMailRegistered($email, $contact_id, $status)) {
            // Bugfixing, work around: clean up register records!
            $where = array(
              dbKITregister::field_email => $_SESSION['EMAIL']
            );
            if (!$dbRegister->sqlDeleteRecord($where)) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $dbRegister->getError()));
              return false;
            }
            // user must be registered in KIT
            $contact_array = array();
            $contact_array[kitContactInterface::kit_email] = $_SESSION['EMAIL'];
            $contact_array[kitContactInterface::kit_intern] = $dbMarketCfg->getValue(dbMarketCfg::cfgKITcategory);
            $register = array();
            // insert contact
            if (!$kitContactInterface->addContact($contact_array, $contact_id, $register)) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $kitContactInterface->getError()));
              return false;
            }

            // update register record, set to active
            $where = array(
              dbKITregister::field_contact_id => $contact_id
            );
            $data = array(
              dbKITregister::field_status => dbKITregister::status_active,
              dbKITregister::field_register_confirmed => date('Y-m-d H:i:s'),
              dbKITregister::field_update_when => date('Y-m-d H:i:s'),
              dbKITregister::field_update_by => 'kitMarketPlace'
            );
            if (!$dbRegister->sqlUpdateRecord($data, $where)) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $dbRegister->getError()));
              return false;
            }
            // ok - login user via KIT
            $_SESSION[kitContactInterface::session_kit_aid] = $register[dbKITregister::field_id];
            $_SESSION[kitContactInterface::session_kit_key] = $register[dbKITregister::field_register_key];
            $_SESSION[kitContactInterface::session_kit_contact_id] = $register[dbKITregister::field_contact_id];
            return true;
          }
          else {
            // user is registered in KIT
            $where = array(
              dbKITregister::field_contact_id => $contact_id,
              dbKITregister::field_status => dbKITregister::status_active
            );
            $register = array();
            if (!$dbRegister->sqlSelectRecord($where, $register)) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $dbRegister->getError()));
              return false;
            }
            if (count($register) < 1) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_id_invalid, $contact_id)));
              return false;
            }
            $register = end($register);
            $_SESSION[kitContactInterface::session_kit_aid] = $register[dbKITregister::field_id];
            $_SESSION[kitContactInterface::session_kit_key] = $register[dbKITregister::field_register_key];
            $_SESSION[kitContactInterface::session_kit_contact_id] = $register[dbKITregister::field_contact_id];
            return true;
          }
        }
      }
    }
    elseif ($kitContactInterface->isAuthenticated()) {
      // Pruefung der Kategorien
      $cat = $dbMarketCfg->getValue(dbMarketCfg::cfgKITcategory);
      if (!$kitContactInterface->existsCategory(kitContactInterface::category_type_intern, $cat)) {
        if (!$kitContactInterface->addCategory(kitContactInterface::category_type_intern, $cat, $cat)) {
          $this->setError(sprintf('[%s - %] %s', __METHOD__, __LINE__, $kitContactInterface->getError()));
          return false;
        }
      }
      $categories = array();
      if (!$kitContactInterface->getCategories($_SESSION[kitContactInterface::session_kit_contact_id], $categories)) {
        $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $kitContactInterface->getError()));
        return false;
      }
      if (in_array($cat, $categories)) {
        // ok - user is authenticated
        return true;
      }
      else {
        $this->setError(market_error_auth_wrong_category);
        return false;
      }
    }
    return false;
  } // accountIsAuthenticated()

  /**
   * Login Dialog fuer das Kundenkonto
   *
   * @return STR dialog BOOL on success or error
   */
  public function accountLoginDlg() {
    global $kitContactInterface;
    global $dbMarketCfg;

    $dlg = $dbMarketCfg->getValue(dbMarketCfg::cfgFormDlgLogin);

    $form = new formFrontend();
    $params = $form->getParams();
    $params['form'] = $dlg;
    $params['return'] = true;
    $form->setParams($params);

    $result = $form->action();
    if (is_string($result)) {
      return $result;
    }
    elseif (is_bool($result) && ($result == false) && $form->isError()) {
      $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $form->getError()));
      return false;
    }
    elseif (is_bool($result) && ($result == true)) {
      // return true;
      // user is logged in, now check if he is allowed to access kitMarketPlace
      return $this->accountIsAuthenticated();
    }
    else {
      $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, market_error_undefined));
      return false;
    }
  } // accountLoginDlg()

  public function accountAccountDlg() {
    global $kitContactInterface;
    global $dbMarketCfg;
    $this->setTempVars(array(
      self::request_main_action => self::action_account,
      self::request_account_action => self::action_account
    ));

    $dlg = $dbMarketCfg->getValue(dbMarketCfg::cfgFormDlgAccount);
    $form = new formFrontend();
    $params = $form->getParams();
    $params['form'] = $dlg;
    $params['return'] = true;
    $form->setParams($params);
    return $form->action();
  } // accountAccountDlg()

  public function accountAdvertisementAdd() {
    global $dbMarketAd;
    global $dbMarketCats;
    global $dbMarketCfg;
    global $kitLibrary;

    $ad_id = (isset($_REQUEST[dbMarketAdvertisement::field_id])) ? $_REQUEST[dbMarketAdvertisement::field_id] : -1;

    if ($ad_id > 0) {
      // Kleinanzeige auslesen
      $SQL = sprintf("SELECT * FROM %s WHERE %s='%s' AND %s!='%s'", $dbMarketAd->getTableName(), dbMarketAdvertisement::field_id, $ad_id, dbMarketAdvertisement::field_status, dbMarketAdvertisement::status_deleted);
      $ad = array();
      if (!$dbMarketAd->sqlExec($SQL, $ad)) {
        $this->setError($dbMarketAd->getError());
        return false;
      }
      if (count($ad) < 1) {
        $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_id_invalid, $ad_id)));
        return false;
      }
      $ad = $ad[0];
    }
    else {
      $ad = $dbMarketAd->getFields();
      $ad[dbMarketAdvertisement::field_id] = -1;
      $ad[dbMarketAdvertisement::field_category] = -1;
      $ad[dbMarketAdvertisement::field_status] = dbMarketAdvertisement::status_locked;
      $ad[dbMarketAdvertisement::field_kit_id] = $_SESSION[kitContactInterface::session_kit_contact_id];
      $ad[dbMarketAdvertisement::field_ad_type] = dbMarketAdvertisement::type_offer;
      $ad[dbMarketAdvertisement::field_commercial] = dbMarketAdvertisement::commercial_no;
      $ad[dbMarketAdvertisement::field_price_type] = dbMarketAdvertisement::price_asking;
    }

    foreach ($ad as $key => $value) {
      switch ($key) :
        default :
          if (isset($_REQUEST[$key])) $ad[$key] = $_REQUEST[$key];
      endswitch
      ;
    }

    // Kategorien auslesen
    $SQL = sprintf("SELECT * FROM %s WHERE %s='%s' ORDER BY %s, %s, %s, %s, %s ASC", $dbMarketCats->getTableName(), dbMarketCategories::field_status, dbMarketCategories::status_active, dbMarketCategories::field_level_01, dbMarketCategories::field_level_02, dbMarketCategories::field_level_03, dbMarketCategories::field_level_04, dbMarketCategories::field_level_05);
    $categories = array();
    if (!$dbMarketCats->sqlExec($SQL, $categories)) {
      $this->setError($dbMarketCats->getError());
      return false;
    }

    // Liste der Kategorien erstellen
    $category_list = array();
    $category_list[] = array(
      'text' => market_text_select,
      'value' => -1,
      'selected' => ($ad[dbMarketAdvertisement::field_category] == -1) ? 1 : 0
    );
    $category_check = array();
    foreach ($categories as $category) {
      $path = array();
      for($i = 1; $i < 6; $i++) {
        if (!empty($category[sprintf('cat_level_%02d', $i)])) $path[] = $category[sprintf('cat_level_%02d', $i)];
      }
      $path_str = implode(' > ', $path);
      if (!in_array($path_str, $category_check)) {
        $category_check[] = $path_str;
        $category_list[] = array(
          'text' => $path_str,
          'value' => $category[dbMarketCategories::field_id],
          'selected' => ($category[dbMarketCategories::field_id] == $ad[dbMarketAdvertisement::field_category]) ? 1 : 0
        );
      }
    }

    // Kleinanzeige TYP
    $ad_types = array();
    foreach ($dbMarketAd->type_array as $value => $text) {
      $ad_types[] = array(
        'text' => $text,
        'value' => $value,
        'selected' => ($value == $ad[dbMarketAdvertisement::field_ad_type]) ? 1 : 0
      );
    }

    // Gewerblich / Privat
    $commercial_array = array();
    foreach ($dbMarketAd->commercial_array as $value => $text) {
      $commercial_array[] = array(
        'text' => $text,
        'value' => $value,
        'selected' => ($value == $ad[dbMarketAdvertisement::field_commercial]) ? 1 : 0
      );
    }

    // Preis Typ
    $price_types = array();
    foreach ($dbMarketAd->price_array as $value => $text) {
      $price_types[] = array(
        'text' => $text,
        'value' => $value,
        'selected' => ($value == $ad[dbMarketAdvertisement::field_price_type]) ? 1 : 0
      );
    }

    $form = array(
      'name' => 'advertisement_add',
      'action' => array(
        'name' => self::request_main_action,
        'value' => self::action_account,
        'link' => $this->page_link
      ),
      'account' => array(
        'name' => self::request_account_action,
        'value' => self::action_advertisement_check
      ),
      'id' => array(
        'name' => dbMarketAdvertisement::field_id,
        'value' => $ad_id
      ),
      'title' => market_head_advertisement_add,
      'response' => array(
        'text' => ($this->isMessage()) ? $this->getMessage() : market_intro_advertisement_add,
        'is_message' => ($this->isMessage()) ? 1 : 0
      ),
      'btn' => array(
        'ok' => tool_btn_ok,
        'abort' => tool_btn_abort
      ),
      'header' => array(
        'id' => market_th_id,
        'kit_id' => market_th_kit_id,
        'category' => market_th_category,
        'type' => market_th_type,
        'commercial' => market_th_commercial,
        'title' => market_th_title,
        'price' => market_th_price,
        'price_type' => market_th_price_type,
        'pictures' => market_th_pictures,
        'text' => market_th_text,
        'status' => market_th_status,
        'start_date' => market_th_start_date,
        'end_date' => market_th_end_date,
        'timestamp' => market_th_timestamp
      )
    );

    $post_max_size = $kitLibrary->convertBytes(ini_get('post_max_size'));
    $upload_max_filesize = $kitLibrary->convertBytes(ini_get('upload_max_filesize'));
    $max_size = ($post_max_size >= $upload_max_filesize) ? $upload_max_filesize : $post_max_size;
    $max_size = $kitLibrary->bytes2Str($max_size);
    $max_images = $dbMarketCfg->getValue(dbMarketCfg::cfgAdMaxImages);
    $max_image_width = $dbMarketCfg->getValue(dbMarketCfg::cfgAdMaxImageWidth);
    $max_image_height = $dbMarketCfg->getValue(dbMarketCfg::cfgAdMaxImageHeight);
    $prev_width = $dbMarketCfg->getValue(dbMarketCfg::cfgAdImagePrevWidth);
    $file_types = implode(', ', $dbMarketCfg->getValue(dbMarketCfg::cfgAdImageTypes));
    $images = array();
    $pictures = (!empty($ad[dbMarketAdvertisement::field_pictures])) ? explode(',', $ad[dbMarketAdvertisement::field_pictures]) : array();

    $upl_path = $this->media_path . $ad[dbMarketAdvertisement::field_kit_id] . '/' . $ad[dbMarketAdvertisement::field_id] . '/';
    $upl_url = str_replace(WB_PATH, WB_URL, $upl_path);
    $prev_path = $upl_path . $prev_width . '/';
    $prev_url = str_replace(WB_PATH, WB_URL, $prev_path);

    $tmp_dir = $this->media_path . $ad[dbMarketAdvertisement::field_kit_id] . '/tmp/';

    foreach ($pictures as $picture) {
      if (!file_exists($upl_path . $picture)) {
        if (file_exists($tmp_dir . $picture)) {
          // Datei befindet sich noch im TEMP Verzeichnis, verschieben...
          if (!file_exists($upl_path)) {
            // Verzeichnis erstellen
            if (!mkdir($upl_path, 0755, true)) {
              $this->setError(sprintf('[%s - %s] %s', sprintf(tool_error_mkdir, $upl_path)));
              return false;
            }
          }
          if (!rename($tmp_dir . $picture, $upl_path . $picture)) {
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_move_file, $tmp_dir . $picture, $upl_path . $picture)));
            return false;
          }
        }
        else {
          // Datei nicht gefunden
          $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_missing_file, $upl_path . $picture)));
          return false;
        }
      }
      // Dateiinformationen
      $path_parts = pathinfo($upl_path . $picture);
      // Breite und Hoehe festhalten
      list($full_width, $full_height) = getimagesize($upl_path . $picture);
      // Vorschaubild pruefen
      if (!file_exists($prev_path . $picture)) {
        $factor = $prev_width / $full_width;
        $new_height = ceil($full_height * $factor);
        $new_width = ceil($full_width * $factor);
        if (false === ($new_file = $this->createTweakedFile($path_parts['filename'], $path_parts['extension'], $upl_path . $picture, $new_width, $new_height, $full_width, $full_height))) {
          $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_tweaking_file, $upl_path . $picture)));
          return false;
        }
        if (!file_exists($prev_path)) {
          if (!mkdir($prev_path, 0755, true)) {
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_mkdir, $prev_path)));
            return false;
          }
        }
        if (!rename($new_file, $prev_path . $picture)) {
          $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_move_file, $new_file, $prev_path . $picture)));
          return false;
        }
      }
      list($prev_width, $prev_height) = getimagesize($prev_path . $picture);
      $images[] = array(
        'fullsize' => array(
          'url' => $upl_url . $picture,
          'width' => $full_width,
          'height' => $full_height
        ),
        'preview' => array(
          'url' => $prev_url . $picture,
          'width' => $prev_width,
          'height' => $prev_height
        )
      );
    }
    $advertisement = array(
      'category' => array(
        'label' => market_label_adv_category,
        'name' => dbMarketAdvertisement::field_category,
        'values' => $category_list,
        'hint' => market_hint_adv_category
      ),
      'type' => array(
        'label' => market_label_adv_type,
        'name' => dbMarketAdvertisement::field_ad_type,
        'values' => $ad_types,
        'hint' => market_hint_adv_type
      ),
      'commercial' => array(
        'label' => market_label_adv_commercial,
        'name' => dbMarketAdvertisement::field_commercial,
        'values' => $commercial_array,
        'hint' => market_hint_adv_commercial
      ),
      'title' => array(
        'label' => market_label_adv_title,
        'name' => dbMarketAdvertisement::field_title,
        'value' => $ad[dbMarketAdvertisement::field_title],
        'hint' => market_hint_adv_title
      ),
      'text' => array(
        'label' => market_label_adv_text,
        'name' => dbMarketAdvertisement::field_text,
        'value' => $ad[dbMarketAdvertisement::field_text],
        'hint' => market_hint_adv_text
      ),
      'price' => array(
        'label' => market_label_adv_price,
        'name' => dbMarketAdvertisement::field_price,
        'value' => $ad[dbMarketAdvertisement::field_price],
        'hint' => market_hint_adv_price
      ),
      'price_type' => array(
        'label' => market_label_adv_price_type,
        'name' => dbMarketAdvertisement::field_price_type,
        'values' => $price_types,
        'hint' => market_hint_adv_price_type
      ),
      'image' => array(
        'label' => market_label_adv_image_upload,
        'name' => dbMarketAdvertisement::field_pictures,
        'values' => $images,
        'hint' => sprintf(market_hint_adv_image_size, $max_images, $max_size),
        'max_img' => $max_images,
        'max_size' => $max_size,
        'max_width' => $max_image_width,
        'max_height' => $max_image_height,
        'file_types' => $file_types
      ),
      'status' => array(
        'name' => dbMarketAdvertisement::field_status,
        'value' => array(
          'closed' => array(
            'value' => dbMarketAdvertisement::status_closed,
            'selected' => ($ad[dbMarketAdvertisement::field_status] == dbMarketAdvertisement::status_closed) ? 1 : 0
          )
        )
      )
    );
    $data = array(
      'form' => $form,
      'advertisement' => $advertisement
    );
    return $this->getTemplate('account.advertisement.add.htt', $data);
  } // accountAdvertisementAdd()

  public function accountAdvertisementCheck() {
    global $dbMarketAd;
    global $kitLibrary;
    global $dbMarketCfg;

    // pruefen ob die ID gesetzt ist
    if (!isset($_REQUEST[dbMarketAdvertisement::field_id])) {
      $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_request_missing, dbMarketAdvertisement::field_id)));
      return false;
    }
    $ad_id = $_REQUEST[dbMarketAdvertisement::field_id];

    // ID auslesen oder Default Werte setzen
    if ($ad_id > 0) {
      $where = array(
        dbMarketAdvertisement::field_id => $ad_id
      );
      $old_advertisement = array();
      if (!$dbMarketAd->sqlSelectRecord($where, $old_advertisement)) {
        $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $dbMarketAd->getError()));
        return false;
      }
      if (count($old_advertisement) < 1) {
        $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_id_invalid, $ad_id)));
        return false;
      }
      $old_advertisement = $old_advertisement[0];
    }
    else {
      // Default Werte fuer einen neuen Eintrag
      $old_advertisement = $dbMarketAd->getFields();
      $old_advertisement[dbMarketAdvertisement::field_kit_id] = $_SESSION[kitContactInterface::session_kit_contact_id];
      $old_advertisement[dbMarketAdvertisement::field_status] = dbMarketAdvertisement::status_locked;
      $old_advertisement[dbMarketAdvertisement::field_price_type] = dbMarketAdvertisement::price_asking;
    }

    $changed = false;
    $checked = true;
    $message = '';
    $new_advertisement = $old_advertisement;
    $publish_directly = $dbMarketCfg->getValue(dbMarketCfg::cfgAdPublishDirect);

    // Felder durchlaufen und pruefen
    foreach ($old_advertisement as $key => $value) {
      switch ($key) :
        case dbMarketAdvertisement::field_id :
        case dbMarketAdvertisement::field_start_date :
        case dbMarketAdvertisement::field_end_date :
        case dbMarketAdvertisement::field_timestamp :
        case dbMarketAdvertisement::field_pictures :
        case dbMarketAdvertisement::field_kit_id :
          // nichts tun, ueberspringen
          continue;
        case dbMarketAdvertisement::field_price :
          // Preisangabe pruefen
          if (!isset($_REQUEST[$key])) {
            // Feld muss gesetzt sein
            $message .= sprintf(market_msg_field_empty, $dbMarketAd->field_name_array[$key]);
            $checked = false;
          }
          else {
            // Preis TYP muss bereits gesetzt sein...
            $new_advertisement[dbMarketAdvertisement::field_price_type] = $_REQUEST[dbMarketAdvertisement::field_price_type];
            $price = $kitLibrary->str2float($_REQUEST[$key], tool_cfg_thousand_separator, tool_cfg_decimal_separator);
            if ($price < 0) $price = 0;
            if ($new_advertisement[dbMarketAdvertisement::field_price_type] == dbMarketAdvertisement::price_give_away) {
              $price = 0;
            }
            if (($price == 0) && ($new_advertisement[dbMarketAdvertisement::field_price_type] != dbMarketAdvertisement::price_give_away)) {
              $message .= market_msg_price_needed;
              $checked = false;
              break;
            }
            if ($price != $old_advertisement[$key]) {
              // Preis hat sich geaendert
              $changed = true;
              $new_advertisement[$key] = $price;
              break;
            }
            $new_advertisement[$key] = $price;
          }
          break;
        case dbMarketAdvertisement::field_category :
          if (!isset($_REQUEST[$key])) {
            // Feld muss gesetzt sein
            $message .= sprintf(market_msg_field_empty, $dbMarketAd->field_name_array[$key]);
            $checked = false;
          }
          elseif ($_REQUEST[$key] < 1) {
            $message .= market_msg_category_needed;
            $checked = false;
          }
          elseif ($_REQUEST[$key] != $old_advertisement[$key]) {
            $changed = true;
            $new_advertisement[$key] = $_REQUEST[$key];
          }
          else {
            $new_advertisement[$key] = $_REQUEST[$key];
          }
          break;
        case dbMarketAdvertisement::field_status :
          if (isset($_REQUEST[$key])) {
            $new_advertisement[$key] = dbMarketAdvertisement::status_closed;
            $changed = true;
          }
          break;
        default :
          // allgemeine Felder
          if (!isset($_REQUEST[$key]) || empty($_REQUEST[$key])) {
            // Feld muss gesetzt sein und darf nicht leer sein!
            $checked = false;
            $message .= sprintf(market_msg_field_empty, $dbMarketAd->field_name_array[$key]);
          }
          elseif ($_REQUEST[$key] != $old_advertisement[$key]) {
            $changed = true;
            $new_advertisement[$key] = $_REQUEST[$key];
          }
          else {
            $new_advertisement[$key] = $_REQUEST[$key];
          }
          break;
      endswitch
      ;
    }

    $pictures = (!empty($new_advertisement[dbMarketAdvertisement::field_pictures])) ? explode(',', $new_advertisement[dbMarketAdvertisement::field_pictures]) : array();
    // Pruefen, ob eine Datei uebertragen wurde...
    if (isset($_FILES[dbMarketAdvertisement::field_pictures]) && (is_uploaded_file($_FILES[dbMarketAdvertisement::field_pictures]['tmp_name']))) {
      if ($_FILES[dbMarketAdvertisement::field_pictures]['error'] == UPLOAD_ERR_OK) {
        $file_original = $_FILES[dbMarketAdvertisement::field_pictures]['name'];
        $tmp = explode('.', $file_original);
        $ext = strtolower(end($tmp));
        $allowed_filetypes = $dbMarketCfg->getValue(dbMarketCfg::cfgAdImageTypes);
        if (!in_array($ext, $allowed_filetypes)) {
          $exts = implode(', ', $allowed_filetypes);
          $message .= sprintf(market_msg_file_ext_not_allowed, $_FILES[dbMarketAdvertisement::field_pictures]['name'], $exts);
          @unlink($_FILES[dbMarketAdvertisement::field_pictures]['tmp_name']);
          $checked = false;
        }
        else {
          $tmp_file = $_FILES[dbMarketAdvertisement::field_pictures]['tmp_name'];
          $ad_dir = ($ad_id > 0) ? $ad_id : 'tmp';
          $upload_dir = $this->media_path . $_SESSION[kitContactInterface::session_kit_contact_id] . '/' . $ad_dir . '/';
          if (!file_exists($upload_dir)) {
            if (!mkdir($upload_dir, 0755, true)) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_mkdir, $upload_dir)));
              return false;
            }
          }

          $ufile = page_filename($_FILES[dbMarketAdvertisement::field_pictures]['name']);
          $upl_file = $upload_dir . $ufile;
          if (!move_uploaded_file($tmp_file, $upl_file)) {
            // error moving file
            $this->setError(sprintf(tool_error_upload_move_file, $upl_file));
            return false;
          }
          if (!chmod($upl_file, 0755)) {
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_chmod, basename($upl_file))));
          }

          // Upload erfolgreich - Bild Abmessungen pruefen
          $path_parts = pathinfo($upl_file);

          list($origin_width, $origin_height) = getimagesize($upl_file);
          $max_width = $dbMarketCfg->getValue(dbMarketCfg::cfgAdMaxImageWidth);
          $max_height = $dbMarketCfg->getValue(dbMarketCfg::cfgAdMaxImageHeight);
          $max_prev_width = $dbMarketCfg->getValue(dbMarketCfg::cfgAdImagePrevWidth);

          if (($origin_width > $max_width) || ($origin_height > $max_height)) {
            // Bild runterrechnen
            $factor = ($origin_width > $max_width) ? $max_width / $origin_width : $max_height / $origin_height;
            $new_height = ceil($origin_height * $factor);
            $new_width = ceil($origin_width * $factor);
            if (false === ($new_file = $this->createTweakedFile($path_parts['filename'], $ext, $upl_file, $new_width, $new_height, $origin_width, $origin_height))) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_tweaking_file, $upl_file)));
              return false;
            }
            @unlink($upl_file);
            if (!rename($new_file, $upl_file)) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_rename_file, $new_file, $upl_file)));
              return false;
            }
            $origin_width = $new_width;
            $origin_height = $new_height;
          }

          // Vorschaubild anlegen
          $factor = $max_prev_width / $origin_width;
          $new_height = ceil($origin_height * $factor);
          $new_width = ceil($origin_width * $factor);
          if (false === ($new_file = $this->createTweakedFile($path_parts['filename'], $ext, $upl_file, $new_width, $new_height, $origin_width, $origin_height))) {
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_tweaking_file, $upl_file)));
            return false;
          }
          if (!file_exists($upload_dir . $max_prev_width)) {
            if (!mkdir($upload_dir . $max_prev_width, 0755, true)) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_mkdir, $upload_dir . $max_prev_width)));
              return false;
            }
          }
          if (!rename($new_file, $upload_dir . $max_prev_width . '/' . $ufile)) {
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_move_file, $new_file, $upload_dir . $max_prev_width . '/' . $ufile)));
            return false;
          }

          if (!in_array($ufile, $pictures)) $pictures[] = $ufile;
          $changed = true;
          $message .= sprintf(tool_msg_upload_success, $_FILES[dbMarketAdvertisement::field_pictures]['name']);
        }
      }
      else {
        switch ($_FILES[dbMarketAdvertisement::field_pictures]['error']) :
          case UPLOAD_ERR_INI_SIZE :
            $error = sprintf(tool_error_upload_ini_size, ini_get('upload_max_filesize'));
            break;
          case UPLOAD_ERR_FORM_SIZE :
            $error = tool_error_upload_form_size;
            break;
          case UPLOAD_ERR_PARTIAL :
            $error = sprintf(tool_error_upload_partial, $_FILES[dbMarketAdvertisement::field_pictures]['name']);
            break;
          default :
            $error = tool_error_upload_undefined_error;
        endswitch
        ;
        $this->setError($error);
        return false;
      }
    }
    $new_advertisement[dbMarketAdvertisement::field_pictures] = implode(',', $pictures);

    if ($checked && $changed) {
      // Daten sind geprueft und haben sich veraendert
      if ($ad_id > 0) {
        // Datensatz aktualisieren
        $where = array(
          dbMarketAdvertisement::field_id => $ad_id
        );
        unset($new_advertisement[dbMarketAdvertisement::field_timestamp]);
        if (!$dbMarketAd->sqlUpdateRecord($new_advertisement, $where)) {
          $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $dbMarketAd->getError()));
          return false;
        }
        $message .= sprintf(tool_msg_record_updated, $ad_id);
      }
      else {
        // neuen Datensatz anlegen
        $status = $publish_directly ? dbMarketAdvertisement::status_active : dbMarketAdvertisement::status_locked;
        $new_advertisement[dbMarketAdvertisement::field_status] = $status;
        unset($new_advertisement[dbMarketAdvertisement::field_timestamp]);

        if (!$dbMarketAd->sqlInsertRecord($new_advertisement, $ad_id)) {
          $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $dbMarketAd->getError()));
          return false;
        }
        $message .= $publish_directly ? market_msg_ad_inserted_locked : market_msg_ad_inserted_publish;
      }
      foreach ($dbMarketAd->getFields() as $key => $value) {
        unset($_REQUEST[$key]);
      }
      $_REQUEST[dbMarketAdvertisement::field_id] = $ad_id;
    }

    $this->setMessage($message);
    return $this->accountAdvertisementAdd();
  } // accountAdvertisementCheck()

  public function accountOverview() {
    global $dbMarketAd;
    global $dbMarketCats;

    $SQL = sprintf("SELECT * FROM %s WHERE %s='%s' AND %s!='%s' ORDER BY %s DESC", $dbMarketAd->getTableName(), dbMarketAdvertisement::field_kit_id, $_SESSION[kitContactInterface::session_kit_contact_id], dbMarketAdvertisement::field_status, dbMarketAdvertisement::status_deleted, dbMarketAdvertisement::field_timestamp);
    $ads = array();
    if (!$dbMarketAd->sqlExec($SQL, $ads)) {
      $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $dbMarketAd->getError()));
      return false;
    }
    if (count($ads) < 1) {
      // es gibt keine Eintraege
    }
    else {
      // Liste ausgeben
      $list = array();
      foreach ($ads as $ad) {
        $cat = array();
        $where = array(
          dbMarketCategories::field_id => $ad[dbMarketAdvertisement::field_category]
        );
        $category = array();
        if (!$dbMarketCats->sqlSelectRecord($where, $category)) {
          $this->setError(sprintf('[%s - %] %s', __METHOD__, __LINE__, $dbMarketCats->getError()));
          return false;
        }
        if (count($category) < 1) {
          $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_id_invalid, $ad[dbMarketAdvertisement::field_category])));
          return false;
        }
        $category = $category[0];
        for($i = 1; $i < 6; $i++) {
          if (!empty($category[sprintf('cat_level_%02d', $i)])) $cat[] = $category[sprintf('cat_level_%02d', $i)];
        }
        $cat_str = implode(' > ', $cat);
        $list[] = array(
          'id' => array(
            'value' => $ad[dbMarketAdvertisement::field_id],
            'link' => sprintf('%s%s%s', $this->page_link, (strpos($this->page_link, '?') === false) ? '?' : '&', http_build_query(array(
              self::request_main_action => self::action_account,
              self::request_account_action => self::action_advertisement_add,
              dbMarketAdvertisement::field_id => $ad[dbMarketAdvertisement::field_id]
            )))
          ),
          'type' => array(
            'offer' => ($ad[dbMarketAdvertisement::field_ad_type] == dbMarketAdvertisement::type_offer) ? 1 : 0
          ),
          'title' => array(
            'text' => $ad[dbMarketAdvertisement::field_title]
          ),
          'category' => array(
            'text' => $cat_str
          )
        );
      }

      $form = array(
        'head' => market_head_advertisement_overview,
        'is_message' => $this->isMessage() ? 1 : 0,
        'message' => $this->isMessage() ? $this->getMessage() : market_intro_advertisement_overview,
        'header' => array(
          'id' => market_th_id,
          'kit_id' => market_th_kit_id,
          'category' => market_th_category,
          'type' => market_th_type,
          'commercial' => market_th_commercial,
          'title' => market_th_title,
          'price' => market_th_price,
          'price_type' => market_th_price_type,
          'pictures' => market_th_pictures,
          'text' => market_th_text,
          'status' => market_th_status,
          'start_date' => market_th_start_date,
          'end_date' => market_th_end_date,
          'timestamp' => market_th_timestamp
        )
      );
      $data = array(
        'form' => $form,
        'advertisement' => $list
      );
      return $this->getTemplate('account.advertisement.overview.list.htt', $data);
    }
  } // accountOverview()

  /**
   * FUNKTION DES OEFFENTLICHEN MARKTPLATZES
   */

  public function marketAction() {

    $action = (isset($_REQUEST[self::request_market_action])) ? $_REQUEST[self::request_market_action] : self::action_default;
    $cat = -1;
    switch ($action) :
      case self::action_advertisement :
        $content = $this->marketShowAdvertisement();
        break;
      case self::action_category :
        // bestimmte Kategorie anzeigen
        $content = $this->marketShowCategory($cat);
        break;
      default :
        $content = $this->marketShowCategory($cat);
        break;
    endswitch
    ;

    $data = array(
      'content' => $content,
      'category' => $cat,
      'categories' => $this->marketCategoriesList()
    );
    return $this->getTemplate('body.market.htt', $data);
  } // marketAction()

  /**
   * Navigationsliste durch die Kategorien
   *
   * @return ARRAY categories
   */
  public function marketCategoriesList() {
    global $dbMarketCats;

    $SQL = sprintf("SELECT * FROM %s WHERE %s='%s' ORDER BY %s, %s, %s, %s, %s ASC", $dbMarketCats->getTableName(), dbMarketCategories::field_status, dbMarketCategories::status_active, dbMarketCategories::field_level_01, dbMarketCategories::field_level_02, dbMarketCategories::field_level_03, dbMarketCategories::field_level_04, dbMarketCategories::field_level_05);
    $categories = array();
    if (!$dbMarketCats->sqlExec($SQL, $categories)) {
      $this->setError($dbMarketCats->getError());
      return false;
    }

    $cat_list = array();

    foreach ($categories as $cat) {
      $text = '';
      for($i = 1; $i < 6; $i++) {
        if (!empty($cat[sprintf('cat_level_%02d', $i)])) {
          $level = $i;
          $text = $cat[sprintf('cat_level_%02d', $i)];
        }
      }
      $cat_list[] = array(
        1 => $cat[dbMarketCategories::field_level_01],
        2 => $cat[dbMarketCategories::field_level_02],
        3 => $cat[dbMarketCategories::field_level_03],
        4 => $cat[dbMarketCategories::field_level_04],
        5 => $cat[dbMarketCategories::field_level_05],
        'id' => $cat[dbMarketCategories::field_id],
        'text' => $text,
        'link' => sprintf('%s%s%s=%s&%s=%s', $this->page_link, (strpos($this->page_link, '?') === false) ? '?' : '&', self::request_market_action, self::action_category, dbMarketCategories::field_id, $cat[dbMarketCategories::field_id]),
        'level' => $level,
        'parent' => ($level > 1) ? $cat[sprintf('cat_level_%02d', $level - 1)] : $cat[dbMarketCategories::field_level_01]
      );
    }

    return $cat_list;
  } // marketCategoriesList()

  public function marketShowCategory(&$cat_id = -1) {
    global $dbMarketAd;
    global $dbMarketCats;
    global $dbMarketCfg;
    global $kitContactInterface;

    $cat_id = isset($_REQUEST[dbMarketCategories::field_id]) ? $_REQUEST[dbMarketCategories::field_id] : -1;
    $max_entries = $dbMarketCfg->getValue(dbMarketCfg::cfgAdListEntries);

    if ($cat_id < 1) {
      // Startseite - keine Kategorie gewaehlt
      $SQL = sprintf("SELECT * FROM %s,%s WHERE %s=%s AND %s='%s' ORDER BY %s DESC LIMIT %s", $dbMarketAd->getTableName(), $dbMarketCats->getTableName(), dbMarketAdvertisement::field_category, dbMarketCategories::field_id, dbMarketAdvertisement::field_status, dbMarketAdvertisement::status_active, dbMarketAdvertisement::field_timestamp, $max_entries);
    }
    else {
      // Kategorie ausgewaehlt
      $where = array(
        dbMarketCategories::field_id => $cat_id
      );
      $category = array();
      if (!$dbMarketCats->sqlSelectRecord($where, $category)) {
        $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $dbMarketCats->getError()));
        return false;
      }
      if (count($category) < 1) {
        $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_id_invalid, $cat_id)));
        return false;
      }
      $category = $category[0];
      $fields = '';
      for($i = 1; $i < 6; $i++) {
        if (!empty($category[sprintf('cat_level_%02d', $i)])) {
          if (!empty($fields)) $fields .= ' AND ';
          $fields .= sprintf("cat_level_%02d='%s'", $i, $category[sprintf('cat_level_%02d', $i)]);
        }
        else {
          break;
        }
      }
      if (empty($fields)) {
        $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, market_error_undefined));
        return false;
      }
      $SQL = sprintf("SELECT * FROM %s,%s WHERE %s=%s AND %s='%s' AND %s ORDER BY %s DESC", $dbMarketAd->getTableName(), $dbMarketCats->getTableName(), dbMarketAdvertisement::field_category, dbMarketCategories::field_id, dbMarketAdvertisement::field_status, dbMarketAdvertisement::status_active, $fields, dbMarketAdvertisement::field_timestamp);
    }

    $advertisements = array();
    if (!$dbMarketAd->sqlExec($SQL, $advertisements)) {
      $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $dbMarketAd->getError()));
      return false;
    }

    $items = array();
    foreach ($advertisements as $ad) {

      $max_image_width = $dbMarketCfg->getValue(dbMarketCfg::cfgAdMaxImageWidth);
      $max_image_height = $dbMarketCfg->getValue(dbMarketCfg::cfgAdMaxImageHeight);
      $prev_width = $dbMarketCfg->getValue(dbMarketCfg::cfgAdImagePrevWidth);
      $images = array();
      $pictures = (!empty($ad[dbMarketAdvertisement::field_pictures])) ? explode(',', $ad[dbMarketAdvertisement::field_pictures]) : array();

      $upl_path = $this->media_path . $ad[dbMarketAdvertisement::field_kit_id] . '/' . $ad[dbMarketAdvertisement::field_id] . '/';
      $upl_url = str_replace(WB_PATH, WB_URL, $upl_path);
      $prev_path = $upl_path . $prev_width . '/';
      $prev_url = str_replace(WB_PATH, WB_URL, $prev_path);

      $tmp_dir = $this->media_path . $ad[dbMarketAdvertisement::field_kit_id] . '/tmp/';

      $i = 0;
      foreach ($pictures as $picture) {
        $i++;
        if (!file_exists($upl_path . $picture)) {
          if (file_exists($tmp_dir . $picture)) {
            // Datei befindet sich noch im TEMP Verzeichnis, verschieben...
            if (!file_exists($upl_path)) {
              // Verzeichnis erstellen
              if (!mkdir($upl_path, 0755, true)) {
                $this->setError(sprintf('[%s - %s] %s', sprintf(tool_error_mkdir, $upl_path)));
                return false;
              }
            }
            if (!rename($tmp_dir . $picture, $upl_path . $picture)) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_move_file, $tmp_dir . $picture, $upl_path . $picture)));
              return false;
            }
          }
          else {
            // Datei nicht gefunden
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_missing_file, $upl_path . $picture)));
            return false;
          }
        }
        // Dateiinformationen
        $path_parts = pathinfo($upl_path . $picture);
        // Breite und Hoehe festhalten
        list($full_width, $full_height) = getimagesize($upl_path . $picture);
        // Vorschaubild pruefen
        if (!file_exists($prev_path . $picture)) {
          $factor = $prev_width / $full_width;
          $new_height = ceil($full_height * $factor);
          $new_width = ceil($full_width * $factor);
          if (false === ($new_file = $this->createTweakedFile($path_parts['filename'], $path_parts['extension'], $upl_path . $picture, $new_width, $new_height, $full_width, $full_height))) {
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_tweaking_file, $upl_path . $picture)));
            return false;
          }
          if (!file_exists($prev_path)) {
            if (!mkdir($prev_path, 0755, true)) {
              $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_mkdir, $prev_path)));
              return false;
            }
          }
          if (!rename($new_file, $prev_path . $picture)) {
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_move_file, $new_file, $prev_path . $picture)));
            return false;
          }
        }
        list($prev_width, $prev_height) = getimagesize($prev_path . $picture);
        $images[$i] = array(
          'fullsize' => array(
            'url' => $upl_url . $picture,
            'width' => $full_width,
            'height' => $full_height
          ),
          'preview' => array(
            'url' => $prev_url . $picture,
            'width' => $prev_width,
            'height' => $prev_height
          )
        );
      }

      // Kategorien
      $kat = array();
      for($i = 1; $i < 6; $i++) {
        if (!empty($ad[sprintf('cat_level_%02d', $i)])) $kat[] = $ad[sprintf('cat_level_%02d', $i)];
      }
      $kat_str = implode(' > ', $kat);

      // Kontakt
      $contact = array();
      if (!$kitContactInterface->getContact($ad[dbMarketAdvertisement::field_kit_id], $contact)) {
        $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $kitContactInterface->getError()));
        return false;
      }
      $items[] = array(
        'id' => $ad[dbMarketAdvertisement::field_id],
        'images' => $images,
        'category' => $kat_str,
        'type' => $dbMarketAd->type_array[$ad[dbMarketAdvertisement::field_ad_type]],
        'commercial' => $dbMarketAd->commercial_array[$ad[dbMarketAdvertisement::field_commercial]],
        'title' => $ad[dbMarketAdvertisement::field_title],
        'text' => $ad[dbMarketAdvertisement::field_text],
        'price' => array(
          'value' => $ad[dbMarketAdvertisement::field_price],
          'text' => number_format($ad[dbMarketAdvertisement::field_price], 2, tool_cfg_decimal_separator, tool_cfg_thousand_separator)
        ),
        'price_type' => $dbMarketAd->price_array[$ad[dbMarketAdvertisement::field_price_type]],
        'link' => sprintf('%s%s%s=%s&%s=%s', $this->page_link, (strpos($this->page_link, '?') === false) ? '?' : '&', self::request_market_action, self::action_advertisement, dbMarketAdvertisement::field_id, $ad[dbMarketAdvertisement::field_id]),
        'contact' => $contact
      );
    }

    $data = array(
      'category' => $cat_id,
      'items' => $items
    );
    return $this->getTemplate('market.advertisement.list.htt', $data);
  } // marketShowCategory()

  public function marketShowAdvertisement() {
    global $dbMarketAd;
    global $dbMarketCfg;
    global $kitContactInterface;

    $ad_id = (isset($_REQUEST[dbMarketAdvertisement::field_id])) ? $_REQUEST[dbMarketAdvertisement::field_id] : -1;

    if ($ad_id < 1) {
      $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_request_missing, dbMarketAdvertisement::field_id)));
      return false;
    }

    $where = array(
      dbMarketAdvertisement::field_id => $ad_id
    );
    $ad = array();
    if (!$dbMarketAd->sqlSelectRecord($where, $ad)) {
      $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $dbMarketAd->getError()));
      return false;
    }
    if (count($ad) < 1) {
      $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_id_invalid, $ad_id)));
      return false;
    }
    $ad = $ad[0];

    // Bilder einlesen
    $max_image_width = $dbMarketCfg->getValue(dbMarketCfg::cfgAdMaxImageWidth);
    $max_image_height = $dbMarketCfg->getValue(dbMarketCfg::cfgAdMaxImageHeight);
    $prev_width = $dbMarketCfg->getValue(dbMarketCfg::cfgAdImagePrevWidth);
    $images = array();
    $pictures = (!empty($ad[dbMarketAdvertisement::field_pictures])) ? explode(',', $ad[dbMarketAdvertisement::field_pictures]) : array();

    $upl_path = $this->media_path . $ad[dbMarketAdvertisement::field_kit_id] . '/' . $ad[dbMarketAdvertisement::field_id] . '/';
    $upl_url = str_replace(WB_PATH, WB_URL, $upl_path);
    $prev_path = $upl_path . $prev_width . '/';
    $prev_url = str_replace(WB_PATH, WB_URL, $prev_path);

    $tmp_dir = $this->media_path . $ad[dbMarketAdvertisement::field_kit_id] . '/tmp/';

    $i = 0;
    foreach ($pictures as $picture) {
      $i++;
      if (!file_exists($upl_path . $picture)) {
        if (file_exists($tmp_dir . $picture)) {
          // Datei befindet sich noch im TEMP Verzeichnis, verschieben...
          if (!file_exists($upl_path)) {
            // Verzeichnis erstellen
            if (!mkdir($upl_path, 0755, true)) {
              $this->setError(sprintf('[%s - %s] %s', sprintf(tool_error_mkdir, $upl_path)));
              return false;
            }
          }
          if (!rename($tmp_dir . $picture, $upl_path . $picture)) {
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_move_file, $tmp_dir . $picture, $upl_path . $picture)));
            return false;
          }
        }
        else {
          // Datei nicht gefunden
          $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_missing_file, $upl_path . $picture)));
          return false;
        }
      }
      // Dateiinformationen
      $path_parts = pathinfo($upl_path . $picture);
      // Breite und Hoehe festhalten
      list($full_width, $full_height) = getimagesize($upl_path . $picture);
      // Vorschaubild pruefen
      if (!file_exists($prev_path . $picture)) {
        $factor = $prev_width / $full_width;
        $new_height = ceil($full_height * $factor);
        $new_width = ceil($full_width * $factor);
        if (false === ($new_file = $this->createTweakedFile($path_parts['filename'], $path_parts['extension'], $upl_path . $picture, $new_width, $new_height, $full_width, $full_height))) {
          $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_tweaking_file, $upl_path . $picture)));
          return false;
        }
        if (!file_exists($prev_path)) {
          if (!mkdir($prev_path, 0755, true)) {
            $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_mkdir, $prev_path)));
            return false;
          }
        }
        if (!rename($new_file, $prev_path . $picture)) {
          $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, sprintf(tool_error_move_file, $new_file, $prev_path . $picture)));
          return false;
        }
      }
      list($prev_width, $prev_height) = getimagesize($prev_path . $picture);
      $images[$i] = array(
        'fullsize' => array(
          'url' => $upl_url . $picture,
          'width' => $full_width,
          'height' => $full_height
        ),
        'preview' => array(
          'url' => $prev_url . $picture,
          'width' => $prev_width,
          'height' => $prev_height
        )
      );
    }

    // Kategorien
    $kat = array();
    for($i = 1; $i < 6; $i++) {
      if (!empty($ad[sprintf('cat_level_%02d', $i)])) $kat[] = $ad[sprintf('cat_level_%02d', $i)];
    }
    $kat_str = implode(' > ', $kat);

    // Kontakt
    $contact = array();
    if (!$kitContactInterface->getContact($ad[dbMarketAdvertisement::field_kit_id], $contact)) {
      $this->setError(sprintf('[%s - %s] %s', __METHOD__, __LINE__, $kitContactInterface->getError()));
      return false;
    }
    $item = array(
      'id' => $ad[dbMarketAdvertisement::field_id],
      'images' => $images,
      'category' => $kat_str,
      'type' => $dbMarketAd->type_array[$ad[dbMarketAdvertisement::field_ad_type]],
      'commercial' => $dbMarketAd->commercial_array[$ad[dbMarketAdvertisement::field_commercial]],
      'title' => $ad[dbMarketAdvertisement::field_title],
      'text' => $ad[dbMarketAdvertisement::field_text],
      'price' => array(
        'value' => $ad[dbMarketAdvertisement::field_price],
        'text' => number_format($ad[dbMarketAdvertisement::field_price], 2, tool_cfg_decimal_separator, tool_cfg_thousand_separator)
      ),
      'price_type' => $dbMarketAd->price_array[$ad[dbMarketAdvertisement::field_price_type]],
      'link' => sprintf('%s%s%s=%s&%s=%s', $this->page_link, (strpos($this->page_link, '?') === false) ? '?' : '&', self::request_market_action, self::action_advertisement, dbMarketAdvertisement::field_id, $ad[dbMarketAdvertisement::field_id]),
      'contact' => $contact
    );

    $data = array(
      'advertisement' => $item
    );
    return $this->getTemplate('market.advertisement.detail.htt', $data);
  } // marketShowAdvertisement

} // class marketFrontend

?>


text:
package org.spongepowered.forge.mixin.core.minecraftforge.event.entity;

import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.Level;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.EntityTravelToDimensionEvent;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.entity.ChangeEntityWorldEvent;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.SpongeCommon;
import org.spongepowered.common.event.tracking.PhaseTracker;
import org.spongepowered.forge.launch.bridge.event.ForgeEventBridge_Forge;

@Mixin(value = EntityTravelToDimensionEvent.class, remap = false)
public abstract class EntityTravelToDimensionEventMixin_Forge implements ForgeEventBridge_Forge {

    // @formatter:off
    @Shadow @Final @Mutable private ResourceKey<Level> dimension;
    // @formatter:on

    @Override
    public void bridge$syncFrom(final Event event) {
        if (event instanceof ChangeEntityWorldEvent.Pre) {
            ((net.minecraftforge.eventbus.api.Event) (Object) this).setCanceled(((ChangeEntityWorldEvent.Pre) event).isCancelled());
            this.dimension = ((ServerLevel) ((ChangeEntityWorldEvent.Pre) event).destinationWorld()).dimension();
        }
    }

    @Override
    public void bridge$syncTo(final Event event) {
        if (event instanceof ChangeEntityWorldEvent.Pre) {
            ((ChangeEntityWorldEvent.Pre) event).setCancelled(((net.minecraftforge.eventbus.api.Event) (Object) this).isCanceled());
        }
    }

    @Override
    public @Nullable Event bridge$createSpongeEvent() {
        final Entity entity = ((EntityEvent) (Object) this).getEntity();
        final ServerLevel toWorld = SpongeCommon.server().getLevel(this.dimension);
        return SpongeEventFactory.createChangeEntityWorldEventPre(PhaseTracker.getCauseStackManager().currentCause(),
                (org.spongepowered.api.entity.Entity) entity, (org.spongepowered.api.world.server.ServerWorld) entity.getCommandSenderWorld(),
                (org.spongepowered.api.world.server.ServerWorld) toWorld, (org.spongepowered.api.world.server.ServerWorld) toWorld);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package de.tor.tribes.util;

import de.tor.tribes.io.DataHolder;
import de.tor.tribes.io.UnitHolder;
import de.tor.tribes.types.Layer;
import de.tor.tribes.util.bb.BasicFormatter;
import de.tor.tribes.util.translation.TranslationManager;
import java.awt.Toolkit;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Default for all Global settings
 * that are used by almost all components. e.g. WorldData or UI specific objects
 *
 * @author Charon
 * @author extremeCrazyCoder
 */

public class GlobalDefaults {
    private static Logger logger = LogManager.getLogger("GlobalDefaults");
    private static boolean INITIALIZED = false;

    private static PropertiesConfiguration GLOBAL_DEFAULTS = null;

    /**
     * Init all managed objects
     *
     * @throws Exception If an Error occurs while initializing the objects
     */
    public static void initialize() {
        if (INITIALIZED) {
            return;
        }
        INITIALIZED = true;
        logger.debug("Loading defaults");
        loadDefaults();
    }

    /**
     * Add a property
     */

    public static void loadDefaults() {
        GLOBAL_DEFAULTS = new PropertiesConfiguration();
        GLOBAL_DEFAULTS.addProperty("ui.language", TranslationManager.DEFAULT_LANGUAGE);
        TranslationManager.getSingleton().setLanguage(GlobalOptions.getProperty("ui.language"));

        GLOBAL_DEFAULTS.addProperty("attack.movement", false);
        GLOBAL_DEFAULTS.addProperty("attack.planer.check.amount", 20000);
        GLOBAL_DEFAULTS.addProperty("attack.planer.enable.check", true);
        GLOBAL_DEFAULTS.addProperty("check.updates.on.startup", true);
        GLOBAL_DEFAULTS.addProperty("church.frame.alwaysOnTop", false);
        GLOBAL_DEFAULTS.addProperty("clipboard.notification", true);
        GLOBAL_DEFAULTS.addProperty("clock.alwaysOnTop", false);
        GLOBAL_DEFAULTS.addProperty("clock.delete_old", true);
        GLOBAL_DEFAULTS.addProperty("command.sleep.time", 150);
        GLOBAL_DEFAULTS.addProperty("conquers.frame.alwaysOnTop", false);
        GLOBAL_DEFAULTS.addProperty("default.browser", "");
        GLOBAL_DEFAULTS.addProperty("default.mark", 0);
        GLOBAL_DEFAULTS.addProperty("default.skin", "default");
        GLOBAL_DEFAULTS.addProperty("delete.farm.reports.on.exit", true);
        GLOBAL_DEFAULTS.addProperty("draw.attacks.by.default", false);
        GLOBAL_DEFAULTS.addProperty("extended.attack.vectors", false);
        GLOBAL_DEFAULTS.addProperty("extended.text.attacks", false);
        GLOBAL_DEFAULTS.addProperty("form.config.frame.alwaysOnTop", false);
        GLOBAL_DEFAULTS.addProperty("ribbon.size", 1.0);
        GLOBAL_DEFAULTS.addProperty("highlight.tribes.villages", false);
        GLOBAL_DEFAULTS.addProperty("include.support", true);
        GLOBAL_DEFAULTS.addProperty("inform.on.updates", true);
        GLOBAL_DEFAULTS.addProperty("main.size.height", (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() - 50);
        GLOBAL_DEFAULTS.addProperty("main.size.width", (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() - 50);
        GLOBAL_DEFAULTS.addProperty("map.marker.transparency", 80);
        GLOBAL_DEFAULTS.addProperty("map.showcontinents", true);
        GLOBAL_DEFAULTS.addProperty("map.zoom.max", 3.0);
        GLOBAL_DEFAULTS.addProperty("map.zoom.min", 0.4);
        GLOBAL_DEFAULTS.addProperty("map.zoom.in.out.factor", 1.06);
        GLOBAL_DEFAULTS.addProperty("mark.villages.on.minimap", true);
        GLOBAL_DEFAULTS.addProperty("max.density.troops", 65000);
        GLOBAL_DEFAULTS.addProperty("max.farm.space", 20000);
        GLOBAL_DEFAULTS.addProperty("farm.popup.use.real", false);
        GLOBAL_DEFAULTS.addProperty("max.loss.ratio", 50);
        GLOBAL_DEFAULTS.addProperty("max.sim.rounds", 500);
        GLOBAL_DEFAULTS.addProperty("no.welcome", false);
        GLOBAL_DEFAULTS.addProperty("notify.duration", 1);
        GLOBAL_DEFAULTS.addProperty("obst.server", "");
        GLOBAL_DEFAULTS.addProperty("parser.movement.plan", "imported");
        GLOBAL_DEFAULTS.addProperty("parser.movement.delete.all.on.import", "false");
        GLOBAL_DEFAULTS.addProperty("proxySet", false);
        GLOBAL_DEFAULTS.addProperty("proxyHost", "");
        GLOBAL_DEFAULTS.addProperty("proxyPort", 8080);
        GLOBAL_DEFAULTS.addProperty("proxyType", 0);
        GLOBAL_DEFAULTS.addProperty("proxyUser", "");
        GLOBAL_DEFAULTS.addProperty("proxyPassword", "");
        GLOBAL_DEFAULTS.addProperty("radar.size", 60); //in minutes
        GLOBAL_DEFAULTS.addProperty("red.width", 0);
        GLOBAL_DEFAULTS.addProperty("red.height", 0);
        GLOBAL_DEFAULTS.addProperty("report.server.port", 8080);
        GLOBAL_DEFAULTS.addProperty("ribbon.minimized", false);
        GLOBAL_DEFAULTS.addProperty("screen.dir", ".");
        GLOBAL_DEFAULTS.addProperty("search.frame.alwaysOnTop", false);
        GLOBAL_DEFAULTS.addProperty("show.barbarian", true);
        GLOBAL_DEFAULTS.addProperty("show.live.countdown", true);
        GLOBAL_DEFAULTS.addProperty("show.map.popup", true);
        GLOBAL_DEFAULTS.addProperty("show.mouseover.info", false);
        GLOBAL_DEFAULTS.addProperty("show.popup.conquers", true);
        GLOBAL_DEFAULTS.addProperty("show.popup.farm.space", true);
        GLOBAL_DEFAULTS.addProperty("show.popup.ranks", true);
        GLOBAL_DEFAULTS.addProperty("show.sectors", true);
        GLOBAL_DEFAULTS.addProperty("show.ruler", true);
        GLOBAL_DEFAULTS.addProperty("show.church", true);
        GLOBAL_DEFAULTS.addProperty("show.watchtower", true);
        GLOBAL_DEFAULTS.addProperty("show.ruler", true);
        GLOBAL_DEFAULTS.addProperty("sos.mark.all.duplicates.as.fake", "true");
        GLOBAL_DEFAULTS.addProperty("standard.defense.split", "heavy=0/spy=50/sword=500/archer=500/spear=500");
        GLOBAL_DEFAULTS.addProperty("standard.off", "catapult=50/light=3000/ram=300/axe=7000/marcher=500");
        GLOBAL_DEFAULTS.addProperty("stats.frame.alwaysOnTop", false);
        GLOBAL_DEFAULTS.addProperty("support.tolerance", 0);
        GLOBAL_DEFAULTS.addProperty("systray.enabled", SystrayHelper.isSystraySupported());
        GLOBAL_DEFAULTS.addProperty("tag.frame.menu.visible", true);
        GLOBAL_DEFAULTS.addProperty("tag.frame.table.visibility", "true;true;true;true");
        GLOBAL_DEFAULTS.addProperty("tap.height", 0);
        GLOBAL_DEFAULTS.addProperty("tap.width", 0);
        GLOBAL_DEFAULTS.addProperty("text.attacks.per.file", "10");
        GLOBAL_DEFAULTS.addProperty("village.order", 0);
        GLOBAL_DEFAULTS.addProperty("watchtower.frame.alwaysOnTop", false);
        GLOBAL_DEFAULTS.addProperty("zip.text.attacks", false);

        for (UnitHolder unit : DataHolder.getSingleton().getUnits()) {
            GLOBAL_DEFAULTS.addProperty(unit.getName() + ".color", "#ff0000");
        }

        GLOBAL_DEFAULTS.addProperty("layer.order", Layer.getDefaultLayerString());

        //Default templates
        GLOBAL_DEFAULTS.addProperty("attack.template.header", "<Standard>");
        GLOBAL_DEFAULTS.addProperty("attack.template.header.internal", "templates/attack_header.tmpl");
        GLOBAL_DEFAULTS.addProperty("attack.template.block", "<Standard>");
        GLOBAL_DEFAULTS.addProperty("attack.template.block.internal", "templates/attack_block.tmpl");
        GLOBAL_DEFAULTS.addProperty("attack.template.footer", "<Standard>");
        GLOBAL_DEFAULTS.addProperty("attack.template.footer.internal", "templates/attack_footer.tmpl");

        addBasicFormatter(new de.tor.tribes.util.bb.ReportListFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.AllyReportStatsFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.AttackListFormatter(false));
        addBasicFormatter(new de.tor.tribes.util.bb.AttackListFormatter(true));
        addBasicFormatter(new de.tor.tribes.util.bb.DefStatsFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.FormListFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.KillStatsFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.MarkerListFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.NoteListFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.OverallReportStatsFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.PointStatsFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.SosListFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.TagListFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.TribeReportStatsFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.TroopListFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.KnownVillageListFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.VillageListFormatter());
        addBasicFormatter(new de.tor.tribes.util.bb.WinnerLoserStatsFormatter());

        //TODO set to true after Moral is working
        GLOBAL_DEFAULTS.addProperty("show.popup.moral", ServerSettings.getSingleton()
                .getMoralType() == ServerSettings.POINTBASED_MORAL);
    }

    /**
     * Get the value of a property
     */
    public static String getProperty(String pKey) {
        if (pKey == null) {
            return null;
        }
        if(!INITIALIZED) initialize();

        Object property = GLOBAL_DEFAULTS.getProperty(pKey);
        if (property != null) {
            return property.toString();
        } else {
            return null;
        }
    }

    public static PropertiesConfiguration getProperties() {
        if(!INITIALIZED) initialize();
        return GLOBAL_DEFAULTS;
    }

    public static void reinit() {
        GLOBAL_DEFAULTS.clear();
        loadDefaults();
    }

    private static <T extends BasicFormatter> void addBasicFormatter(T formatterInstance) {
        GLOBAL_DEFAULTS.addProperty(formatterInstance.getPropertyKey(),
                formatterInstance.getStandardTemplate());
    }
}


text:
<?php

declare(strict_types=1);

namespace LizardsAndPumpkins\ProductRelations\ContentDelivery;

use LizardsAndPumpkins\Http\ContentDelivery\ProductJsonService\ProductJsonService;
use LizardsAndPumpkins\Context\Context;
use LizardsAndPumpkins\Import\Product\ProductId;
use LizardsAndPumpkins\ProductRelations\ProductRelations;
use PHPUnit\Framework\TestCase;

/**
 * @covers \LizardsAndPumpkins\ProductRelations\ContentDelivery\ProductRelationsService
 */
class ProductRelationsServiceTest extends TestCase
{
    /**
     * @var ProductRelations|MockObject
     */
    private $mockProductRelations;

    /**
     * @var ProductRelationsLocator|MockObject
     */
    private $stubProductRelationsLocator;

    /**
     * @var ProductId|MockObject
     */
    private $stubProductId;

    /**
     * @var ProductRelationTypeCode|MockObject
     */
    private $stubProductRelationTypeCode;

    /**
     * @var ProductJsonService|MockObject
     */
    private $stubProductJsonService;

    /**
     * @var ProductRelationsService
     */
    private $productRelationsService;

    /**
     * @var Context
     */
    private $stubContext;

    final protected function setUp(): void
    {
        $this->mockProductRelations = $this->createMock(ProductRelations::class);
        $this->stubProductRelationsLocator = $this->createMock(ProductRelationsLocator::class);
        $this->stubProductRelationsLocator->method('locate')->willReturn($this->mockProductRelations);
        $this->stubProductJsonService = $this->createMock(ProductJsonService::class);
        $this->stubContext = $this->createMock(Context::class);

        $this->stubProductId = $this->createMock(ProductId::class);
        $this->stubProductRelationTypeCode = $this->createMock(ProductRelationTypeCode::class);

        $this->productRelationsService = new ProductRelationsService(
            $this->stubProductRelationsLocator,
            $this->stubProductJsonService
        );
    }

    public function testItDelegatesToTheProductRelationsInstanceToFetchTheRelatedProducts(): void
    {
        $this->mockProductRelations->expects($this->once())->method('getById')->willReturn([]);

        $result = $this->productRelationsService->getRelatedProductData(
            $this->stubProductRelationTypeCode,
            $this->stubProductId,
            $this->stubContext
        );
        $this->assertSame([], $result);
    }

    public function testItFetchesTheRelatedProductJsonSnippetsFromTheProductJsonService(): void
    {
        $stubRelatedProductIds = [$this->createMock(ProductId::class)];
        $stubRelatedProductData = [
            ['Dummy Product Data 1'],
            ['Dummy Product Data 2'],
        ];

        $this->mockProductRelations->method('getById')->willReturn($stubRelatedProductIds);

        $this->stubProductJsonService->method('get')->willReturn($stubRelatedProductData);

        $this->assertSame($stubRelatedProductData, $this->productRelationsService->getRelatedProductData(
            $this->stubProductRelationTypeCode,
            $this->stubProductId,
            $this->stubContext
        ));
    }
}


text:
import * as React from 'react';
import { observer } from 'mobx-react';

import './LoadingOverlay.css';

interface LoadingOverlayProps {
    display: boolean;
    text?: string;
}

@observer
class LoadingOverlay extends React.Component<LoadingOverlayProps> {
    render() {
        if (this.props.display === false) {
            return false;
        }
        return (

{this.props.text}

);
    }
}

export default LoadingOverlay;


text:
Pattern: Use of deprecated function on `itertools` module

Issue: -

## Description

Emitted when accessing a function on `itertools` that has been removed in Python 3. Use `six.moves` to import a Python 2 and Python 3 compatible function instead.

Example of **incorrect** code:

```python
from itertools import izip
print(list(izip([1, 2], [3])))
```

Example of **correct** code:

```python
from six.moves import zip
print(list(zip([1, 2], [3])))
```


text:
package org.globalwordnet.api.serialize

import eu.monnetproject.lang.{Language, Script}
import org.globalwordnet.api.wn._
import org.scalatest._

class JsonSpec extends FlatSpec with Matchers {
  var resource : LexicalResource = null
  "Json reader" should "successfully read a JSON file" in {
    resource = WNJSON.read(new java.io.FileReader("src/test/resources/example.json"))
  }
  it should "produce 2 lexicons" in {
    resource.lexicons.size should be (2)
  }
  it should "get features of lexicon" in {
    val lexicon = resource.lexicons(0)
    lexicon.id should be ("example-en")
    lexicon.label should be ("Example wordnet (English)")
    lexicon.language should be (Language.ENGLISH)
    lexicon.email should be ("john@mccr.ae")
    lexicon.license should be ("https://creativecommons.org/publicdomain/zero/1.0/")
    lexicon.version should be ("1.0")
    lexicon.citation should be (Some("CILI: the Collaborative Interlingual Index. Francis Bond, Piek Vossen, John P. McCrae and Christiane Fellbaum, Proceedings of the Global WordNet Conference 2016, (2016)."))
    lexicon.url should be (Some("http://globalwordnet.github.io/schemas/"))
    lexicon.publisher should be (Some("Global Wordnet Association"))
  }
  it should "produce 3 english entries" in {
    resource.lexicons(0).entries.size should be (3)
  }
  it should "produce 2 synset" in {
    resource.lexicons(0).synsets.size should be (2)
  }
  it should "produce an entry for grandfather" in {
    val e = resource.lexicons(0).entries(0)
    e.id should be ("w1")
    e.lemma.writtenForm should be ("grandfather")
    e.lemma.partOfSpeech should be (noun)
    e.senses(0).id should be ("example-en-10161911-n-1")
    e.senses(0).synsetRef should be ("example-en-10161911-n")
  }
  it should "produce a sense" in {
    val s = resource.lexicons(0).entries(1).senses(0)
    s.id should be ("example-en-1-n-1")
    s.synsetRef should be ("example-en-1-n")
  }
  it should "produce a sense relation" in {
    val r = resource.lexicons(0).entries(1).senses(0).senseRelations(0)
    r.relType should be (derivation)
    r.target should be ("example-en-10161911-n-1")
  }
  it should "produce syntactic behavior" in {
    resource.lexicons(0).entries(2).syntacticBehaviours.size should be (3)
    val s = resource.lexicons(0).entries(2).syntacticBehaviours(0)
    s.subcategorizationFrame should be ("Sam cannot %s Sue")
  }
  it should "produce a synset" in {
    val s = resource.lexicons(0).synsets(0)
    s.id should be ("example-en-10161911-n")
    s.ili should be (Some("i90287"))
    s.definitions(0).content should be ("the father of your father or mother")
    s.synsetRelations(0).relType should be (hypernym)
    s.synsetRelations(0).target should be ("example-en-10162692-n")
  }
  val f = java.io.File.createTempFile("lexicon", ".json")
  f.deleteOnExit()
  "JSON Writer" should "write a file" in {
    WNJSON.write(resource, f)
  }
  it should "roundtrip" in {
    val text1 = io.Source.fromFile("src/test/resources/example.json").getLines.mkString(" ").replaceAll("\\s+", "")
    val text2 = io.Source.fromFile(f).getLines.mkString("\n").replaceAll("\\s+","")
    text2.length should be (text1.length)
    //val f1 = text1.groupBy(x => x).mapValues(_.size)
    //val f2 = text2.groupBy(x => x).mapValues(_.size)
    //for(k <- f1.keys) {
    //  if(f1(k) - f2.getOrElse(k, 0) != 0) {
    //    println("%s\t%d" format(k, f1(k) - f2.getOrElse(k, 0)))
    //  }
    //}
  }

}


text:
namespace ArtZilla.Net.Core.Extensions {
	public static class NumberUtils {
		/// <summary>
		/// todo: add description
		/// method from https://stackoverflow.com/a/33325313
		/// </summary>
		/// <param name="high"></param>
		/// <param name="low"></param>
		/// <returns></returns>
		public static long MakeLong(int high, int low)
			=> (long) high << 32 | (long)(uint)low;

		/// <summary>
		/// todo: add description
		/// </summary>
		/// <param name="high"></param>
		/// <param name="low"></param>
		/// <returns></returns>
		public static long MakeLong(int high, uint low)
			=> (long) high << 32 | low;

		/// <summary>
		/// todo: add description
		/// </summary>
		/// <param name="high"></param>
		/// <param name="low"></param>
		/// <returns></returns>
		public static long MakeLong(uint high, uint low)
			=> (long) high << 32 | low;
	}
}


text:
package skadistats.clarity.decoder.unpacker;

import skadistats.clarity.decoder.BitStream;
import skadistats.clarity.model.Vector;

public class QAnglePitchYawOnlyUnpacker implements Unpacker<Vector> {

    private final int nBits;

    public QAnglePitchYawOnlyUnpacker(int nBits) {
        this.nBits = nBits;
    }

    @Override
    public Vector unpack(BitStream bs) {
        float[] v = new float[3];
        if ((nBits | 0x20) == 0x20) {
            v[0] = Float.intBitsToFloat(bs.readUBitInt(32));
            v[1] = Float.intBitsToFloat(bs.readUBitInt(32));
        } else {
            v[0] = bs.readBitAngle(nBits);
            v[1] = bs.readBitAngle(nBits);
        }
        return new Vector(v);
    }

}


text:
<?php

namespace SunlightExtend\Devkit\Component;

use Sunlight\Localization\LocalizationDictionary;

class MissingLocalizationLogger
{
    /** @var \SplObjectStorage dict => array(key1 => count1, ...) */
    private $missingEntries;

    function __construct()
    {
        $this->missingEntries = new \SplObjectStorage();
    }

    /**
     * @param LocalizationDictionary $dict
     * @param string                 $key
     */
    function log(LocalizationDictionary $dict, string $key): void
    {
        if (!isset($this->missingEntries[$dict])) {
            $this->missingEntries[$dict] = [];
        }

        $missingEntries = $this->missingEntries[$dict];

        if (!isset($missingEntries[$key])) {
            $missingEntries[$key] = 0;
        }

        ++$missingEntries[$key];

        $this->missingEntries[$dict] = $missingEntries;
    }

    /**
     * @return \SplObjectStorage
     */
    function getMissingEntries(): \SplObjectStorage
    {
        return $this->missingEntries;
    }
}


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\PeerAssessment\Builder\Component;

use Chamilo\Core\Repository\ContentObject\PeerAssessment\Builder\Manager;
use Chamilo\Libraries\Architecture\Application\ApplicationConfiguration;
use Chamilo\Libraries\Architecture\Application\ApplicationFactory;

class CreatorComponent extends Manager
{

    public function run()
    {
        $factory = new ApplicationFactory(
            \Chamilo\Core\Repository\Builder\Action\Manager::context(),
            new ApplicationConfiguration($this->getRequest(), $this->get_user(), $this));
        return $factory->run();
    }

    /*
     * function get_additional_parameters() { return array(self :: PARAM_TYPE); }
     */
}


text:
namespace SportPredictionsSystem.Data.Contracts
{
    using System;

    public interface IDeletableEntity
    {
        bool IsDeleted { get; set; }

        DateTime? DeletedOn { get; set; }
    }
}


text:
package edu.berkeley.eecs.cfc_tracker;

public final class Constants {
	public static String LONGITUDE = "longitude";
	public static String LATITUDE = "latitude";
	public static String ACCELERATOR_X = "ax";
	public static String ACCELERATOR_Y = "ay";
	public static String ACCELERATOR_Z = "az";
	public static String BATTERY_LEVEL = "battery_level";
	public static String ACTIVITY_TYPE = "activity_type";
	public static String ACTIVITY_CONFIDENCE = "activity_confidence";

	public static String[] sensors = {LONGITUDE,
									  LATITUDE,
									  ACCELERATOR_X,
									  ACCELERATOR_Y,
									  ACCELERATOR_Z,
									  BATTERY_LEVEL,
									  ACTIVITY_TYPE,
									  ACTIVITY_CONFIDENCE};
}


text:
package eugene.behavioral.interceptingfilter;

/**
 * Created by Jian on 2015/8/12.
 */
/**
 * Concrete implementation of filter
 * This checks for the deposit code
 * @author joshzambales
 *
 */
public class DepositFilter extends AbstractFilter {

    @Override
    public String execute(Order order) {
        String result = super.execute(order);
        if (order.getDepositNumber() == null || order.getDepositNumber().isEmpty()) {
            return result + "Invalid deposit number! ";
        } else {
            return result;
        }
    }
}


text:
package xesende

import (
	"encoding/xml"
	"time"
)

// Accounts returns a list of accounts the user is on.
func (c *Client) Accounts() (*AccountsResponse, error) {
	req, err := c.newRequest("GET", "/v1.0/accounts", nil)
	if err != nil {
		return nil, err
	}

	var v accountsResponse
	if _, err = c.do(req, &v); err != nil {
		return nil, err
	}

	response := &AccountsResponse{
		Accounts: make([]AccountResponse, len(v.Accounts)),
	}

	for i, account := range v.Accounts {
		response.Accounts[i] = AccountResponse{
			ID:                account.ID,
			URI:               account.URI,
			Reference:         account.Reference,
			Label:             account.Label,
			Address:           account.Address,
			Type:              account.Type,
			MessagesRemaining: account.MessagesRemaining,
			ExpiresOn:         account.ExpiresOn.Time,
			Role:              account.Role,
			SettingsURI:       account.Settings.URI,
		}
	}

	return response, nil
}

// AccountsResponse is a list of accounts.
type AccountsResponse struct {
	Accounts []AccountResponse
}

// AccountResponse is a single account.
type AccountResponse struct {
	ID                string
	URI               string
	Reference         string
	Label             string
	Address           string
	Type              string
	MessagesRemaining int
	ExpiresOn         time.Time
	Role              string
	SettingsURI       string
}

type accountsResponse struct {
	XMLName  xml.Name                  `xml:"http://api.esendex.com/ns/ accounts"`
	Accounts []accountsResponseAccount `xml:"account"`
}

type accountsResponseAccount struct {
	ID                string       `xml:"id,attr"`
	URI               string       `xml:"uri,attr"`
	Reference         string       `xml:"reference"`
	Label             string       `xml:"label"`
	Address           string       `xml:"address"`
	Type              string       `xml:"type"`
	MessagesRemaining int          `xml:"messagesremaining"`
	ExpiresOn         accountsTime `xml:"expireson"`
	Role              string       `xml:"role"`
	Settings          struct {
		URI string `xml:"uri,attr"`
	} `xml:"settings"`
}

const accountsTimeFormat = "2006-01-02T15:04:05"

type accountsTime struct {
	time.Time
}

func (t accountsTime) MarshalText() ([]byte, error) {
	return []byte(t.Format(accountsTimeFormat)), nil
}

func (t *accountsTime) UnmarshalText(data []byte) error {
	g, err := time.ParseInLocation(accountsTimeFormat, string(data), time.UTC)
	if err != nil {
		return err
	}
	*t = accountsTime{g}
	return nil
}


text:
Search for a Crunchyroll episode and print its url to stdout.

Comes with `dmenu-crunchy-search`, which calls `dmenu` for input,
notifies using `notify-send`, and streams using `livestreamer`.

All dependencies can be substituted via command-line arguments.


text:
from ubuntu:16.04

RUN apt-get update &&  apt-get install -y build-essential fakeroot devscripts inetutils-tools inetutils-ping apt-utils vim aptitude wget xsel openssh-server openssh-client python-bzrlib python-paramiko software-properties-common


text:
from nipype.testing import assert_equal
from nipype.interfaces.fsl.maths import MeanImage

def test_MeanImage_inputs():
    input_map = dict(args=dict(argstr='%s',
    ),
    dimension=dict(argstr='-%smean',
    position=4,
    usedefault=True,
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    in_file=dict(argstr='%s',
    mandatory=True,
    position=2,
    ),
    internal_datatype=dict(argstr='-dt %s',
    position=1,
    ),
    nan2zeros=dict(argstr='-nan',
    position=3,
    ),
    out_file=dict(argstr='%s',
    genfile=True,
    hash_files=False,
    position=-2,
    ),
    output_datatype=dict(argstr='-odt %s',
    position=-1,
    ),
    output_type=dict(),
    terminal_output=dict(mandatory=True,
    nohash=True,
    ),
    )
    inputs = MeanImage.input_spec()

    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(inputs.traits()[key], metakey), value

def test_MeanImage_outputs():
    output_map = dict(out_file=dict(),
    )
    outputs = MeanImage.output_spec()

    for key, metadata in output_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(outputs.traits()[key], metakey), value


text:
package com.optimuscode.core.common.model;

import com.optimuscode.core.utils.SupportedLanguage;

import java.util.ArrayList;
import java.util.List;

public class CompilationUnit extends ProcessingUnit{

    protected List<SourceUnit> sources;

    private SupportedLanguage language = SupportedLanguage.Java;

    public CompilationUnit(SupportedLanguage language){
        this.sources = new ArrayList<SourceUnit>();
        this.language = language;
    }

    public void addSource(final String name, final String source){
        final String extension = sourceExtension.get(language);
        this.sources.add(new SourceUnit(name, source, extension));
    }

    public List<SourceUnit> getSources(){
        return this.sources;
    }

    public SupportedLanguage getLanguage() {
        return language;
    }

    public void setLanguage(final SupportedLanguage language) {
        this.language = language;
    }
}