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

define('ISWIZARDS', true);
include_once '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..'
. DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'constants.php';


class ListSightsForTranslation extends Wizard
{
  public function __construct()
  {
    $this->wizardName = 'List Sights for Translation';
    $this->wizardDescription = 'Dieser Wizard listet alle Texte/Begriffe in Sichten von '
            . KUFERWEB . ' auf, die für die Mehrsprachigkeit übersetzt werden müssen.';
  }

  
  public function _getWizardBody()
  {
    $sights = array_merge(SightsAPI::getSights(-1), SightsAPI::getSights(\ToolsAPI::TOOL_WEBBASYS));

    

    if (GetOperations::isDefined('show_sights')) {
      $body = $this->_createOutputTableFromSights($sights);
    } elseif (GetOperations::isDefined('export_csv')) {
      $body = $this->_exportSightsToCsv($sights);
    } else {
      $body = '<span>Drücken Sie <a class="link" href="index.php?show_sights=1">hier</a>, um Sichteninhalte auf der Seite in einer Tabelle auszugeben.</span><br /><br />'
              . '<span>Drücken Sie <a class="link" href="index.php?export_csv=1">hier</a>, um Sichteninhalte in eine Datei zu exportieren.</span>';
    }

    return $body;
  }

  
  private function _exportSightsToCsv($pSights)
  {
    $list = array();
    $list[] = 'Alle mit * markierten Zeilen müssen nicht übersetzt werden';

    $exportname = 'sights_for_translation_' . date('Ymd_His') . '.csv';
    $fehlermeldung = '<span>Die Datei ' . CleanOperations::cleanStringForHtml($exportname) . 'konnte nicht angelegt werden. Bitte überprüfen Sie die Schreibrechte des Web-Servers auf das Verzeichnis '
            . CleanOperations::cleanStringForHtml(dirname(__FILE__)) . '</span>';
    $fileHandle = @fopen($exportname, 'w');
    if (!$fileHandle) {
      return $fehlermeldung;
    }

    foreach ($pSights as $sight) {
      $sight = $this->_filterSightContent($sight, "\r\n");

      if ($sight->header !== '' || $sight->body !== '' || $sight->footer !== '' || $sight->nodata !== '' || $sight->nocolumn !== '') {

        
        $list = array_merge($list, array('', '**Sicht: ' . $sight->description . ' (' . $sight->id . ')**'));
        if ($sight->header != '') {
          $list = array_merge($list, array('*Header*'), explode("\r\n", $sight->header));
        }
        if ($sight->body != '') {
          $list = array_merge($list, array('*Body*'), explode("\r\n", $sight->body));
        }
        if ($sight->footer != '') {
          $list = array_merge($list, array('*Footer*'), explode("\r\n", $sight->footer));
        }
        if ($sight->nodata != '') {
          $list = array_merge($list, array('*NoData*'), explode("\r\n", $sight->nodata));
        }
        if ($sight->nocolumn != '') {
          $list = array_merge($list, array('*NoColumn*'), explode("\r\n", $sight->nocolumn));
        }
      } else {
        $list = array_merge($list, array('', '**Sicht: ' . $sight->description . ' (' . $sight->id . ')** ist LEER'));
      }
    }
    $fields = array();
    foreach ($list as $field) {
      if ($field != '') {
        $fields[] = array($field);
      }
    }

    foreach ($fields as $field) {
      fputcsv($fileHandle, $field, ';');
    }
    fclose($fileHandle);

    if (file_exists($exportname)) {
      return 'Sichteninhalte erfolgreich in Datei <a href="' . CleanOperations::cleanStringForHtml($exportname) . '">' . CleanOperations::cleanStringForHtml($exportname) . '</a> exportiert.';
    } else {
      return $fehlermeldung;
    }
  }

  
  private function _createOutputTableFromSights($pSights)
  {
    $body = '<link rel="stylesheet" type="text/css" href="listsightsfortranslation.css">';
    foreach ($pSights as $sight) {
      $sight = $this->_filterSightContent($sight);

      if ($sight->header !== '' || $sight->body !== '' || $sight->footer !== '' || $sight->nodata !== '' || $sight->nocolumn !== '') {
        $body .= '<h2>' . CleanOperations::cleanStringForHtml($sight->description) . ' (' . CleanOperations::cleanStringForHtml($sight->id) . ')' . '</h2>'
                    . '<table>'
                      . '<tr>'
                        . '<th>Header</th>' 
                        . '<th>Body</th>' 
                        . '<th>Footer</th>' 
                        . '<th>noData</th>' 
                        . '<th>noColumn</th>'
                      . '</tr>'
                      . '<tr>'
                        . '<td>' . $sight->header . '</td>'
                        . '<td>' . $sight->body . '</td>'
                        . '<td>' . $sight->footer . '</td>'
                        . '<td>' . $sight->nodata . '</td>'
                        . '<td>' . $sight->nocolumn . '</td>'
                      . '</tr>'
                    . '</table>';
      } else {
        $body .= '<h2>' . CleanOperations::cleanStringForHtml($sight->description) . ' (' . CleanOperations::cleanStringForHtml($sight->id) . ') ist LEER</h2>';
      }
    }

    return $body;
  }

  
  private function _filterSightContent($pSight, $pLineBreak = '<br />')
  {
    $objVars = get_object_vars($pSight);
    foreach ($objVars as $var => $value) {
      if (in_array($var, array('id', 'description', 'toolid'))) {
        continue;
      }

      $matches = array();

      $value = strip_tags($value); 
      $value = str_replace('(§IF§)', '', $value); 
      $value = preg_replace('/".*"\\s*(>|<|==|!=|>=|<=|<>)\\s*".*"/i', '', $value); 
      $value = preg_replace('/\\belse\\b/i', '', $value); 
      $value = preg_replace('/\\s*\\{%[^}]+%\\}/', '', $value); 
      $value = preg_replace('/"[a-z]+\\.[a-z]+"/i', '', $value); 
      $value = preg_replace('#(http|https)://([a-z0-9]+\\.)+[a-z]+#i', '', $value); 
      $value = preg_replace('/\\([^a-zäöüÄÖÜ:]/i', '', $value); 
      $value = preg_replace('/[^a-zäöüÄÖÜß:]\\)/i', '', $value); 
      $value = StringOperations::html_entity_decode($value);

      
      preg_match_all('/([a-zA-ZäöüÄÖÜß\'\\(\\) \\-\\.,:]*)|([0-9]+,[0-9\\-]{2}\\s*)/', $value, $matches);

      
      $matches[0] = preg_replace('/^\\s*(\\-|\\+)/', '', $matches[0]);

      $items = array();
      $i = 0;
      foreach ($matches[0] as $match) {
        if (trim($match) != '') {
          if (StringOperations::strlen(trim($match)) === 1 && preg_match('/[,\\.:\\-]/', trim($match))) {
            if (isset($items[$i - 1])) {
              $items[$i - 1] .= trim($match);
            }
          } else {
            $items[$i] = trim($match);
            $i++;
          }
        }
      }
      $pSight->{$var} = implode($pLineBreak, $items);
    }

    return $pSight;
  }
}

$listSightsForTranslation = new ListSightsForTranslation();
$listSightsForTranslation->start();