<?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 ExecuteScripts extends Wizard
{
  
  public function __construct()
  {
    $this->wizardName = 'Execute Scripts';
    $this->wizardDescription
      = 'Dieser Wizard führt Scripte aus, die im Unterordner '
      . '/scripts liegen.';
  }

  
  public function getServerConfiguration()
  {
    $return = "<table class='table'>\n";
    $return .= "<tr class='tr'><th class='th' colspan='2'><p class='font wizardbody'>Folgende Konfiguration wird zum Einspielen der Skripte verwendet:</p></th></tr>\n";

    
    $conInfo = DBConnectionInfo::getInstance();
    $return .= "<tr class='tr'><td class='td key'><p class='font wizardbody'>Datenbanktyp:</p></td><td class='td value'><p class='font wizardbody'>" . CleanOperations::cleanStringForHtml($conInfo->db_typ) . "</p></td></tr>\n";
    $return .= "<tr class='tr'><td class='td key'><p class='font wizardbody'>Servername:</p></td><td class='td value'><p class='font wizardbody'>" . CleanOperations::cleanStringForHtml($conInfo->db_server) . "</p></td></tr>\n";
    $return .= "<tr class='tr'><td class='td key'><p class='font wizardbody'>Datenbank:</p></td><td class='td value'><p class='font wizardbody'>" . CleanOperations::cleanStringForHtml($conInfo->db_name) . "</p></td></tr>\n";
    $return .= "<tr class='tr'><td class='td key'><p class='font wizardbody'>Benutzer:</p></td><td class='td value'><p class='font wizardbody'>" . CleanOperations::cleanStringForHtml($conInfo->db_user) . "</p></td></tr>\n";
    $return .= '</table>' . BR_WT . "\n";

    return $return;
  }

  
  public function getScriptListGUI()
  {
    $return = '';
    if (file_exists('./scripts')) {
      $return .= "<form action='' method='POST'>\n";
      $ary = $this->getScriptFiles('./scripts');
      if (count($ary) > 0) {
        $return
          .= "<p class='font wizardbody'>Diese Skriptdateien wurden in dem Unterordner "
          . '/scripts gefunden. Markieren Sie alle, die Sie ausführen wollen und klicken '
          . 'dann bitte auf Ok.</p>' . BR_WT . "\n";

        
        $return .= '<input type="checkbox" name="renamefiles" value="1"><span class="font">Dateien nicht '
            . 'l&ouml;schen sondern umbenennen und in den Ordner imported_scripts verschieben</span>' . BR_WT . BR_WT;

        
        for ($i = 0; $i < count($ary); $i++) {
          $return .= "<input type='checkbox' name='" . $i . "' value='" . CleanOperations::cleanStringForHtml($ary[$i]) . "' checked>"
            . "<a href='scripts/" . CleanOperations::cleanStringForHtml($ary[$i]) . "' class='font link'>"
            . CleanOperations::cleanStringForHtml($ary[$i]) . ' (' . round(filesize('scripts/' . $ary[$i]) / 1024, 2) . ' KB)'
            . '</a>' . BR_WT . "\n";
        }
        $return
            .= "<a class='font smallfont link' href='#' onClick='javascript:"
            . $this->GetJavascriptCheckCode(true, count($ary)) . "'"
            . "'>Alle markieren</a>" . BR_WT . "\n";

        $return
             .= "<a class='font smallfont link' href='#' onClick='javascript:"
             . $this->GetJavascriptCheckCode(false, count($ary)) . "'"
             . "'>Alle demarkieren</a>\n";

        $return .= BR_WT . BR_WT . "\n";

        
        $return .= "<input type='hidden' name='filecount' value='" . count($ary) . "'>\n";
        $return .= "<input type='hidden' name='execute' value='1'>\n";
        $return .= "<input type='submit' value='Ok'>\n";
        $return .= "</form>\n";
      } else {
        $return .= "<p class='font wizardbody'>Es wurden keine Dateien in dem Unterordner /scripts gefunden! "
        . "Bitte uploaden Sie die einzuspielenden Dateien (z.B. per FTP) in den Unterordner /scripts!</p>\n";
      }
    } else {
      $return .= "<p class='font wizardbody'>Der Unterordner /scripts existiert nicht. Bitte legen Sie diesen "
      . "Ordner an und uploaden Sie die einzuspielenden Dateien!</p>\n";
    }

    return $return;
  }

  
  public function GetJavascriptCheckCode($pChecked, $pCheckboxCount)
  {
    $result = '';
    $checked = $pChecked ? 'true' : 'false';

    for ($i = 0; $i < $pCheckboxCount; $i++) {
      $result .= 'document.getElementsByName("' . CleanOperations::cleanStringForJs($i) . '")[0].checked = ' . $checked . ';';
    }

    return $result;
  }

  
  public function executeScript($pFilename, $pRename = false)
  {
    $filename = './scripts/' . $pFilename;


    
    $handle = fopen($filename, 'r');
    $sqlary = array();
    
    while (! feof($handle)) {
      $sqlary[] = fgets($handle);
    }
    fclose($handle);

    $return = '';

    $dboperation = DBOperation::getInstance(1);
    foreach ($sqlary as $sql) {
      $statement = trim($sql);

      if ($statement != '') {
        $dboperation->query($statement);
      } 
    }

    $return .= "<p class='font wizardbody'><img src='img/success.png'> " . CleanOperations::cleanStringForHtml($pFilename) . ' wurde erfolgreich ausgeführt';
    if ($pRename) {
      if (rename($filename, './imported_scripts/' . $pFilename . '.done')) {
        $return .= ' und in den Ordner imported_scripts verschoben';
      }
    } else { 
      if (unlink($filename)) {
        $return .= ' und gelöscht';
      }
    }
    $return .= "!</p>\n";

    return $return;
  }

  
  public function StartExecuteScripts()
  {
    $return = BR_WT . "\n";
    $fileCount = $_POST['filecount'];
    $rename = $_POST['renamefiles'] == 1;
    for ($i = 0; $i < $fileCount; $i++) {
      if (isset($_POST[$i])) { 
        $return .= $this->executeScript($_POST[$i], $rename);
      } 
    }

    $return .= BR_WT . "<a href='index.php' class='font link'>Zurück</a>" . BR_WT . "\n";
    $return .= BR_WT . "\n";

    return $return;
  }

  
  public function _getWizardBody()
  {
    $return = '';
    if (isset($_POST['execute'])) { 

      $return .= $this->StartExecuteScripts();
    } else {
      $return .= $this->getServerConfiguration();
      $return .= $this->getScriptListGUI();
    }

    return $return;
  }

  
  public function getScriptFiles($pPath)
  {
    $pPath = $pPath . '/';
    $ary = array();
    $handle = opendir($pPath); 
    while ($file = readdir($handle)) {
      if ($file != '.' && $file != '..' and is_file($pPath . $file)) { 
      array_push($ary, $file);
      } 
    }
    closedir($handle); 

    sort($ary);

    return $ary;
  }
}

$execScript = new ExecuteScripts();
$execScript->start();