<?php
// Klassen fuer PLP-TV
// by Joachim Braun
// created 2010-10-02

require_once('schule.config.inc.php');
include_once('iCal/class.iCal.inc.php');

//fuer Zend-Framework:
set_include_path('/www/data/ftp/rsmbobbn/_sys/libs/' . PATH_SEPARATOR . get_include_path());
require("Zend/Validate.php");
require("Zend/Mail.php");
require("Zend/Mail/Transport/Smtp.php");
require("Zend/Pdf.php");


// *************************
// * class plp3_terminvereinbarung 
// *
// * laedt alle Daten der Schule (via Schulnummer)
// * das sind
// *
// *  - alle PLPs, bei der die Schule die grundstaendige Schule ist, incl. aktueller Stand
// *  - alle PLPs, bei der die Schule die Einsatzschule ist, incl. aktueller Stand
// *  - alle PLPs, bei der die Schule die pruefende Schule ist, incl. aktueller Stand
// *
// *************************

class plp3_terminvereinbarung {
  var $schulnummer = "";
  var $schuljahr = 0;
  var $day_shift_eroeffnung=1;  // 1 == 1 Werktag vorher (Montag bis Freitag)
  var $type="";
  var $logonOk = false;

  var $isAdmin=false;
  // Schuldaten
  var $schuldaten = array();
  var $schuldaten_geladen = false;

  // Refs der PLP
  var $grund_refs=array();
  var $refGSgeladen=false;
  var $einsatz_refs=array();
  var $refESgeladen=false;
  var $pruef_refs=array();
  var $refPSgeladen=false;

  // plp3-Data
  var $plp_data=array();
  var $plp_data_geladen=false;

  // plp3-Data settings
  var $plp_data_settings_regexp=array(
    'text_all'    => array ('regexp' => '/^.+$/'                                                                       , 'errormesssage' => 'Fehler'),
    'text'        => array ('regexp' => '/^[\ a-zA-Z0-9äÄöÖüÜßáÁúÚóÓéÉíÌàÀòÒìÌèÈâÂôÔûÛ!?\-\.\:^_#+*~\(\)%=\/]*$/'      , 'errormesssage' => 'Ungültige Zeichen!'),
    'int'         => array ('regexp' => '/^[0-9]*$/'                                                                   , 'errormesssage' => 'Keine Zahl!'),
    'datum'       => array ('regexp' => '/^(\d\d\d\d\-\d\d\-\d\d)$/'                                                   , 'errormesssage' => 'Datum ungültig!'),
    'datum_us_de' => array ('regexp' => '/^(\d\d\d\d\-\d\d\-\d\d|\d\d\.\d\d\.\d\d\d\d)$/'                              , 'errormesssage' => 'Datum ungültig!'),
    'zeit'        => array ('regexp' => '/^\d\d:\d\d(:\d\d)?$/'                                                        , 'errormesssage' => 'Zeitangabe ungültig!'),
    'uhrzeit'     => array ('regexp' => '/^\d\d:\d\d$/'                                                                , 'errormesssage' => 'Zeitangabe ungültig!')
  );
  var $plp_data_settings=array(
    'ps' => array (
        'text'  => array( 'plp3_vorsitz', 'plp3_erstpruefer' ),
        'datum' => array( 'plp3_datum' ),
        'zeit'  => array( 'plp3_zeit_von', 'plp3_zeit_bis' ),
		'int'   => array( 'plp3_vorsitz_BRN_Freigabe', 'plp3_erstpruefer_BRN_Freigabe')
      ),
    'es' => array (
        'text'  => array( 'plp3_zweitpruefer', 'plp3_jgst', 'plp3_klasse', 'plp3_betreuungslehrer', 'plp3_fachlehrer' ), // 'plp3_fach', 'plp3_zfl', 'plp3_kirchliche_oberbehoerde',
        'datum' => array( 'vorstunde_datum' ),
        'zeit'  => array( 'vorstunde_zeit_von', 'vorstunde_zeit_bis' ),
		'int'   => array( 'plp3_zweitpruefer_BRN_Freigabe', 'plp3_betreuungslehrer_BRN_Freigabe', 'plp3_fachlehrer_BRN_Freigabe')
      ),
    'gs' => array (
        'text_all' => array( 'plp3_thema'),  
		//2018-02-28: Änderung, da ZFLs sich selbst eintragen, somit darf dieses Feld nicht upgedatet werden
		'text'     => array( 'plp3_seminarleitung_gs', 'plp3_kirchliche_oberbehoerde', 'eroeffnung_an_schule', 'eroeffnung_durch'), // , 'bemerkung'
        'int'      => array( 'plp3_zeitverlaengerung_auf_minuten','plp3_zeitverlaengerung', 'eroeffnung_erledigt', 'plp3_kirchliche_oberbehoerde_BRN_Freigabe', 'eroeffnung_durch_BRN_Freigabe'),
		//'text'     => array( 'plp3_seminarleitung_gs', 'plp3_zfl', 'plp3_kirchliche_oberbehoerde', 'eroeffnung_an_schule', 'eroeffnung_durch'), // , 'bemerkung'
        //'int'      => array( 'plp3_zeitverlaengerung_auf_minuten','plp3_zeitverlaengerung', 'eroeffnung_erledigt', 'plp3_zfl_BRN_Freigabe', 'plp3_kirchliche_oberbehoerde_BRN_Freigabe', 'eroeffnung_durch_BRN_Freigabe'),
        'datum'    => array( 'eroeffnung_datum' )
      )
  );
  
  var $plp_data_settings_necessary_regexp_bad=array( // nur Test auf leer !!!
    'text_all'    => '/^\s*$/',
    'text'        => '/^\s*$/',
    'datum'       => '/^0000-00-00$/',
    'datum_us_de' => '/^(0000-00-00|0000\.00\.00)$/',
    'zeit'        => '/^00:00:00$/' ,
    'uhrzeit'     => '/^00:00$/'
  );
  var $plp_data_settings_necessary=array(  // notwendige Eingaben
    'ps' => array (
        'text'  => array( 'plp3_vorsitz', 'plp3_erstpruefer' ),
        'datum' => array( 'plp3_datum' ),
        'zeit'  => array( 'plp3_zeit_von', 'plp3_zeit_bis' )
      ),
    'es' => array (
        'text'  => array( 'plp3_zweitpruefer', 'plp3_jgst', 'plp3_klasse', 'plp3_betreuungslehrer' ), // 'plp3_fach', 'plp3_betreuungslehrer', 'plp3_fachlehrer', 'plp3_zfl',
        'datum' => array( 'vorstunde_datum' ),
        'zeit'  => array( 'vorstunde_zeit_von', 'vorstunde_zeit_bis' )
      ),
    'gs' => array (
        'text_all' => array( 'plp3_thema'),  
		'text'  => array( 'eroeffnung_durch', 'eroeffnung_an_schule' ),
        'datum' => array( 'eroeffnung_datum' )
      )
  );
  // AUSNAHME: SchPsy
  var $plp_data_settings_necessary_AUSNAHME_PLP3_FACH=array(
  	'es' => array( 'SchPsy' => true )
  );
  var $no_details_for_PLP3_FACH=array(
  	'es' => array( 'SchPsy' => true )  	
  );
  
  // stati
  var $plp_status_first = 'ps';
  var $plp_status_last  = 'fertig';
  var $plp_status_follow=array(
    'ps'  => 'es',
    'es'  => 'gs',
    'gs'  => 'fertig'
  );
  //var $plp_status_ready = array();

  // error
  var $error=array();
  var $error_data=array();

  // more
  var $showPLZ=false;
  var $debug=0;
  var $html_newline="<br>";


// statt var getExportSettings -> geht schneller als array
private function _getExportSettings($setSize=true){
  return array(
    'pkz'                                => array( 'headline' => 'PKZ',                          'size' =>   9,   'setSize' => $setSize ),
    'plp3_fach'                          => array( 'headline' => 'fach_plp_3',                   'size' =>  10,   'setSize' => $setSize ),
    'plp3_klasse'                        => array( 'headline' => 'klasse',                       'size' =>  10,   'setSize' => $setSize ),
    'plp3_jgst'                          => array( 'headline' => 'jgst',                         'size' =>   2,   'setSize' => false    ),
    'snr_pruef'                          => array( 'headline' => 'snr_pruef',                    'size' =>   5,   'setSize' => false    ),
    'plp3_vorsitz'                       => array( 'headline' => 'plp3_vorsitz',                 'size' => 100,   'setSize' => $setSize ),
    'plp3_erstpruefer'                   => array( 'headline' => 'plp3_erstpruefer',             'size' => 100,   'setSize' => $setSize ),
    'plp3_zweitpruefer'                  => array( 'headline' => 'plp3_zweitpruefer',            'size' => 100,   'setSize' => $setSize ),
    'plp3_betreuungslehrer'              => array( 'headline' => 'plp3_betreuungslehrer',        'size' => 100,   'setSize' => $setSize ),
    'plp3_fachlehrer'                    => array( 'headline' => 'plp3_fachlehrer',              'size' => 100,   'setSize' => $setSize ),
    'plp3_zfl'                           => array( 'headline' => 'plp3_zfl',                     'size' => 100,   'setSize' => $setSize ),
    'plp3_kirchliche_oberbehoerde'       => array( 'headline' => 'plp3_kirchliche_oberbehoerde', 'size' => 100,   'setSize' => $setSize ),
    'vorstunde_datum'                    => array( 'headline' => 'vorstunde_datum',              'size' =>  10,   'setSize' => false    ),
    'vorstunde_zeit_von'                 => array( 'headline' => 'vorstunde_zeit_von',           'size' =>  10,   'setSize' => false    ),
    'vorstunde_zeit_bis'                 => array( 'headline' => 'vorstunde_zeit_bis',           'size' =>  10,   'setSize' => false    ),
    'plp3_datum'                         => array( 'headline' => 'plp3_datum',                   'size' =>  10,   'setSize' => $setSize ),
    'plp3_zeit_von'                      => array( 'headline' => 'plp3_zeit_von',                'size' =>  10,   'setSize' => false    ),
    'plp3_zeit_bis'                      => array( 'headline' => 'plp3_zeit_bis',                'size' =>  10,   'setSize' => false    ),
    'plp3_zeitverlaengerung_auf_minuten' => array( 'headline' => 'plp3_zeitverlaengerung_min',   'size' =>   3,   'setSize' => false    ),
    'eroeffnung_datum'                   => array( 'headline' => 'datum_eroeffnung',             'size' =>  10,   'setSize' => false    ),
    'plp3_thema'                         => array( 'headline' => 'plp3_thema',                   'size' => 500,   'setSize' => $setSize )
  );
}



// *************************
// * function plp3_terminvereinbarung($Schulnummer, $Schuljahr)
// * Konstruktor
function plp3_terminvereinbarung($Schulnummer, $Schuljahr, $type="", $sortierung="") {
  $countTmp=preg_match('/^\d\d\d\d$/', $Schulnummer);
  $countTmp2=preg_match('/^\d\d\d\d$/', $Schuljahr);
  $countTmp3=preg_match('/^[a-zA-Z0-9]*$/', $Schuljahr);
  $countTmp4=preg_match('/^[a-zA-Z0-9_]*$/', $sortierung);
  $this->logonOk = ( $countTmp and $countTmp2 and  $countTmp3 and  $countTmp4 and ($Schuljahr >= 2010) );
  if ($this->logonOk) {
    $this->schulnummer=$Schulnummer;
    $this->schuljahr=$Schuljahr;
    $this->type=$type;
    $this->sortierung=$sortierung;
  }
  return $this->logonOk;
}

// *************************
// * get...
function getSchuldaten()    { return $this->schuldaten;   }
function istSeminarschule() { return ($this->schuldaten['seminar']=='ja'); }
function getSchulnummer()   { return $this->schulnummer;   }
function getPLP3_GS()       { return $this->grund_refs;   }
function getPLP3_ES()       { return $this->einsatz_refs; }
function getPLP3_PS()       { return $this->pruef_refs;   }
function getPLP3_Detail()   { return $this->plp_data;     }
function getDetailErrors()  { return $this->error_data;   }
function getStatus()        { return $this->plp_data['status']; }
function nextStatusOf($status) { return $this->plp_status_follow[$status]; }
//function getStatiReady()    { return $this->plp_status_ready; }


// *************************
// * set...
function setStatus($status) { $this->plp_data['status']=$status; }

function setAdmin($isadmin) { $this->isAdmin=$isadmin; }

// *************************
// * test...
function testChangeStatus($c_status) {
  if ($this->debug>=3) { echo $this->html_newline, $this->html_newline, "change status: ", $c_status, ' - ', 'data status: ', $this->plp_data['status'], $this->html_newline, $this->html_newline; }
  return ($this->plp_data['status']==$c_status);
}


// *************************
// * saveDetails()
// * speichert die Daten, die ueber POST uebertragen werden
function saveDetails_ALT_LOESCHEN_AB_2011_01_01() {
  if ($this->logonOk) {
    $this->ladeSchuldaten();
  }
}


// *************************
// * ladePLP3s()
// * laedt alle Refs, in der die akt. Schule als Schule der PLP eingetragen ist
function ladePLP3s($typ="all", $options=array()) {
  if ($this->logonOk) {
    if ($typ=="all" || $typ=="gs") { $this->ladePLP3sRefsAlsGrundstaendigeSeminarschule( $options ); }
    if ($typ=="all" || $typ=="es") { $this->ladePLP3sRefsAlsEnsatzschule( $options ); }
    if ($typ=="all" || $typ=="ps") { $this->ladePLP3sRefsAlsPruefendeSeminarschule( $options ); }
  }
}


private function querySelectFrom_PLP3s() {
  return "
      SELECT
        plp_tv_main.*,
        plp_tv_main.idplptvmain as id,

        plp_tv_status.sort_ps as status_sort_ps,
        plp_tv_status.sort_es as status_sort_es,
        plp_tv_status.sort_gs as status_sort_gs,

        sem_faecher1.bezeichnung as fach1_bezeichnung,
        sem_faecher2.bezeichnung as fach2_bezeichnung,
        sem_faecher3.bezeichnung as fach3_bezeichnung,
        sem_faecherPLP3.bezeichnung as plp3_fach_bezeichnung,

        schulenGS.Schulnr as schulenGS_Schulnr,
        schulenGS.Schulname as schulenGS_Schulname,
        schulenGS.Schulname2 as schulenGS_Schulname2,
        schulenGS.Strasse as schulenGS_Strasse,
        schulenGS.PLZ as schulenGS_PLZ,
        schulenGS.Ort as schulenGS_Ort,
        schulenGS.Telefon as schulenGS_Telefon,
        schulenGS.email as schulenGS_Mail,
        schulenGS.Fax as schulenGS_Fax,
        schulenGS.seminar as schulenGS_seminar,

        schulenES.Schulnr as schulenES_Schulnr,
        schulenES.Schulname as schulenES_Schulname,
        schulenES.Schulname2 as schulenES_Schulname2,
        schulenES.Strasse as schulenES_Strasse,
        schulenES.PLZ as schulenES_PLZ,
        schulenES.Ort as schulenES_Ort,
        schulenES.Telefon as schulenES_Telefon,
        schulenES.email as schulenES_Mail,
        schulenES.Fax as schulenES_Fax,
        schulenES.seminar as schulenES_seminar,

        schulenPS.Schulnr as schulenPS_Schulnr,
        schulenPS.Schulname as schulenPS_Schulname,
        schulenPS.Schulname2 as schulenPS_Schulname2,
        schulenPS.Strasse as schulenPS_Strasse,
        schulenPS.PLZ as schulenPS_PLZ,
        schulenPS.Ort as schulenPS_Ort,
        schulenPS.Telefon as schulenPS_Telefon,
        schulenPS.email as schulenPS_Mail,
        schulenPS.Fax as schulenPS_Fax,
        schulenPS.seminar as schulenPS_seminar,

        schulen_geodatenGS.Laenge as schulen_geodatenGS_Laenge,
        schulen_geodatenGS.Breite as schulen_geodatenGS_Breite,
        schulen_geodatenES.Laenge as schulen_geodatenES_Laenge,
        schulen_geodatenES.Breite as schulen_geodatenES_Breite,
        schulen_geodatenPS.Laenge as schulen_geodatenPS_Laenge,
        schulen_geodatenPS.Breite as schulen_geodatenPS_Breite


      FROM
        ((((((((((((
        plp_tv_main)
        LEFT JOIN plp_tv_status ON plp_tv_status.status = plp_tv_main.status)
        LEFT JOIN plp_tv_sem_faecher as sem_faecher1 ON plp_tv_main.fach1 = sem_faecher1.fach)
        LEFT JOIN plp_tv_sem_faecher as sem_faecher2 ON plp_tv_main.fach2 = sem_faecher2.fach)
        LEFT JOIN plp_tv_sem_faecher as sem_faecher3 ON plp_tv_main.fach3 = sem_faecher3.fach)
        LEFT JOIN plp_tv_sem_faecher as sem_faecherPLP3 ON plp_tv_main.plp3_fach = sem_faecherPLP3.fach)
        LEFT JOIN schulen as schulenGS ON plp_tv_main.snr_gs = schulenGS.Schulnr)
        LEFT JOIN schulen as schulenES ON plp_tv_main.snr_einsatz = schulenES.Schulnr)
        LEFT JOIN schulen as schulenPS ON plp_tv_main.snr_pruef = schulenPS.Schulnr)
        LEFT JOIN schulen_geodaten as schulen_geodatenGS ON plp_tv_main.snr_gs = schulen_geodatenGS.schulnr)
        LEFT JOIN schulen_geodaten as schulen_geodatenES ON plp_tv_main.snr_einsatz = schulen_geodatenES.schulnr)
        LEFT JOIN schulen_geodaten as schulen_geodatenPS ON plp_tv_main.snr_pruef = schulen_geodatenPS.schulnr)
        ";
}

private function querySelectFrom_ORDER_PLP3s($type='') {
  $order='';
  switch ($this->sortierung) {
    case 'sort_ref_up':
      $order=' ORDER BY ref_nachname ASC, ref_vorname ASC ';
    break;
    case 'sort_ref_down':
      $order=' ORDER BY ref_nachname DESC, ref_vorname DESC ';
    break;
    case 'sort_pruef_up':
      $order=' ORDER BY schulenPS.Ort ASC, ref_nachname ASC, ref_vorname ASC ';
    break;
    case 'sort_pruef_down':
      $order=' ORDER BY schulenPS.Ort DESC, ref_nachname DESC, ref_vorname DESC ';
    break;
    case 'sort_einsatz_up':
      $order=' ORDER BY schulenES.Ort ASC, ref_nachname ASC, ref_vorname ASC ';
    break;
    case 'sort_einsatz_down':
      $order=' ORDER BY schulenES.Ort DESC, ref_nachname DESC, ref_vorname DESC ';
    break;
    case 'sort_grund_up':
      $order=' ORDER BY schulenGS.Ort ASC, ref_nachname ASC, ref_vorname ASC ';
    break;
    case 'sort_grund_down':
      $order=' ORDER BY schulenGS.Ort DESC, ref_nachname DESC, ref_vorname DESC ';
    break;
    case 'sort_pruef_plz_up':
      $order=' ORDER BY schulenPS.PLZ ASC, ref_nachname ASC, ref_vorname ASC ';
      $this->showPLZ=1;
    break;
    case 'sort_pruef_plz_down':
      $order=' ORDER BY schulenPS.PLZ DESC, ref_nachname DESC, ref_vorname DESC ';
      $this->showPLZ=1;
    break;
    case 'sort_einsatz_plz_up':
      $order=' ORDER BY schulenES.PLZ ASC, ref_nachname ASC, ref_vorname ASC ';
      $this->showPLZ=1;
    break;
    case 'sort_einsatz_plz_down':
      $order=' ORDER BY schulenES.PLZ DESC, ref_nachname DESC, ref_vorname DESC ';
      $this->showPLZ=1;
    break;
    case 'sort_grund_plz_up':
      $order=' ORDER BY schulenGS.PLZ ASC, ref_nachname ASC, ref_vorname ASC ';
      $this->showPLZ=1;
    break;
    case 'sort_grund_plz_down':
      $order=' ORDER BY schulenGS.PLZ DESC, ref_nachname DESC, ref_vorname DESC ';
      $this->showPLZ=1;
    break;
    case 'sort_status_up':
      $sort_status=(
        $type=='ps' ? 'status_sort_ps' : (
        $type=='es' ? 'status_sort_es' : (
        $type=='gs' ? 'status_sort_gs' : ''
      ) ) );
      $order=' ORDER BY '.($sort_status ? $sort_status.' ASC, ': '').'ref_nachname ASC, ref_vorname ASC ';
    break;
    case 'sort_status_down':
      $sort_status=(
        $type=='ps' ? 'status_sort_ps' : (
        $type=='es' ? 'status_sort_es' : (
        $type=='gs' ? 'status_sort_gs' : ''
      ) ) );
      $order=' ORDER BY '.($sort_status ? $sort_status.' DESC, ' : '').'ref_nachname DESC, ref_vorname DESC ';
    break;
    case 'sort_termin_up':
      $order=' ORDER BY plp3_datum ASC, ref_nachname ASC, ref_vorname ASC ';
    break;
    case 'sort_termin_down':
      $order=' ORDER BY plp3_datum DESC, ref_nachname DESC, ref_vorname DESC ';
    break;

/*
status_sort_ps,
status_sort_es,
status_sort_gs,
*/

  }
  return $order;
}

private function querySelectFrom_ORDER_PLP3s_PDF($sort){
  $order='';
  switch ($sort) {
    case 'eroeffnung':
      $order=' ORDER BY eroeffnung_datum, plp3_fach_bezeichnung, plp3_fach, ref_nachname ASC, ref_vorname ASC ';
    break;
    case 'pruefungstermine':
      $order=' ORDER BY plp3_datum, plp3_fach_bezeichnung, plp3_fach, ref_nachname ASC, ref_vorname ASC ';
    break;
    case 'pruefungsfach':
      $order=' ORDER BY plp3_fach_bezeichnung, plp3_fach, plp3_datum, ref_nachname ASC, ref_vorname ASC ';
    break;
  }
  return $order;	
}

// *************************
// * ladePLP3sRefsAlsGrundstaendigeSeminarschule
// * laedt alle Refs, in der die akt. Schule als grundstaendige Seminarschule eingetragen ist
function ladePLP3sRefsAlsGrundstaendigeSeminarschule($options=array()) {
  global $db;

  if (!$this->refGSgeladen and $this->logonOk) {
    $query=$this->querySelectFrom_PLP3s();
    $query.= "
      WHERE
        (
          ( snr_gs = '".$this->schulnummer."' )
        AND
          ( schuljahr = '".$this->schuljahr."' )
        )
      ";
    
	// add ORDER
	if ($options['sort-pdf']) {
		$query.=$this->querySelectFrom_ORDER_PLP3s_PDF($options['sort-pdf']);
	}
	else {
    	$query.=$this->querySelectFrom_ORDER_PLP3s('gs');
    }

    if ($this->debug>=3) { echo $this->html_newline, $query, $this->html_newline; }

    $rs = $db->Execute($query);

    while (!$rs->EOF) {
      // $rs->fields['ref_nameMail'] = rawurlencode($rs->fields['ref_vorname'].' '.$rs->fields['ref_nachname']);
      $rs->fields['ref_nameMail'] = $this->_formatText_getICal($rs->fields['ref_vorname'].' '.$rs->fields['ref_nachname']);
	  $rs->fields['link_to_details'] = $this->no_details_for_PLP3_FACH['gs'][ $rs->fields['plp3_fach'] ] ? false : true;

      $tmp=$this->_my_stripslashes_array($rs->fields);
	  $tmp['statusReady'] = $this->calculateStatusReady($rs->fields);

  	  $tmp['pre_eroeffnung']='';
	  if ( isset($tmp['eroeffnung_datum']) and $tmp['eroeffnung_datum'] ) {
	  	$tmp['pre_eroeffnung'] = $this->_minus_X_Werktage($tmp['eroeffnung_datum'], $this->day_shift_eroeffnung);
	  }

	  $this->grund_refs[] = $tmp;
      
      // $this->plp_data['statusReady'] = $this->calculateStatusReady($rs->fields);

      $rs->MoveNext();
    }

    $this->refGSgeladen=true;
    if ($this->debug>=3) { echo $this->html_newline,'Refs - GS:',$this->html_newline; print_r($this->grund_refs); }
  }
}


// *************************
// * ladePLP3sRefsAlsEnsatzschule
// * laedt alle Refs, in der die akt. Schule als Einsatzschule eingetragen ist
function ladePLP3sRefsAlsEnsatzschule($options=array()) {
  global $db;

  if (!$this->refESgeladen and $this->logonOk) {
    $query=$this->querySelectFrom_PLP3s();
    $query.= "
      WHERE
        (
          ( snr_einsatz = '".$this->schulnummer."' )
        AND
          ( schuljahr = '".$this->schuljahr."' )
        )
      ";

	// add ORDER
	if ($options['sort-pdf']) {
		$query.=$this->querySelectFrom_ORDER_PLP3s_PDF($options['sort-pdf']);
	}
	else {
    	$query.=$this->querySelectFrom_ORDER_PLP3s('es');
    }
	//    $query.=$this->querySelectFrom_ORDER_PLP3s('es');


    if ($this->debug>=3) { echo $this->html_newline, $query, $this->html_newline; }

    $rs = $db->Execute($query);
    while (!$rs->EOF) {
      // $rs->fields['statusReady'] = $this->calculateStatusReady($rs->fields);
      // $rs->fields['ref_nameMail'] = rawurlencode($rs->fields['ref_vorname'].' '.$rs->fields['ref_nachname']);
      $rs->fields['ref_nameMail'] = $this->_formatText_getICal($rs->fields['ref_vorname'].' '.$rs->fields['ref_nachname']);
	  $rs->fields['link_to_details'] = $this->no_details_for_PLP3_FACH['es'][ $rs->fields['plp3_fach'] ] ? false : true;

      // $this->einsatz_refs[] = $this->_my_stripslashes_array($rs->fields);
      $tmp=$this->_my_stripslashes_array($rs->fields);
	  $tmp['statusReady'] = $this->calculateStatusReady($rs->fields);	  

  	  $tmp['pre_eroeffnung']='';
	  if ( isset($tmp['eroeffnung_datum']) and $tmp['eroeffnung_datum'] ) {
	  	$tmp['pre_eroeffnung'] = $this->_minus_X_Werktage($tmp['eroeffnung_datum'], $this->day_shift_eroeffnung);
	  }
	  $this->einsatz_refs[] = $tmp;

      $rs->MoveNext();
    }

    $this->refESgeladen=true;
    if ($this->debug>=3) { echo $this->html_newline,'Refs - ES:',$this->html_newline; print_r($this->einsatz_refs); }
  }
}



// *************************
// * ladePLP3sRefsAlsGrundstaendigenSeminarschule
// * laedt alle Refs, in der die akt. Schule als pruefende Seminarschule eingetragen ist
function ladePLP3sRefsAlsPruefendeSeminarschule($options=array()) {
  global $db;

  if (!$this->refPSgeladen and $this->logonOk) {
    $query=$this->querySelectFrom_PLP3s();
    $query.= "
      WHERE
        (
          ( snr_pruef = '".$this->schulnummer."' )
        AND
          ( schuljahr = '".$this->schuljahr."' )
        )
      ";

    // add order
    // $query.=$this->querySelectFrom_ORDER_PLP3s('ps');
	if ($options['sort-pdf']) {
		$query.=$this->querySelectFrom_ORDER_PLP3s_PDF($options['sort-pdf']);
	}
	else {
    	$query.=$this->querySelectFrom_ORDER_PLP3s('ps');
    }


    if ($this->debug>=3) { echo $this->html_newline, $query, $this->html_newline; }
    // echo $query;

//  echo $query;
    $rs = $db->Execute($query);
    while (!$rs->EOF) {
      // $rs->fields['statusReady'] = $this->calculateStatusReady($rs->fields);
      // $rs->fields['ref_nameMail'] = rawurlencode($rs->fields['ref_vorname'].' '.$rs->fields['ref_nachname']);
      $rs->fields['ref_nameMail'] = $this->_formatText_getICal($rs->fields['ref_vorname'].' '.$rs->fields['ref_nachname']);
	  $rs->fields['link_to_details'] = $this->no_details_for_PLP3_FACH['ps'][ $rs->fields['plp3_fach'] ] ? false : true;

      // $this->pruef_refs[] = $this->_my_stripslashes_array($rs->fields);
      $tmp=$this->_my_stripslashes_array($rs->fields);
	  $tmp['statusReady'] = $this->calculateStatusReady($rs->fields);	  

  	  $tmp['pre_eroeffnung']='';
	  if ( isset($tmp['eroeffnung_datum']) and $tmp['eroeffnung_datum'] ) {
	  	$tmp['pre_eroeffnung'] = $this->_minus_X_Werktage($tmp['eroeffnung_datum'], $this->day_shift_eroeffnung);
	  }
	  $this->pruef_refs[] = $tmp;

      $rs->MoveNext();
    }

    $this->refPSgeladen=true;
    if ($this->debug>=3) { echo $this->html_newline,'Refs - PS:',$this->html_newline; print_r($this->pruef_refs); }
  }
}


function getCountOfRefs() {
  return array(
    'ps' => array(
      'do'    =>  $this->_getCountOfRefs('ps', 'do'),
      'wait'  =>  $this->_getCountOfRefs('ps', 'wait'),
      'ready' =>  $this->_getCountOfRefs('ps', 'ready')
    ),
    'es' => array(
      'do'    =>  $this->_getCountOfRefs('es', 'do'),
      'wait'  =>  $this->_getCountOfRefs('es', 'wait'),
      'ready' =>  $this->_getCountOfRefs('es', 'ready')
    ),
    'gs' => array(
      'do'    =>  $this->_getCountOfRefs('gs', 'do'),
      'wait'  =>  $this->_getCountOfRefs('gs', 'wait'),
      'ready' =>  $this->_getCountOfRefs('gs', 'ready')
    )
  );
}


// *************************
// * getCountOfRefs
private function _getCountOfRefs($type, $status) {
  global $db;

  $querytype='aetsch';
  switch ($type) {
    case 'ps':
      $querytype='snr_pruef';
    break;
    case 'es':
      $querytype='snr_einsatz';
    break;
    case 'gs':
      $querytype='snr_gs';
    break;
    default:
      $type='aetsch';
    break;
  }


  $querystatus='aetsch';
  switch ($status.'-'.$type) {
    case 'do-ps':
      $querystatus="plp_tv_status.status = 'neu' OR plp_tv_status.status = 'ps'";
    break;
    case 'do-es':
      $querystatus="plp_tv_status.status = 'es'";
    break;
    case 'do-gs':
      $querystatus="plp_tv_status.status = 'gs'";
    break;
    case 'wait-ps':
      $querystatus="plp_tv_status.status = 'es' OR plp_tv_status.status = 'gs'";
    break;
    case 'wait-es':
      $querystatus="plp_tv_status.status = 'ps' OR plp_tv_status.status = 'neu' OR plp_tv_status.status = 'gs'";
    break;
    case 'wait-gs':
      $querystatus="plp_tv_status.status = 'ps' OR plp_tv_status.status = 'neu' OR plp_tv_status.status = 'es'";
    break;
    case 'ready-ps':
    case 'ready-es':
    case 'ready-gs':
      $querystatus="plp_tv_status.status = 'fertig'";
    break;
  }

  $query="
    SELECT count( plp_tv_main.idplptvmain ) AS countit
    FROM (((((((((
      plp_tv_main)
      LEFT JOIN plp_tv_status ON plp_tv_status.status = plp_tv_main.status)
      LEFT JOIN plp_tv_sem_faecher AS sem_faecher1 ON plp_tv_main.fach1 = sem_faecher1.fach)
      LEFT JOIN plp_tv_sem_faecher AS sem_faecher2 ON plp_tv_main.fach2 = sem_faecher2.fach)
      LEFT JOIN plp_tv_sem_faecher AS sem_faecher3 ON plp_tv_main.fach3 = sem_faecher3.fach)
      LEFT JOIN plp_tv_sem_faecher AS sem_faecherPLP3 ON plp_tv_main.plp3_fach = sem_faecherPLP3.fach)
      LEFT JOIN schulen AS schulenGS ON plp_tv_main.snr_gs = schulenGS.Schulnr)
      LEFT JOIN schulen AS schulenES ON plp_tv_main.snr_einsatz = schulenES.Schulnr)
      LEFT JOIN schulen AS schulenPS ON plp_tv_main.snr_pruef = schulenPS.Schulnr)
    WHERE (
      ($querytype= '".$this->schulnummer."')
      AND
      (schuljahr = '".$this->schuljahr."')
      AND
      ($querystatus)
    )
  ";
//  echo ($status.'-'.$type)=='wait-es' ? $query: '';
  $countit=0;
  $rs = $db->Execute($query);
  if (!$rs->EOF) {
    $countit = $rs->fields['countit'];
  }

  return $countit ? $countit : 0;
}


// *************************
// * ladeDetailsById($plp3id)
// * laedt alle Detaildaten zu einer Pruefungslehrprobe
function ladeDetailsById($plp3id, $neuladen=false) {
  global $db;

  if ($neuladen) {$this->plp_data_geladen=false; }

  if (!$this->plp_data_geladen and $this->logonOk and preg_match("/^[a-zA-Z0-9]+$/", $plp3id) ) {
    $schulnummer=$this->schulnummer;
    $query=$this->querySelectFrom_PLP3s();
    $query.= "
      WHERE
        (
          ( idplptvmain = '".$plp3id."' )
        AND
          ( schuljahr = '".$this->schuljahr."' )
        )
        AND (
          ( snr_gs = '$schulnummer' )
          OR
          ( snr_einsatz = '$schulnummer' )
          OR
          ( snr_pruef = '$schulnummer' )
        )
      ";

    if ($this->debug>=3) { echo $this->html_newline, $query, $this->html_newline; }

    $rs = $db->Execute($query);
    if (!$rs->EOF) {
      $rs->fields['statusReady'] = $this->calculateStatusReady($rs->fields);
      // $rs->fields['ref_nameMail'] = rawurlencode($rs->fields['ref_vorname'].' '.$rs->fields['ref_nachname']);
      $rs->fields['ref_nameMail'] = $this->_formatText_getICal($rs->fields['ref_vorname'].' '.$rs->fields['ref_nachname']);

      $this->plp_data = $this->_my_stripslashes_array($rs->fields);
      $this->plp_data['statusReady'] = $this->calculateStatusReady($rs->fields);


  	  $this->plp_data['pre_eroeffnung']='';
	  if ( isset($this->plp_data['eroeffnung_datum']) and $this->plp_data['eroeffnung_datum'] ) {
	  	$this->plp_data['pre_eroeffnung'] = $this->_minus_X_Werktage($this->plp_data['eroeffnung_datum'], $this->day_shift_eroeffnung);
	  }

      $this->plp_data_geladen = true;
    }

    if ($this->debug>=3) { echo $this->html_newline,'PLP-Data:',$this->html_newline; print_r($this->plp_data); }
  }
}


// *************************
// * ladeSchuldaten()
// * laedt eigene Schuldaten der aktuellen Schule wie Adresse, E-Mail, ...
function ladeSchuldaten() {
  global $db;

  if (!$this->schuldaten_geladen and $this->logonOk) {
    $query = "
      SELECT
        *
      FROM
        schulen
      WHERE
        ( Schulnr = '".$this->schulnummer."' )
    ";

    $rs = $db->Execute($query);
    if (!$rs->EOF) {
      $this->schuldaten = $rs->fields;
      $rs->MoveNext();
      $this->schuldaten_geladen=true;
    }
    if (!$this->schuldaten_geladen) {
      $this->error['schuldaten-laden']='Schuldaten konnten nicht geladen werden.';
    }
    $this->schuldaten_geladen=true;

    if ($this->debug>=2) { echo $this->html_newline,'Schuldaten:',$this->html_newline; print_r($this->schuldaten); }
  }
}


// *************************
// * saveSchuldaten()
// * speichert die uebertragenen Daten (kontrolliert auch die Uebergabe und setzt ggf. neuen status)
function saveSchuldaten($sd) {
  if ($this->debug>=2) { echo $this->html_newline, 'check: ', $this->getStatus(), $this->html_newline; }

  if ($_POST['autofill_ps'] ) { $autofill='all'; }
  if ($_POST['autofill_ps_vorsitz'] ) { $autofill='vorsitz'; }
  if ($_POST['autofill_ps_erstpruefer'] ) { $autofill='erstpruefer'; }
  if ($_POST['autofill_ps_zweitpruefer'] ) { $autofill='zweitpruefer'; }
  if ($_POST['autofill_ps_zeit_bis'] ) { $autofill='zeit_bis'; }

  if ($_POST['autofill_es_vorstunde_zeit_bis'] ) { $autofill='vorstunde_zeit_bis'; }
  if ($_POST['autofill_es_zweitpruefer'] ) { $autofill='zweitpruefer'; }
  

  if ($_POST['autofill_gs_plp3_zfl'] ) { $autofill='zfl'; }
  if ($_POST['autofill_gs_eroeffnung_datum'] ) { $autofill='eroeffnung_datum'; }
  if ($_POST['autofill_gs_seminarleitung_gs'] ) { $autofill='seminarleitung_gs'; }
  if ($_POST['autofill_gs_eroeffnung_durch_gs'] ) { $autofill='eroeffnung_durch_gs'; }
  if ($_POST['autofill_gs_eroeffnung_durch_es'] ) { $autofill='eroeffnung_durch_es'; }

  if ($autofill) { $sd = $this->autofill($sd, $this->type, $autofill); }

  switch ($this->getStatus()) {
    case 'ps': case 'es': case 'gs': case 'fertig':
      $this->saveSchuldaten_type($sd, $this->type);
      break;
    default:
      $this->error['savedata_typ']='Schultyp nicht bekannt.';
      break;
  }
}


// *************************
// * saveSchuldaten_type
private function saveSchuldaten_type($sd, $type) {
  if ( $options['debug'] != '') { $debug=$options['debug']; } else { $debug=$this->debug; }

  if ($debug>2) {
    echo $type,"<br>";
    print_r($sd);
    echo "<br>";
  }

  $check=true;
  $allDataNames=array();
  $plp_data_settings = $this->plp_data_settings[$type];

  foreach ($plp_data_settings as $data_type => $dataNames) {

    $checktmp=$this->checkSchuldaten_RegExp($sd,
                             $this->plp_data_settings_regexp[$data_type]['regexp'],
                             $this->plp_data_settings_regexp[$data_type]['errormesssage'],
                             $dataNames, array('empty' => true)
                          );
    $check = $check && $checktmp;

    $allDataNames = array_merge($allDataNames, $dataNames);
  }

  if ($type=='gs' || $type=='fertig') {
    if ($sd['plp3_zeitverlaengerung']) {
      if ($sd['plp3_zeitverlaengerung_auf_minuten'] > 0) {}
      else {
        $this->error_data['plp3_zeitverlaengerung_auf_minuten']= 'Bitte angeben.';
        $check = $check && false;
      }
    }
    else {
      if ($sd['plp3_zeitverlaengerung_auf_minuten']) {
        $this->error_data['plp3_zeitverlaengerung']= 'Bitte genehmigen.';
        $check = $check && false;
      }
      else {
      }
    }
  }

  if ($check) {
    $this->saveCheckedSchuldaten($sd, $allDataNames);
  }

  $this->replaceLoadedSchuldaten($sd, $allDataNames);
  $this->calculateNewStatus();
}


// *************************
// * replaceLoadedSchuldaten
private function replaceLoadedSchuldaten($sd, $dataNames ) {
  foreach ( $dataNames as $valName ) {
    $this->plp_data[$valName] = $sd[$valName]; // geladene (bzw. vorhandene) Daten ersetzen mit den geaenderten
  }
  return true;
}


// *************************
// * checkSchuldaten_RegExp
private function checkSchuldaten_RegExp($sd, $suchmuster, $errormessage, $dataNames, $options=array() ) {
  if ( $options['debug'] != '') { $debug=$options['debug']; } else { $debug=$this->debug; }

  $error_count=0;

  foreach ( $dataNames as $valName ) {
    if (($options['empty']) and ($sd[$valName]=='')) {
      if ($debug>=2) { echo $this->html_newline, "$valName: ",'leere Eingabe', $this->html_newline; }
    }
    elseif ( !preg_match($suchmuster, $sd[$valName]) ) {
      $this->error_data[$valName]= $errormessage;
      $error_count++;
      if ($debug>=2) { echo $this->html_newline, 'ERROR: ', $valName, '=', $sd[$valName], '; ', $this->error_data[$valName], $this->html_newline; }
    }
  }

  return ($error_count == 0 ? 1 : 0);
}


// *************************
// * saveCheckedSchuldaten
private function saveCheckedSchuldaten($sd, $dataNames) {
  global $db;
  $record=array();

  foreach ( $dataNames as $dataName ) {
    $record[$dataName] = addslashes($sd[$dataName]); // 2011-02-07
  }
	
  $updateSQL = $db->AutoExecute("plp_tv_main", $record, 'UPDATE', "idplptvmain = '".$this->plp_data['idplptvmain']."'");
 
}

// HTML / ADDSLASHES / STRIPSLASHES
function hsc_3($c) { 
	$a=array();
	foreach ($c as $k => $v) { $a[$k]=$this->hsc_2($v); }
	return $a;
}
function hsc_2($c) { 
	$a=array();
	foreach ($c as $k => $v) { $a[$k]=$this->hsc_1($v); }
	return $a;
}
function hsc_1($c) { 
	if (is_array($c)) { return $c; }
	else { return htmlspecialchars($c); }
}

private function _my_stripslashes_array($a) {
  $b=array();
  foreach ( $a as $k => $v ) {
    $b[$k] = stripslashes($v.""); // 2011-02-07
  }	
  return $b;
}

// HTML / ADDSLASHES / STRIPSLASHES


// *************************
// * calculateNewStatus
private function _minus_X_Werktage($datum, $tage) {
	$wochen=0+floor($tage/5);
	$restliche_tage=$tage % 5;

	$neues_datum=strtotime(" - ".($wochen*7)." days", strtotime($datum));
	
	if ( date("w",$neues_datum)==6 ) { $neues_datum=strtotime(" - 1 day", $neues_datum); }
	elseif ( date("w",$neues_datum)==0 ) { $neues_datum=strtotime(" - 2 days", $neues_datum); };

	$wochentag=date("w",$neues_datum);
	if ($wochentag - $restliche_tage < 1) {
		$neues_datum=strtotime(" - ".(2+$restliche_tage)." days", $neues_datum);
	}
	else {
		if ($restliche_tage==1) { $neues_datum=strtotime(" - 1 day", $neues_datum); }
		else { $neues_datum=strtotime(" - $restliche_tage days", $neues_datum); }
	}
	
	return date("Y-m-d", $neues_datum);
}

// *************************
// * calculateNewStatus
private function calculateNewStatus() {
  $new_status=$this->calculateStatus($this->plp_data);

  if ($new_status!=$this->plp_data['status']) {
    $this->plp_data['status']=$new_status;
    global $db;
    $record['status']=$new_status;
    $updateSQL = $db->AutoExecute("plp_tv_main", $record, 'UPDATE', "idplptvmain = '".$this->plp_data['idplptvmain']."'");
  }

  if ($debug>2) { echo '<br>new status = ',$new_status,'<br>'; }
}


// *************************
// * calculateStatus
// * bestimmt den aktuellen Status (PS/neu -> ES -> GS )
private function calculateStatus($sd) {
  $aktueller_status=$this->getStatus();

  // echo "TZ: ", ' - plp3_zeit_von=' , $sd['plp3_zeit_von'], ' - plp3_zeit_bis=' , $sd['plp3_zeit_bis'], ' - plp3_zeitverlaengerung_auf_minuten:' , $sd['plp3_zeitverlaengerung_auf_minuten'], '<br>';
  $status_tmp=$this->plp_status_first;
  $ready=false;

  $max_i=99;
  $i=0;
  while ($status_tmp!=$this->plp_status_last && !$ready) { 
    $i++;
    // echo "check $status_tmp <br>";
    if ( $this->check_dataset_completed($sd, $this->plp_data_settings_necessary[$status_tmp], $status_tmp ) ) {
      $status_tmp=$this->plp_status_follow[$status_tmp];
    }
    else {
      $ready=true; // $this->plp_status_ready[$status_tmp]=true;  // $ready=true;
      // status suche fertig, da der Datensatz nicht komplett ( check_dataset_completeda() )
    }
    $ready=(($i>$max_i) || $ready);   // ($i>$max_i); // (($i>$max_i) || $ready);
  }

  if (
    $sd['plp3_zeitverlaengerung']
    and $sd['plp3_zeitverlaengerung_auf_minuten']
    and (
      substr($sd['plp3_zeit_bis'].'00:00',0,2)*60 + substr($sd['plp3_zeit_bis'].'00:00',3,2)
      - substr($sd['plp3_zeit_von'].'00:00',0,2)*60 - substr($sd['plp3_zeit_von'].'00:00',3,2)
      !=
      $sd['plp3_zeitverlaengerung_auf_minuten']
    )
  ) {
    $status_tmp='ps';
  }

  return ($status_tmp ? $status_tmp : $aktueller_status);
}

// *************************
// * calculateStatusReady
// * ueberprueft, ob die Angaben fuer jeden Status (PS,ES,GS) vollstaendig sind
private function calculateStatusReady($sd) {
  // echo "TZ: ", ' - plp3_zeit_von=' , $sd['plp3_zeit_von'], ' - plp3_zeit_bis=' , $sd['plp3_zeit_bis'], ' - plp3_zeitverlaengerung_auf_minuten:' , $sd['plp3_zeitverlaengerung_auf_minuten'], '<br>';
  $status_tmp=$this->plp_status_first;
  $plp_status_ready=array();
  $ready=false;

  $max_i=99;
  $i=0;
  while ($status_tmp!=$this->plp_status_last && !$ready) {
    $i++;
    if ( $this->check_dataset_completed($sd, $this->plp_data_settings_necessary[$status_tmp], $status_tmp ) ) {
      $plp_status_ready[$status_tmp]=1;  // ready=true;
      $status_tmp=$this->plp_status_follow[$status_tmp];
      //$ready=true;
    }
    else {
      // $ready=true;
      $plp_status_ready[$status_tmp]=0;
      $status_tmp=$this->plp_status_follow[$status_tmp]; // Status nicht ready -> naechster Status
    }
    $ready=($i>$max_i); // (($i>$max_i) || $ready);
  }

  if (
    $sd['plp3_zeitverlaengerung']
    and $sd['plp3_zeitverlaengerung_auf_minuten']
    and (
      substr($sd['plp3_zeit_bis'].'00:00',0,2)*60 + substr($sd['plp3_zeit_bis'].'00:00',3,2)
      - substr($sd['plp3_zeit_von'].'00:00',0,2)*60 - substr($sd['plp3_zeit_von'].'00:00',3,2)
      !=
      $sd['plp3_zeitverlaengerung_auf_minuten']
    )
  ) {
    $status_tmp='ps';
    $plp_status_ready['ps']=0;
  }

	// print_r($plp_status_ready);

  return $plp_status_ready;
}


private function check_dataset_completed( $sd, $plp_data_settings_necessary_st, $status ) {
  if ( $options['debug'] != '') { $debug=$options['debug']; } else { $debug=$this->debug; }
  $is_bad=false;

  if ($this->plp_data_settings_necessary_AUSNAHME_PLP3_FACH[ $status ][ $sd['plp3_fach'] ] ) {
		// z. B. $this->plp_data_settings_necessary_AUSNAHME_PLP3_FACH['es']['SchPsy']
		// bei Einsatzschulen ist im Fach SchPsy nichts einzugeben
  }
  else {
    foreach ($plp_data_settings_necessary_st as $fieldtype => $fieldnames) {
	  if ($debug>2) { echo "<br>-----------------------<br>Teste $fieldtype-Types <br>-----------------------<br>"; }

	  foreach ($fieldnames as $fieldname) {
	    if ($debug>2) { echo "$fieldname (",$this->plp_data_settings_necessary_regexp_bad[$fieldtype],"=?=",$sd[$fieldname], "): "; }
		if ($sd[$fieldname]) {
		  $is_bad=preg_match( $this->plp_data_settings_necessary_regexp_bad[$fieldtype], $sd[$fieldname]);
		}
		else { $is_bad=true;}
        if ($debug>2) { echo ($is_bad ? "bad" : "ok") , "<br>" ; }
		if ($is_bad) { break; }

	  }
      if ($is_bad) { break; }
	}
  }
  return !$is_bad;
}
// *********************************
// * AUTOFILL
// *********************************
private function autofill($sd, $type, $autofill) {
  switch ($type) {
    // *********************************
    // PS
    case 'ps':
		if ($autofill=='all') {
			$person=$this->load_DATA('Seminarleitung', 'ps');
			if ( count($person)<1 ) { $person=$this->load_DATA('Schulleitung', 'ps'); }
			$sd['plp3_vorsitz']=$person['name'];
			$sd['plp3_vorsitz_BRN_Freigabe']=$person['BRN_Freigabe'];
			
			$person=$this->load_DATA('Seminarlehrer', 'ps');
			$sd['plp3_erstpruefer']=$person['name'];
			$sd['plp3_erstpruefer_BRN_Freigabe']=$person['BRN_Freigabe'];
		}
		elseif($autofill=='vorsitz')     {
			$person=$this->load_DATA('Seminarleitung', 'ps');
			if ( count($person)<1 ) { $person=$this->load_DATA('Schulleitung', 'ps'); }
			$sd['plp3_vorsitz']=$person['name'];
			$sd['plp3_vorsitz_BRN_Freigabe']=$person['BRN_Freigabe'];
		}
		elseif($autofill=='erstpruefer') { 
			$person=$this->load_DATA('Seminarlehrer', 'ps');
			$sd['plp3_erstpruefer']=$person['name'];
			$sd['plp3_erstpruefer_BRN_Freigabe']=$person['BRN_Freigabe'];
		}
		elseif($autofill=='zweitpruefer'){ 
			$person=$this->load_DATA('Schulleitung', 'es');
			$sd['plp3_zweitpruefer']=$person['name'];
			$sd['plp3_zweitpruefer_BRN_Freigabe']=$person['BRN_Freigabe'];
		}
		elseif($autofill=='zeit_bis')    {
			if ( $this->plp_data['plp3_zeitverlaengerung'] and $this->plp_data['plp3_zeitverlaengerung_auf_minuten'] ) {
			$sd['plp3_zeit_bis']=$this->addXXMinutes($_POST['plp3_zeit_von'], $this->plp_data['plp3_zeitverlaengerung_auf_minuten']);
		}
		else{
			$sd['plp3_zeit_bis']=$this->add45Minutes($_POST['plp3_zeit_von']);
		}
      }
    break;

    // *********************************
    // ES
    case 'es':
		if ($autofill=='vorstunde_zeit_bis') { $sd['vorstunde_zeit_bis'] =$this->add45Minutes($_POST['vorstunde_zeit_von']); }
		elseif($autofill=='zweitpruefer'){ 
			$person=$this->load_DATA('Schulleitung', 'es');
			$sd['plp3_zweitpruefer']=$person['name'];
			$sd['plp3_zweitpruefer_BRN_Freigabe']=$person['BRN_Freigabe'];
		}
    break;

    // *********************************
    // GS
    case 'gs':
		//wird eigentlich nicht mehr gebraucht, da ZFL sich nun selbst einträgt
		if($autofill=='zfl')                        { 
			$person=$this->load_DATA('ZFL');
			$sd['plp3_zfl']=$person['name'];
			$sd['plp3_zfl_BRN_Freigabe']=$person['BRN_Freigabe'];
		}
		elseif($autofill=='eroeffnung_datum')       { $sd['eroeffnung_datum']=$this->sub14Days($this->plp_data['plp3_datum']); }
		elseif($autofill=='seminarleitung_gs')      {
			$person=$this->load_DATA('Seminarleitung', 'gs');
			if ( count($person)<1 ) { $person=$this->load_DATA('Schulleitung', 'gs'); }
			$sd['plp3_seminarleitung_gs']=$person['name'];
			$sd['plp3_seminarleitung_gs_BRN_Freigabe']=$person['BRN_Freigabe'];
		}
		elseif($autofill=='eroeffnung_durch_gs')      {
			$person=$this->load_DATA('Seminarleitung', 'gs');
			if ( count($person)<1 ) { $person=$this->load_DATA('Schulleitung', 'gs'); }
			$sd['eroeffnung_durch']=$person['name'];
			$sd['eroeffnung_durch_BRN_Freigabe']=$person['BRN_Freigabe'];
		}
		elseif($autofill=='eroeffnung_durch_es')      { 
			$person=$this->load_DATA('Schulleitung', 'es');
			$sd['eroeffnung_durch']=$person['name'];
			$sd['eroeffnung_durch_BRN_Freigabe']=$person['BRN_Freigabe'];
		}
    break;
  }

  return $sd;
}

private function load_DATA($object, $type='') {
  global $db;
  $return_val='';
  $return_BRN_Freigabe='';

  $snr='';
  switch ($type) {
    case 'ps':
      $snr=$this->plp_data['snr_pruef'];
      break;
    case 'es':
      $snr=$this->plp_data['snr_einsatz'];
      break;
    case 'gs':
      $snr=$this->plp_data['snr_gs'];
      break;
  }

  switch ($object) {
	case "Seminarleitung":
		$query= "SELECT * FROM Schulverwaltung WHERE Funktion = 'Seminarleitung' AND Schulnr = '".$snr."'";
		$rs = $db->Execute($query);
		if (!$rs->EOF) { 
			$return_val=$rs->fields['Amtsbezeichnung'].' '.$rs->fields['Vorname'].' '.$rs->fields['Nachname']; 
			$return_BRN_Freigabe = ( $rs->fields['FreigabeBRN'] =='zugestimmt' ? 1 : 0);
		}
	break;
	case "Seminarlehrer":
		$query= "SELECT * FROM sem_lehrer WHERE Schulnr = '".$snr."' AND seminarfach = '".$this->plp_data['plp3_fach']."'";
		$rs = $db->Execute($query);
		if (!$rs->EOF) { 
			$return_val=$rs->fields['titel'].' '.$rs->fields['vorname'].' '.$rs->fields['name']; 
			$return_BRN_Freigabe = ( $rs->fields['FreigabeBRN'] =='zugestimmt' ? 1 : 0);
		}
	break;
	case "Schulleitung":
		$query= "SELECT * FROM Schulverwaltung WHERE Schulnr = '".$snr."' AND ( Funktion = 'Schulleiter' OR Funktion = 'Schulleiterin' )";
		$rs = $db->Execute($query);
		if (!$rs->EOF) { 
			$return_val=$rs->fields['Amtsbezeichnung'].' '.$rs->fields['Vorname'].' '.$rs->fields['Nachname']; 
			$return_BRN_Freigabe = ( $rs->fields['FreigabeBRN'] =='zugestimmt' ? 1 : 0);
		}
	break;
	case "ZFL":
		$query= "SELECT * FROM sem_lehrer WHERE (zfl = 1) AND (seminarfach = '".$this->plp_data['plp3_fach']."')"; //$_POST['plp3_fach']."')";
		$rs = $db->Execute($query);
		// echo $query.'<br>';
		// echo 'ZFL: '.$rs->fields['titel'].' '.$rs->fields['vorname'].' '.$rs->fields['name'];
		if (!$rs->EOF) { 
			$return_val=$rs->fields['titel'].' '.$rs->fields['vorname'].' '.$rs->fields['name']; 
			$return_BRN_Freigabe = ( $rs->fields['FreigabeBRN'] =='zugestimmt' ? 1 : 0);
		}
		else {
			$query= "SELECT sem_lehrer.*  
			FROM sem_lehrer 
			JOIN plp_tv_sem_faecher ON plp_tv_sem_faecher.fach_alternativ = sem_lehrer.seminarfach 
			WHERE ((sem_lehrer.zfl = 1) AND (plp_tv_sem_faecher.fach= '".$this->plp_data['plp3_fach']."'))";
			$rs = $db->Execute($query);
			if (!$rs->EOF) { 
				$return_val=$rs->fields['titel'].' '.$rs->fields['vorname'].' '.$rs->fields['name']; 
				$return_BRN_Freigabe = ( $rs->fields['FreigabeBRN'] =='zugestimmt' ? 1 : 0);
			}
		}
	break;
  }
  return array( 'name' => $return_val, 'BRN_Freigabe' => $return_BRN_Freigabe);
}

private function add45Minutes($zeit) {
  return date('h:i',strtotime('2010-01-01 '.$zeit)+(2700)).':00';
}
private function addXXMinutes($zeit,$minutes) {
  $seconds=60*$minutes;
  return date('h:i',strtotime('2010-01-01 '.$zeit)+($seconds)).':00';
}
private function sub14Days($datum) {
  $datumR='';
  if ($datum) {
    if ($datum!="0000-00-00") {
      // $datumR=date('Y-m-d',strtotime($datum)-(1209600));
      $datumR=date('Y-m-d', strtotime('-14 days', strtotime($datum) ) );
	}
  }
  return $datumR;
}

function getSeminarfaecher($all=false) {
  global $db;
  $result=array();
  $fach1='';

  if (!$all) {
    $fach1=$this->plp_data['fach1'];
    $fach2=$this->plp_data['fach2'];
    $fach3=$this->plp_data['fach3'];
  }

  $query= "SELECT * FROM plp_tv_sem_faecher";
  $where="";
  if ($fach1) { $where = " WHERE 
  		plp_tv_sem_faecher.fach='$fach1' 
  		OR plp_tv_sem_faecher.fach='$fach2' 
  		OR plp_tv_sem_faecher.fach='$fach3'";
  }
  
  $order= " ORDER BY plp_tv_sem_faecher.bezeichnung ASC";


  $rs = $db->Execute($query.$where.$order);

  $result['-']='-';

  while (!$rs->EOF) {
    $result[$rs->fields['fach']] = $rs->fields['bezeichnung'];
    $rs->MoveNext();
  }

  return $result;
}

function getJahrgangsstufen() { return array('-'=>'-', 5=>5, 6=>6, 7=>7, 8=>8, 9=>9, 10=>10); }

function getZeiten() {
  $zeiten=array('00:00:00' => '');
  for ($std=7; $std<17; $std++) {
    for ($min1=0; $min1<12; $min1++) {
      $tmpZ=''.($std<10 ? '0'.$std : ''.$std).':'.($min1<2 ? '0'.($min1*5) : ''.($min1*5));
      $zeiten[$tmpZ.':00']=$tmpZ;
    }
  }
  return $zeiten;
}


function getAllSchoolsBezirk() {
  if (!preg_match("/^[a-zA-Z0-9]+$/", $derBezirk)) { $derBezirk='aetsch'; }

  global $db;

  $sN = array();

  $query = "
    SELECT
      regbezirk,
      Schulname,
      Ort,
      Schulnr
    FROM
      schulen
    ORDER BY
      regbezirk,
      Schulnr
  ";

  $rs = $db->Execute($query);
  while (!$rs->EOF) {
    $sN[]=array(
      'schulnummer' => $rs->fields['Schulnr'],
      'regbezirk' => $rs->fields['regbezirk'],
      'name' => $rs->fields['Schulname'],
      'ort' => $rs->fields['Ort']
    );
    $rs->MoveNext();
  }

  return $sN;
}


// ***************************** PDF
function getPdfPLP3Formular() {
  $status=$this->getStatus();
  if ( $status=='fertig' ) {

    // *** *** *** *** *** *** ***
    // fuer PDF-Ausgabe
    // *** *** *** *** *** *** ***

    $tmp_name=$this->_formatText_getICal( ($this->plp_data['ref_anrede'] ? $this->plp_data['ref_anrede'].'-' : '').$this->plp_data['ref_vorname'].'-'.$this->plp_data['ref_nachname']  );
    $fileName="/www/data/ftp/rsmbobbn/_sys/libs/plp3tv/documents/plp3tvFormular.pdf";
    $pdffilname="plp3tv-$tmp_name-".$this->plp_data['pkz'].'.pdf';
	$pdffilname=preg_replace("/[^a-zA-Z0-9\-.]/", "_", $pdffilname);

    $pdf = Zend_Pdf::load($fileName);
    $page = $pdf->pages[0];




    // *** *** *** *** *** *** ***
    // Einstellungen
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    $standardlineheight=18;
    $standardSize=12;
    $standardFont=Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
	
	$this->plp_data['schulenPS_Schulname']=utf8_decode($this->plp_data['schulenPS_Schulname']);
	$this->plp_data['schulenPS_Schulname2']=utf8_decode($this->plp_data['schulenPS_Schulname2']);


    // *** *** *** *** *** *** ***
    // Start
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Studienseminar: (Kasten links oben)
    $yStart=793;
    $xStart=57;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);


    // Adresse soll vertikal zentriert im Kasten stehen
    if (!$this->plp_data['schulenGS_Schulname2']) {
      $yStart-=($lineheight/2);
    }

    // 4 Zeilen schreiben
    // $text=utf8_encode( $this->plp_data['schulenGS_Schulname'] );
    $text=( $this->plp_data['schulenGS_Schulname'] );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');

    if ($this->plp_data['schulenGS_Schulname2']) {
      // $text=utf8_encode( $this->plp_data['schulenGS_Schulname2'] );
      $text=( $this->plp_data['schulenGS_Schulname2'] );
      $ypos-=$lineheight;
      $xpos=$xStart;
      $page->drawText($text, $xpos, $ypos, 'UTF-8');
    }

    // $text=utf8_encode( $this->plp_data['schulenGS_Strasse'] );
    $text=( $this->plp_data['schulenGS_Strasse'] );
    $ypos-=$lineheight;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');

    // $text=utf8_encode( $this->plp_data['schulenGS_PLZ'].' '.$this->plp_data['schulenGS_Ort'] );
    $text=( $this->plp_data['schulenGS_PLZ'].' '.$this->plp_data['schulenGS_Ort'] );
    $ypos-=$lineheight;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Pruefungstermin: (Kasten rechts oben)
    $yStart=775;
    $size=$standardSize+2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( 'Prüfungstermin '.substr($this->plp_data['plp3_datum'].'    ',0,4) );
    $text=( 'Prüfungstermin '.substr($this->plp_data['plp3_datum'].'    ',0,4) );
    $ypos=$yStart;
    $xpos=$this->_centerstartposition_range($text, $font, $size, 296, 542);
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Referendarin
    $yStart=718.5;
    $xStart=218;
    $size=$standardSize+1;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( ($this->plp_data['ref_anrede'] ? $this->plp_data['ref_anrede'].' ' : '')
    //  .$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']  );
    // $text=utf8_encode(   $this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']  );
    $tmpAnrede="";
    if ( $this->plp_data['ref_anrede']=="Stud.-Refin." or $this->plp_data['ref_anrede']=="Frau") { $tmpAnrede="Frau "; }
    if ( $this->plp_data['ref_anrede']=="Stud.-Ref." or $this->plp_data['ref_anrede']=="Herr")   { $tmpAnrede="Herr "; }
    // $text=utf8_encode( $tmpAnrede.$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']  );
    $text=( $tmpAnrede.$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']  );

    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Faecherverbindung
    $yStart=702.3;
    $xStart=218;
    $size=$standardSize-1;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['fach1'].' / '.$this->plp_data['fach2'].($this->plp_data['fach3'] ? ' / '.$this->plp_data['fach3'] : ''));
    $text=( $this->plp_data['fach1'].' / '.$this->plp_data['fach2'].($this->plp_data['fach3'] ? ' / '.$this->plp_data['fach3'] : ''));
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Unterrichtsfach Mittelblock
    $yStart=596.5;
    $xStart=182;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_fach_bezeichnung'] );
    $text=( $this->plp_data['plp3_fach_bezeichnung'] );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Ptuefungsort
    $yStart=579;
    $xStart=182;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['schulenES_Schulname'].($this->plp_data['schulenES_Schulname2'] ? ', '.$this->plp_data['schulenES_Schulname2'] : '') );
    $text=( $this->plp_data['schulenES_Schulname'].($this->plp_data['schulenES_Schulname2'] ? ', '.$this->plp_data['schulenES_Schulname2'] : '') );
    if ( $this->_textwidth($text, $font, $size)+$xStart > 540 ) {
      // $text=utf8_encode( $this->plp_data['schulenES_Schulname'].' ('.$this->plp_data['schulenES_Schulnr'].')' );
      $text=( $this->plp_data['schulenES_Schulname'].' ('.$this->plp_data['schulenES_Schulnr'].')' );
    }
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Klasse
    $yStart=561.5;
    $xStart=182;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_klasse'] );
    $text=( $this->plp_data['plp3_klasse'] );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***


    // *** *** *** *** *** *** ***
    // Datum
    $yStart=534.5;
    $xStart=230;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=( // utf8_encode
      substr($this->plp_data['plp3_datum'].'          ',8,2)
      .'.'.substr($this->plp_data['plp3_datum'].'          ',5,2)
      .'.'.substr($this->plp_data['plp3_datum'].'          ',0,4)
    );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // von
    $yStart=534.5;
    $xStart=370;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=(    // utf8_encode
      substr($this->plp_data['plp3_zeit_von'].'          ',0,5)
    );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // bis
    $yStart=534.5;
    $xStart=460;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=(   // utf8_encode
      substr($this->plp_data['plp3_zeit_bis'].'          ',0,5)
    );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // pruefende Seminarschule (links)
	
	/*
    $yStart=486;
    $xStart=115;
    $size=$standardSize-5;
    $lineheight=($size*1.2);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=utf8_encode( $this->plp_data['schulenPS_Schulname'] );
    $ypos=$yStart;
    $xpos=$xStart-0.5*$this->_textwidth($text, $font, $size);;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');

    if ($this->plp_data['schulenPS_Schulname2']) {
      $text=$this->plp_data['schulenPS_Schulname2'];
      $ypos=$yStart-$lineheight;
      $xpos=$xStart-0.5*$this->_textwidth($text, $font, $size);;
      $page->drawText($text, $xpos, $ypos, 'UTF-8');
    }
	*/
//////////////////////////////////////////////////////////////////////////////////////////////////////

    // *** *** *** *** *** *** ***
    // pruefende Seminarschule (links)

    $yStart=486;
    $xStart=115;
	$innerpagewidth=118;
    $size=$standardSize-5;
    $lineheight=($size*1.2);
    $font=$standardFont;
    $page->setFont($font, $size);
	
	$textOK=true;
    $text=( $this->plp_data['schulenPS_Schulname'] );
	if ($this->_textwidth($text, $font, $size)>$innerpagewidth) {$textOK=false;}

    if ($this->plp_data['schulenPS_Schulname2']) {
      $text=$this->plp_data['schulenPS_Schulname2'];
	  if ($this->_textwidth($text, $font, $size)>$innerpagewidth) {$textOK=false;}
	}
	
    if ($textOK) {
		// $text=utf8_encode( $this->plp_data['schulenPS_Schulname'] );
		$text=( $this->plp_data['schulenPS_Schulname'] );
		$ypos=$yStart;
		$xpos=$xStart-0.5*$this->_textwidth($text, $font, $size);
		$page->drawText($text, $xpos, $ypos, 'UTF-8');
	
		if ($this->plp_data['schulenPS_Schulname2']) {
		  // $text=utf8_encode($this->plp_data['schulenPS_Schulname2']);
		  $text=($this->plp_data['schulenPS_Schulname2']);
		  $ypos=$yStart-$lineheight;
		  $xpos=$xStart-0.5*$this->_textwidth($text, $font, $size);
		  $page->drawText($text, $xpos, $ypos, 'UTF-8');
		}
	}
	else { // MEHRZEILIG
		// $yStart=500.5;
	    $yStart=486.5;
		$xStart=52;
		$xEnd=170;
		// $yCenter=500.5;
		$yCenter=486.5;
		$innerpagewidth=118;
		$size=$standardSize-5;
		$lineheight=($size*1.2);
		$font=$standardFont;
		$page->setFont($font, $size);
	
		$textPS=( $this->plp_data['schulenPS_Schulname'].( $this->plp_data['schulenPS_Schulname2'] ? ', '.$this->plp_data['schulenPS_Schulname2'] :'' ) );
	
		$txt_arr=preg_split( '/ +/', $textPS );
		if (count($txt_arr)>0) {
		  $text3 = new textblock2($innerpagewidth, $font, $size, true);
		  for ($i=0; $i<count($txt_arr); $i++) {
			$text3->addWord( $txt_arr[$i].' ' );
		  }
	
		  if ($text3->getLineCount()==1) {
			// Text schreiben (nur eine Zeile) -> zentriert
			$page->drawText(
			  ($text3->getLine(0)),  // utf8_encode
			  $this->_centerstartposition_range(($text3->getLine(0)), $font, $size, $xStart, $xEnd),
			  $yCenter,
			  'UTF-8'
			);
		  }
		  elseif ($text3->getLineCount()>1) {
			// Text schreiben (mehrere Zeilen) -> links beginnen
			$ypos=$yCenter; // $yCenter+0.5*$lineheight*$text3->getLineCount()-$size*0.5;
			if ($text3->getLineCount()>2) {$ypos=$yCenter+2;}
			$xpos=$xStart;
			for ($i=0; $i<$text3->getLineCount(); $i++) {
			  $page->drawText(
				($text3->getLine($i)), 
				// $xpos, 
				$this->_centerstartposition_range(($text3->getLine($i)), $font, $size, $xStart, $xEnd),
				$ypos-$i*$lineheight, 
				'UTF-8');
			}
		  }
		} 
	}


//////////////////////////////////////////////////////////////////////////////////////////////////////
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // vorsitz
    $yStart=508;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_vorsitz'] );
    $text=( $this->plp_data['plp3_vorsitz'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // erstpruefer
    $yStart=490.5;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_erstpruefer'] );
    $text=( $this->plp_data['plp3_erstpruefer'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // zweitpruefer
    $yStart=473;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_zweitpruefer'] );
    $text=( $this->plp_data['plp3_zweitpruefer'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // betreuungslehrer
    $yStart=456;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_betreuungslehrer'] );
    $text=( $this->plp_data['plp3_betreuungslehrer'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // fachlehrer
    $yStart=438;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_fachlehrer'] );
    $text=( $this->plp_data['plp3_fachlehrer'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // zfl
    $yStart=421;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_zfl'] );
    $text=( $this->plp_data['plp3_zfl'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // kirchliche_oberbehoerde
    $yStart=404;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_kirchliche_oberbehoerde'] );
    $text=( $this->plp_data['plp3_kirchliche_oberbehoerde'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Vorstunde-Datum
    $yStart=386;
    $xStart=230;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=(     // utf8_encode
      substr($this->plp_data['vorstunde_datum'].'          ',8,2)
      .'.'.substr($this->plp_data['vorstunde_datum'].'          ',5,2)
      .'.'.substr($this->plp_data['vorstunde_datum'].'          ',0,4)
    );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Vorstunde-von
    $yStart=386;
    $xStart=370;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=(    // utf8_encode
      substr($this->plp_data['vorstunde_zeit_von'].'          ',0,5)
    );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Vorstunde-bis
    $yStart=386;
    $xStart=460;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=(    // utf8_encode
      substr($this->plp_data['vorstunde_zeit_bis'].'          ',0,5)
    );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Thema Kasten unten
    // range: X 47-543   Y 240(-$size)-302 / 230-302
    // mid:       295         271  /  265
    $yStart=302;
    $xStart=55;
    $xEnd=550;
    $yCenter=265+$size*0.5;
    $innerpagewidth=495; // 490
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $txt_arr=preg_split( '/ +/', utf8_decode($this->plp_data['plp3_thema']) );
    if (count($txt_arr)>0) {
      $text2 = new textblock2($innerpagewidth, $font, $size, true);
      for ($i=0; $i<count($txt_arr); $i++) {
        $text2->addWord( $txt_arr[$i].' ' );
      }

      if ($text2->getLineCount()==1) {
        // Text schreiben (nur eine Zeile) -> zentriert
        $page->drawText(
          $text2->getLine(0),
          $this->_centerstartposition_range($text2->getLine(0), $font, $size, $xStart, $xEnd),
          $yCenter,
          'UTF-8'
        );
      }
      elseif ($text2->getLineCount()>1) {
        // Text schreiben (mehrere Zeilen) -> links beginnen
        $ypos=$yCenter+0.5*$lineheight*$text2->getLineCount()-$size*0.5;
        $xpos=$xStart;
        for ($i=0; $i<$text2->getLineCount(); $i++) {
          $page->drawText($text2->getLine($i), $xpos, $ypos-$i*$lineheight, 'UTF-8');
        }
      }
    }

    // *** *** *** *** *** *** ***
    // erhalten am (rechts unten oberhalb der Unterschrift Refi)
    $yStart=169.2;
    $xStart=498;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=(     // utf8_encode
      substr($this->plp_data['eroeffnung_datum'].'          ',8,2)
      .'.'.substr($this->plp_data['eroeffnung_datum'].'          ',5,2)
      .'.'.substr($this->plp_data['eroeffnung_datum'].'          ',0,4)
    );

    $ypos=$yStart;
    $xpos=$xStart-0.5*$this->_textwidth($text, $font, $size);
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Unteschrift links - Seminarleitung GS
    $yStart=105.5;
    $xStart=220;
    $size=$standardSize-4;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['eroeffnung_durch'] );
    $text=( $this->plp_data['eroeffnung_durch'] );
    $ypos=$yStart;
    $xpos=$xStart-0.5*$this->_textwidth($text, $font, $size);
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Unteschrift rechts - Refi
    $yStart=105.5;
    $xStart=478;
    $size=$standardSize-4;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( ($this->plp_data['ref_anrede'] ? $this->plp_data['ref_anrede'].' ' : '').$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']  );
    $text=( ($this->plp_data['ref_anrede'] ? $this->plp_data['ref_anrede'].' ' : '').$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']  );
    $ypos=$yStart;
    $xpos=$xStart-0.5*$this->_textwidth($text, $font, $size);
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***


    // *** *** *** *** *** *** ***
    // Faxnummer GS rechts unten 
    $yStart=64.0;
    $xStart=470;
    $size=$standardSize-4;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['schulenGS_Fax'] );
    $text=( $this->plp_data['schulenGS_Fax'] );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***


    // ******************************
    // Ausgabe
    // ******************************
    $pdfAsString = $pdf->render();
    // header('Content-type: application/x-pdf');
    // header("Content-disposition: attachment; filename=$pdffilname"); 

      header("Pragma: public");
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Cache-Control: private",false);
      header('Content-type: application/x-pdf');
      header("Content-disposition: attachment; filename=$pdffilname");
      header("Content-Transfer-Encoding: binary");

    echo $pdfAsString;
    exit;
  }
  else {
    echo "PDF-Generierung nicht möglich.";
    exit;

  }
}


// ***************************** PDF
function getPdfPLP3Niederschrift() {
  $status=$this->getStatus();
  if ( $status=='fertig' ) {

    // *** *** *** *** *** *** ***
    // fuer PDF-Ausgabe
    // *** *** *** *** *** *** ***
    $tmp_name=$this->_formatText_getICal( ($this->plp_data['ref_anrede'] ? $this->plp_data['ref_anrede'].'-' : '').$this->plp_data['ref_vorname'].'-'.$this->plp_data['ref_nachname']  );
    $fileName="/www/data/ftp/rsmbobbn/_sys/libs/plp3tv/documents/plp3tvNiederschrift.pdf";
    $pdffilname="plp3tv-niederschrift-$tmp_name-".$this->plp_data['pkz'].'.pdf';
	$pdffilname=preg_replace("/[^a-zA-Z0-9\-.]/", "_", $pdffilname);


    $pdf = Zend_Pdf::load($fileName);
    $page = $pdf->pages[0];



    // *** *** *** *** *** *** ***
    // Einstellungen
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    $standardlineheight=18;
    $standardSize=12;
    $standardFont=Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);

	$this->plp_data['schulenPS_Schulname']=utf8_decode($this->plp_data['schulenPS_Schulname']);
	$this->plp_data['schulenPS_Schulname2']=utf8_decode($this->plp_data['schulenPS_Schulname2']);

    // *** *** *** *** *** *** ***
    // Start
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Studienseminar: (Kasten links oben)
    $yStart=793;
    $xStart=57;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);


    // Adresse soll vertikal zentriert im Kasten stehen
    if (!$this->plp_data['schulenGS_Schulname2']) {
      $yStart-=($lineheight/2);
    }

    // 4 Zeilen schreiben
    // $text=utf8_encode( $this->plp_data['schulenGS_Schulname'] );
    $text=( $this->plp_data['schulenGS_Schulname'] );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');

    if ($this->plp_data['schulenGS_Schulname2']) {
      // $text=utf8_encode( $this->plp_data['schulenGS_Schulname2'] );
      $text=( $this->plp_data['schulenGS_Schulname2'] );
      $ypos-=$lineheight;
      $xpos=$xStart;
      $page->drawText($text, $xpos, $ypos, 'UTF-8');
    }

    // $text=utf8_encode( $this->plp_data['schulenGS_Strasse'] );
    $text=( $this->plp_data['schulenGS_Strasse'] );
    $ypos-=$lineheight;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');

    // $text=utf8_encode( $this->plp_data['schulenGS_PLZ'].' '.$this->plp_data['schulenGS_Ort'] );
    $text=( $this->plp_data['schulenGS_PLZ'].' '.$this->plp_data['schulenGS_Ort'] );
    $ypos-=$lineheight;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Pruefungstermin: (Kasten rechts oben)
    $yStart=775;
    $size=$standardSize+2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( 'Prüfungstermin '.substr($this->plp_data['plp3_datum'].'    ',0,4) );
    $text=( 'Prüfungstermin '.substr($this->plp_data['plp3_datum'].'    ',0,4) );
    $ypos=$yStart;
    $xpos=$this->_centerstartposition_range($text, $font, $size, 296, 542);
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Referendarin
    $yStart=718.5;
    $xStart=218; 
    $size=$standardSize+1;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( ($this->plp_data['ref_anrede'] ? $this->plp_data['ref_anrede'].' ' : '')
    //  .$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']  );
    // $text=utf8_encode(   $this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']  );
    $tmpAnrede="";
    if ( $this->plp_data['ref_anrede']=="Stud.-Refin." or $this->plp_data['ref_anrede']=="Frau") { $tmpAnrede="Frau "; }
    if ( $this->plp_data['ref_anrede']=="Stud.-Ref." or $this->plp_data['ref_anrede']=="Herr")   { $tmpAnrede="Herr "; }
    // $text=utf8_encode( $tmpAnrede.$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']  );
    $text=( $tmpAnrede.$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']  );

    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Faecherverbindung
    $yStart=702.3;
    $xStart=218;
    $size=$standardSize-1;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['fach1'].' / '.$this->plp_data['fach2'].($this->plp_data['fach3'] ? ' / '.$this->plp_data['fach3'] : ''));
    $text=( $this->plp_data['fach1'].' / '.$this->plp_data['fach2'].($this->plp_data['fach3'] ? ' / '.$this->plp_data['fach3'] : ''));
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Unterrichtsfach Mittelblock
    $yStart=611; //596.5;
    $xStart=182;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_fach_bezeichnung'] );
    $text=( $this->plp_data['plp3_fach_bezeichnung'] );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Pruefungsort
    $yStart=593.5;//579;
    $xStart=182;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['schulenES_Schulname'].($this->plp_data['schulenES_Schulname2'] ? ', '.$this->plp_data['schulenES_Schulname2'] : '') );
    $text=( $this->plp_data['schulenES_Schulname'].($this->plp_data['schulenES_Schulname2'] ? ', '.$this->plp_data['schulenES_Schulname2'] : '') );
    if ( $this->_textwidth($text, $font, $size)+$xStart > 540 ) {
      // $text=utf8_encode( $this->plp_data['schulenES_Schulname'].' ('.$this->plp_data['schulenES_Schulnr'].')' );
      $text=( $this->plp_data['schulenES_Schulname'].' ('.$this->plp_data['schulenES_Schulnr'].')' );
    }
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Klasse
    $yStart=576;//561.5;
    $xStart=182;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_klasse'] );
    $text=( $this->plp_data['plp3_klasse'] );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***


    // *** *** *** *** *** *** ***
    // Datum
    $yStart=549.5;//534.5;
    $xStart=230;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=(   // utf8_encode
      substr($this->plp_data['plp3_datum'].'          ',8,2)
      .'.'.substr($this->plp_data['plp3_datum'].'          ',5,2)
      .'.'.substr($this->plp_data['plp3_datum'].'          ',0,4)
    );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // von
    $yStart=549.5;//534.5;
    $xStart=370;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=(  // utf8_encode
      substr($this->plp_data['plp3_zeit_von'].'          ',0,5)
    );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // bis
    $yStart=549.5;//534.5;
    $xStart=460;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=(   // utf8_encode
      substr($this->plp_data['plp3_zeit_bis'].'          ',0,5)
    );
    $ypos=$yStart;
    $xpos=$xStart;
    $page->drawText($text, $xpos, $ypos, 'UTF-8');
    // *** *** *** *** *** *** ***


    // *** *** *** *** *** *** ***
    // pruefende Seminarschule (links)
    $yStart=500.5;//486;
    $xStart=115;
	$innerpagewidth=118;
    $size=$standardSize-5;
    $lineheight=($size*1.2);
    $font=$standardFont;
    $page->setFont($font, $size);
	
	$textOK=true;
    $text=( $this->plp_data['schulenPS_Schulname'] );
	if ($this->_textwidth($text, $font, $size)>$innerpagewidth) {$textOK=false;}

    if ($this->plp_data['schulenPS_Schulname2']) {
      $text=$this->plp_data['schulenPS_Schulname2'];
	  if ($this->_textwidth($text, $font, $size)>$innerpagewidth) {$textOK=false;}
	}
	
    if ($textOK) {
		// $text=utf8_encode( $this->plp_data['schulenPS_Schulname'] );
		$text=( $this->plp_data['schulenPS_Schulname'] );
		$ypos=$yStart;
		$xpos=$xStart-0.5*$this->_textwidth($text, $font, $size);
		$page->drawText($text, $xpos, $ypos, 'UTF-8');
	
		if ($this->plp_data['schulenPS_Schulname2']) {
		  // $text=utf8_encode($this->plp_data['schulenPS_Schulname2']);
		  $text=($this->plp_data['schulenPS_Schulname2']);
		  $ypos=$yStart-$lineheight;
		  $xpos=$xStart-0.5*$this->_textwidth($text, $font, $size);
		  $page->drawText($text, $xpos, $ypos, 'UTF-8');
		}
	}
	else { // MEHRZEILIG
		$yStart=500.5;
		$xStart=52;
		$xEnd=170;
		$yCenter=500.5;
		$innerpagewidth=118;
		$size=$standardSize-5;
		$lineheight=($size*1.2);
		$font=$standardFont;
		$page->setFont($font, $size);
	
		$textPS=( $this->plp_data['schulenPS_Schulname'].( $this->plp_data['schulenPS_Schulname2'] ? ', '.$this->plp_data['schulenPS_Schulname2'] :'' ) );
	
		$txt_arr=preg_split( '/ +/', $textPS );
		if (count($txt_arr)>0) {
		  $text3 = new textblock2($innerpagewidth, $font, $size, true);
		  for ($i=0; $i<count($txt_arr); $i++) {
			$text3->addWord( $txt_arr[$i].' ' );
		  }
	
		  if ($text3->getLineCount()==1) {
			// Text schreiben (nur eine Zeile) -> zentriert
			$page->drawText(
			  ($text3->getLine(0)),  // utf8_encode
			  $this->_centerstartposition_range(($text3->getLine(0)), $font, $size, $xStart, $xEnd),
			  $yCenter,
			  'UTF-8'
			);
		  }
		  elseif ($text3->getLineCount()>1) {
			// Text schreiben (mehrere Zeilen) -> links beginnen
			$ypos=$yCenter; // $yCenter+0.5*$lineheight*$text3->getLineCount()-$size*0.5;
			if ($text3->getLineCount()>2) {$ypos=$yCenter+2;}
			$xpos=$xStart;
			for ($i=0; $i<$text3->getLineCount(); $i++) {
			  $page->drawText(
				($text3->getLine($i)), 
				// $xpos, 
				$this->_centerstartposition_range(($text3->getLine($i)), $font, $size, $xStart, $xEnd),
				$ypos-$i*$lineheight, 
				'UTF-8');
			}
		  }
		} 
	}



    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // vorsitz
    $yStart=522.5;//508;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_vorsitz'] );
    $text=( $this->plp_data['plp3_vorsitz'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // erstpruefer
    $yStart=505;//490.5;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_erstpruefer'] );
    $text=( $this->plp_data['plp3_erstpruefer'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // zweitpruefer
    $yStart=487.5;//473;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_zweitpruefer'] );
    $text=( $this->plp_data['plp3_zweitpruefer'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // betreuungslehrer
    $yStart=470.5;//456;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_betreuungslehrer'] );
    $text=( $this->plp_data['plp3_betreuungslehrer'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // fachlehrer
    $yStart=452.5;//438;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_fachlehrer'] );
    $text=( $this->plp_data['plp3_fachlehrer'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // zfl
    $yStart=435.5;//421;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_zfl'] );
    $text=( $this->plp_data['plp3_zfl'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // kirchliche_oberbehoerde
    $yStart=418.5;//404;
    $xStart=344;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    // $text=utf8_encode( $this->plp_data['plp3_kirchliche_oberbehoerde'] );
    $text=( $this->plp_data['plp3_kirchliche_oberbehoerde'] );
    $ypos=$yStart;
    $xpos=$xStart;
	if ($text != "-") { $page->drawText($text, $xpos, $ypos, 'UTF-8'); }
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Thema Kasten unten
    // range: X 47-543   Y 240(-$size)-302 / 230-302
    // mid:       295         271  /  265
    $yStart=302;
    $xStart=55;
    $xEnd=550;
    $yCenter=346+$size*0.5; // 265+$size*0.5;
    $innerpagewidth=495; // 490
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $txt_arr=preg_split( '/ +/', utf8_decode($this->plp_data['plp3_thema']) );
    if (count($txt_arr)>0) {
      $text2 = new textblock2($innerpagewidth, $font, $size, true);
      for ($i=0; $i<count($txt_arr); $i++) {
        $text2->addWord( $txt_arr[$i].' ' );
      }

      if ($text2->getLineCount()==1) {
        // Text schreiben (nur eine Zeile) -> zentriert
        $page->drawText(
          $text2->getLine(0),
          $this->_centerstartposition_range($text2->getLine(0), $font, $size, $xStart, $xEnd),
          $yCenter,
          'UTF-8'
        );
      }
      elseif ($text2->getLineCount()>1) {
        // Text schreiben (mehrere Zeilen) -> links beginnen
        $ypos=$yCenter+0.5*$lineheight*$text2->getLineCount()-$size*0.5;
        $xpos=$xStart;
        for ($i=0; $i<$text2->getLineCount(); $i++) {
          $page->drawText($text2->getLine($i), $xpos, $ypos-$i*$lineheight, 'UTF-8');
        }
      }
    }


    // *** *** *** *** *** *** ***
    // 2. Seite
    $page = $pdf->pages[1];
    // *** *** *** *** *** *** ***

    // *** *** *** *** *** *** ***
    // Ort, den Datum (zweite Seite unten mittig)
    $yStart=180;
    $xStart=52;
    $xEnd=538;
    $size=$standardSize-2;
    $lineheight=($size*1.4);
    $font=$standardFont;
    $page->setFont($font, $size);

    $text=(   // utf8_encode
      $this->plp_data['schulenES_Ort']
      .', den '
      .substr($this->plp_data['plp3_datum'].'          ',8,2)
      .'.'.substr($this->plp_data['plp3_datum'].'          ',5,2)
      .'.'.substr($this->plp_data['plp3_datum'].'          ',0,4)
    );

    $ypos=$yStart;
    $page->drawText(
      $text,
      $this->_centerstartposition_range($text, $font, $size, $xStart, $xEnd),
      $ypos,
      'UTF-8'
    );

    // *** *** *** *** *** *** ***


    // ******************************
    // Ausgabe
    // ******************************
    $pdfAsString = $pdf->render();
    // header('Content-type: application/x-pdf');
    // header("Content-disposition: attachment; filename=$pdffilname");

      header("Pragma: public");
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Cache-Control: private",false);
      header('Content-type: application/x-pdf');
      header("Content-disposition: attachment; filename=$pdffilname");
      header("Content-Transfer-Encoding: binary");

    echo $pdfAsString;
    exit;
  }
  else {
    echo "PDF-Generierung nicht möglich.";
    exit;

  }
}

function pdflist($type='', $sort='') {
	$data=array(); $als_schule="";
	if ($type=='gs') { $data = $this->grund_refs;   $als_schule="grundst. Seminarschule"; }
	if ($type=='es') { $data = $this->einsatz_refs; $als_schule="Einsatzschule"; }
	if ($type=='ps') { $data = $this->pruef_refs;   $als_schule="prüf. Seminarschule";   }

	$tabellen=array(); $header=array();
	if ($sort == 'eroeffnung') {
		$header['h1']="PLP3-Eröffnungen (als $als_schule)";
		$header['h2']='Stand: '.date('d.m.Y H:i');
		$header['fussnote']='E = Eröffnung agbeschlossen';
		$tabellen[0]['spaltenbreiten'] = array(20,4,40,55,55);
		$tabellen[0]['ueberschriften'] = array('Eröffnung', 'E', 'Fach', 'Referendar', 'Notizen');
		$tabellen[0]['optionen'] = array('linien' => true);
		$tabellen[0]['optionen']['padding']=2;
		for ($i=0; $i<count( $data );$i++) {
			$tabellen[0]['tabelle'][]=array(
				$data[$i]['eroeffnung_datum'] ? date('d.m.Y', strtotime($data[$i]['eroeffnung_datum'])) : '',
					// date('d.m.Y', strtotime($data[$i]['eroeffnung_datum'])),
					// $data[$i]['eroeffnung_datum'],
				($data[$i]['eroeffnung_erledigt'] ? 'X' : ''),
				($data[$i]['plp3_fach_bezeichnung'] ? $data[$i]['plp3_fach_bezeichnung'] : $data[$i]['plp3_fach']),
				$data[$i]['ref_vorname'].' '.$data[$i]['ref_nachname'], 
				''
			);
		}
	}
	elseif ($sort == 'pruefungstermine') {
		$header['h1']="PLP3-Termine (als $als_schule)";
		$header['h2']='Stand: '.date('d.m.Y H:i');
		$tabellen[0]['spaltenbreiten'] = array(20,40,55,59);
		$tabellen[0]['ueberschriften'] = array('PLP3 am', 'Fach', 'Referendar', 'Notizen');
		$tabellen[0]['optionen'] = array('linien' => true);
		$tabellen[0]['optionen']['padding']=2;
		for ($i=0; $i<count( $data );$i++) {
			$tabellen[0]['tabelle'][]=array(
				$data[$i]['plp3_datum'] ? date('d.m.Y', strtotime($data[$i]['plp3_datum'])) : '',
				// date('d.m.Y', strtotime($data[$i]['plp3_datum'])),
				// $data[$i]['plp3_datum'],
				($data[$i]['plp3_fach_bezeichnung'] ? $data[$i]['plp3_fach_bezeichnung'] : $data[$i]['plp3_fach']),
				$data[$i]['ref_vorname'].' '.$data[$i]['ref_nachname'],
				''
			);
		}
	}
	elseif ($sort == 'pruefungsfach') {
		$header['h1']="PLP3s nach Prüfungsfächer (als $als_schule)";
		$header['h2']='Stand: '.date('d.m.Y H:i');
		$t=-1; $tmp_fach="";
		for ($i=0; $i<count( $data );$i++) {
			if ( $tmp_fach != ($data[$i]['plp3_fach_bezeichnung'] ? $data[$i]['plp3_fach_bezeichnung'] : $data[$i]['plp3_fach']) ) {
				$t++;
				$tabellen[$t]['h1'] = 
					($data[$i]['plp3_fach_bezeichnung'] ? $data[$i]['plp3_fach_bezeichnung'] : $data[$i]['plp3_fach']);
				$tabellen[$t]['spaltenbreiten'] = array(20,55,99);
				$tabellen[$t]['ueberschriften'] = array('PLP3 am', 'Referendar', 'Notizen');
				$tabellen[$t]['optionen'] = array('linien' => true);
				$tabellen[$t]['optionen']['padding']=2;
				$tmp_fach = $tabellen[$t]['h1'];
			}
			$tabellen[$t]['tabelle'][]=array(
				$data[$i]['plp3_datum'] ? date('d.m.Y', strtotime($data[$i]['plp3_datum'])) : '',
				// date('d.m.Y', strtotime($data[$i]['plp3_datum'])),
				// $data[$i]['plp3_datum'],
				$data[$i]['ref_vorname'].' '.$data[$i]['ref_nachname']
			);
		}
	}
	else {
		$header['h1']=="leer";
	}

	$this->getPdfList($header, $tabellen);
}

// ***************************** PDF-Tabelle
private function getPdfList($header, $tabellen) {
	// *** *** *** *** *** *** ***
	// fuer PDF-Ausgabe
	// *** *** *** *** *** *** ***

	$fileName="/www/data/ftp/rsmbobbn/_sys/libs/plp3tv/documents/BRN-PLP3TV-Liste.pdf";
	
	$pdffilname=preg_replace("/[^a-zA-Z0-9.\-]+/i", '-', "liste-".$header['h1'].'.pdf');

	$pdf=new Zend_Pdf();
	$pdf->pages[] = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
	$page = $pdf->pages[0];
	$geschrieben=array();
	//$page=$pdf->pages[count($pdf->pages)-1];

	$yTop=760; $xLeft=40;
	$xWidth=520; $yHeight=700;
	
	$yMin=$yTop-$yHeight;

	// *** *** *** *** *** *** ***
	// Start
	// *** *** *** *** *** *** ***
				
	// *** *** *** *** *** *** ***
	// Einstellungen global/Start
	$standardlineheight=16;
	$standardSize=11;
	$shift_betweenLine=$standardSize;

	$standardFont=Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
	$standardFontBold=Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD);
	
	$yCursor=$yTop;
	$xCursor=$xLeft;
	// *** *** *** *** *** *** ***

	// *** *** *** *** *** *** ***
	// Ueberschrift (Listname)
	$size=$standardSize+4; $font=$standardFontBold;
	$page->setFont($font, $size);
	
	// $text=utf8_encode( $header['h1'] );
	$text=( $header['h1'] );
	$xpos=$this->_centerstartposition_range($text, $font, $size, $xLeft, $xLeft+$xWidth);
	$page->drawText($text, $xpos, $yCursor, 'UTF-8');
	$geschrieben[count($pdf->pages)-1]++;
	
	$xCursor=$xLeft; $yCursor-=($standardlineheight+10);
	if ($yCursor<$yMin) { $pdf->pages[]=$pdf->newPage(Zend_Pdf_Page::SIZE_A4); $page=$pdf->pages[count($pdf->pages)-1]; $yCursor=$yTop; $page->setFont($font, $size); }
	// *** *** *** *** *** *** ***

	// *** *** *** *** *** *** ***
	// Unterueberschrift, falls vorhanden
	if (isset($header['h2']) and $header['h2']) {
		$size=$standardSize; $font=$standardFontBold;
		$page->setFont($font, $size);
		
		// $text=utf8_encode( $header['h2'] );
		$text=( $header['h2'] );
		$xpos=$this->_centerstartposition_range($text, $font, $size, $xLeft, $xLeft+$xWidth);
		$page->drawText($text, $xpos, $yCursor+6, 'UTF-8');
		$geschrieben[count($pdf->pages)-1]++;
		
		$xCursor=$xLeft; $yCursor-=($standardlineheight+4);
	}
	// *** *** *** *** *** *** ***

	// *** *** *** *** *** *** ***
	// Fussnote
	if (isset($header['fussnote']) and $header['fussnote']) {
		$size=$standardSize*0.5; $font=$standardFont;
		$page->setFont($font, $size);
		
		// $text=utf8_encode( $header['fussnote'] );
		$text=( $header['fussnote'] );
		$page->drawText($text, $xLeft, $yMin*0.6, 'UTF-8');
		$geschrieben[count($pdf->pages)-1]++;
	}
	// *** *** *** *** *** *** ***


	for ($t=0; $t<count($tabellen);$t++) {
		$linien=false; $li=array();
		if (isset($tabellen[$t]['optionen']['linien']) and $tabellen[0]['optionen']['linien']) {
			$linien=true; $tabellen[$t]['optionen']['padding']+=0;
			$li['links']=$xLeft; $li['rechts']=$xLeft+$xWidth;
			$li['oben']=$yCursor+0.5*$standardSize; $li['unten']=$yCursor;
			$li['padding']=$tabellen[$t]['optionen']['padding'];
		}
		
		// *** *** *** *** *** *** ***
		// Tabellenueberschrift, falls vorhanden
		if (isset($tabellen[$t]['h1']) and $tabellen[$t]['h1']) {
			$size=$standardSize+2; $font=$standardFontBold;
			$page->setFont($font, $size);
			
			$yCursor-=$standardlineheight;
			// $text=utf8_encode( $tabellen[$t]['h1'] );
			$text=( $tabellen[$t]['h1'] );
			$xpos=$xLeft;
			$page->drawText($text, $xpos, $yCursor, 'UTF-8');
			$geschrieben[count($pdf->pages)-1]++;

			$xCursor=$xLeft; $yCursor-=($standardlineheight);
			if ($yCursor<$yMin) {
				if ($linien) { 
					$this->draw_TableLines($page, $li['vonX'], array_fill(0, count($li['vonX']), $li['oben']), $li['vonX'], array_fill(0, count($li['vonX']), $li['unten']+$standardSize));
					$li['oben']=$yTop+$shift_betweenLine; $li['unten']=$yTop+$shift_betweenLine;
				}
				$pdf->pages[]=$pdf->newPage(Zend_Pdf_Page::SIZE_A4); $page=$pdf->pages[count($pdf->pages)-1]; $yCursor=$yTop; $page->setFont($font, $size); 
				if ($linien) { $page->drawLine($li['links']-$li['padding'], $li['oben'], $li['rechts']-$li['padding'], $li['oben']); }
			}
		}

		// *** *** *** *** *** *** ***
		$spaltenbreiten=$tabellen[$t]['spaltenbreiten'];
		$ueberschriften=$tabellen[$t]['ueberschriften'];
		$tabelle=$tabellen[$t]['tabelle'];

		// *** *** *** *** *** *** ***
		// Spaltenbreiten festlegen
		$spaltenanzahl=count($spaltenbreiten);
		if ($linien) { $li['vonX']=$spaltenbreiten; array_unshift($li['vonX'], '-1'); }

		$tmp_breite_ges=0;
		for ($i=0; $i<$spaltenanzahl; $i++) { $tmp_breite_ges+=$spaltenbreiten[$i]; }
		
		$tmp_breite=($tmp_breite_ges > 0 ? $xWidth/$tmp_breite_ges : 1);
		for ($i=0; $i<$spaltenanzahl; $i++) {
			$spaltenbreiten[$i]=$spaltenbreiten[$i]*$tmp_breite; 
		}
		if ($linien) {
			$tmp_breite=($tmp_breite_ges > 0 ? ($li['rechts']-$li['links'])/$tmp_breite_ges : 1);
			$li['vonX'][0]=$li['links']-$li['padding']; 
			for ($i=1; $i<$spaltenanzahl+1; $i++) {
				$li['vonX'][$i]=$li['vonX'][$i-1]+$li['vonX'][$i]*$tmp_breite; 
			}
		}
		// *** *** *** *** *** *** ***

		// *** *** *** *** *** *** ***
		// Spaltenueberschriften
		$li['oben']=$yCursor+0.5*$standardSize; $li['unten']=$yCursor;				
		if ($linien) { $page->drawLine($li['links']-$li['padding'], $li['oben'], $li['rechts']-$li['padding'], $li['oben']); }
		$li['oben']=$yCursor+0.5*$standardSize; $li['unten']=$yCursor;				
		$yCursor-=$standardlineheight*0.5;
		$size=$standardSize; $font=$standardFontBold;
		$page->setFont($font, $size);
		
		$xpos=$xLeft;
		for ($i=0; $i<$spaltenanzahl; $i++) {
			// $text=utf8_encode( $ueberschriften[$i] );
			$text=( $ueberschriften[$i] );
			$page->drawText($text, $xpos, $yCursor, 'UTF-8');
			$geschrieben[count($pdf->pages)-1]++;
			$xpos+=$spaltenbreiten[$i];
		}

		$xCursor=$xLeft; $yCursor-=$standardlineheight;
		$li['unten']=$yCursor;
		if ($linien) { $page->drawLine($li['links']-$li['padding'], $yCursor+$shift_betweenLine, $li['rechts']-$li['padding'], $yCursor+$shift_betweenLine); }
		if ($yCursor<$yMin) {
			if ($linien) { 
				$this->draw_TableLines($page, $li['vonX'], array_fill(0, count($li['vonX']), $li['oben']), $li['vonX'], array_fill(0, count($li['vonX']), $li['unten']+$standardSize));
				$li['oben']=$yTop+$shift_betweenLine; $li['unten']=$yTop+$shift_betweenLine;
			}
			$pdf->pages[]=$pdf->newPage(Zend_Pdf_Page::SIZE_A4); $page=$pdf->pages[count($pdf->pages)-1]; $yCursor=$yTop; $page->setFont($font, $size); 
			if ($linien) { $page->drawLine($li['links']-$li['padding'], $li['oben'], $li['rechts']-$li['padding'], $li['oben']); }
		}
		// *** *** *** *** *** *** ***

		// *** *** *** *** *** *** ***
		// Tabelle ausgeben
		$size=$standardSize; $font=$standardFont;
		$page->setFont($font, $size);

		for ($z=0; $z<count($tabelle); $z++) {
			$xpos=$xLeft;
			for ($i=0; $i<$spaltenanzahl; $i++) {
				// $text=utf8_encode( $tabelle[$z][$i] );
				$text=( $tabelle[$z][$i] );
				$page->drawText($text, $xpos, $yCursor, 'UTF-8');
				$geschrieben[count($pdf->pages)-1]++;
				$xpos+=$spaltenbreiten[$i];
			}
			$xCursor=$xLeft; $yCursor-=$standardlineheight;
			$li['unten']=$yCursor;
			if ($linien) { $page->drawLine($li['links']-$li['padding'], $yCursor+$shift_betweenLine, $li['rechts']-$li['padding'], $yCursor+$shift_betweenLine); }
			if ($yCursor<$yMin) {
				if ($linien) { 
					$this->draw_TableLines($page, $li['vonX'], array_fill(0, count($li['vonX']), $li['oben']), $li['vonX'], array_fill(0, count($li['vonX']), $li['unten']+$standardSize));
					$li['oben']=$yTop+$shift_betweenLine; $li['unten']=$yTop+$shift_betweenLine;
				}
				$pdf->pages[]=$pdf->newPage(Zend_Pdf_Page::SIZE_A4); $page=$pdf->pages[count($pdf->pages)-1]; $yCursor=$yTop; $page->setFont($font, $size);
				if ($linien) { $page->drawLine($li['links']-$li['padding'], $li['oben'], $li['rechts']-$li['padding'], $li['oben']); }
			}
		}
		$li['unten']=$yCursor;
		if ($yCursor<$yMin) {
			if ($linien) { 
				$this->draw_TableLines($page, $li['vonX'], array_fill(0, count($li['vonX']), $li['oben']), $li['vonX'], array_fill(0, count($li['vonX']), $li['unten']+$standardSize));
				$li['oben']=$yTop+$shift_betweenLine; $li['unten']=$yTop+$shift_betweenLine;
			}
			$pdf->pages[]=$pdf->newPage(Zend_Pdf_Page::SIZE_A4); $page=$pdf->pages[count($pdf->pages)-1]; $yCursor=$yTop; $page->setFont($font, $size); 
			if ($linien) { $page->drawLine($li['links']-$li['padding'], $li['oben'], $li['rechts']-$li['padding'], $li['oben']); }
		}
		// *** *** *** *** *** *** ***
		if ($linien) { $this->draw_TableLines($page, $li['vonX'], array_fill(0, count($li['vonX']), $li['oben']), $li['vonX'], array_fill(0, count($li['vonX']), $li['unten']+$standardSize)); }
	}

	if (count($pdf->pages)>1) {
		if (!$geschrieben[count($pdf->pages)-1]) {
			unset($pdf->pages[count($pdf->pages)-1]);
		}
	}

	// ******************************
	// Ausgabe
	// ******************************
	$pdfAsString = $pdf->render();
	// header('Content-type: application/x-pdf');
	// header("Content-disposition: attachment; filename=$pdffilname"); 
	
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Cache-Control: private",false);
	header('Content-type: application/x-pdf');
	header("Content-disposition: attachment; filename=$pdffilname");
	header("Content-Transfer-Encoding: binary");
	
	echo $pdfAsString;
}

function draw_TableLines($page, $vonX=array(), $vonY=array(), $nachX=array(), $nachY=array()) {
	for ($i=0; $i<min( count($vonX), count($vonY), count($nachX), count($nachY) ); $i++){
		$page->drawLine($vonX[$i], $vonY[$i], $nachX[$i], $nachY[$i]);
	}
}

function _textwidth($string, $font, $fontSize) {
  return $this->_fontStringWidth($string, $font, $fontSize);
}

function _rightstartposition($right, $string, $font, $fontSize) {
  $textwidth=$this->_fontStringWidth($string, $font, $fontSize);
  return ( $right - $textwidth );
}

function _rightjustifiedstartposition($page, $string, $font, $fontSize){
  $textwidth=$this->_fontStringWidth($string, $font, $fontSize);
  $pagewidth=$page->getWidth();
  return (($pagewidth-$textwidth));
}

function _centerstartposition($page, $string, $font, $fontSize) {
  $textwidth=$this->_fontStringWidth($string, $font, $fontSize);
  $pagewidth=$page->getWidth();
  return (($pagewidth-$textwidth) * 0.5);
}

function _centerstartposition_range($string, $font, $fontSize, $xLeft, $xRight) {
  $textwidth=$this->_fontStringWidth($string, $font, $fontSize);
  return (($xLeft+$xRight-$textwidth) * 0.5);
}


function _fontStringWidth($string, $font, $fontSize){
  // #if (strpos($string,utf8_encode('?'))!==false) { echo $string; die(); }
//  $pattern_s = array(utf8_encode('ä'),utf8_encode('ö'),utf8_encode('ü'),
//             utf8_encode('Ä'),utf8_encode('Öœ'),utf8_encode('Ü„'),
//             utf8_encode('ß'));
//  $replace_s = array(utf8_encode('a'),utf8_encode('o'),utf8_encode('u'),
//             utf8_encode('A'),utf8_encode('O'),utf8_encode('U'),
//             utf8_encode('S'));
  $pattern_s = array(('ä'),('ö'),('ü'),
             ('Ä'),('Ö'),('Ü'),
             ('ß'));
  $replace_s = array(('a'),('o'),('u'),
             ('A'),('O'),('U'),
             ('S'));
  $string = str_replace($pattern_s,$replace_s,$string);
  $string = preg_replace('/[^a-zA-Z0-9 :();.,\-\+]/', 'W', $string);
  // # Inoffizielle Funktion aus dem Zend-WiKi
  // #$drawingString = iconv('', 'UTF-16BE', $string);
  $drawingString = iconv('', 'UTF-16BE', $string);
  $characters = array();
  for ($i = 0; $i < strlen($drawingString); $i++) {
    $characters[] = (ord($drawingString[$i++]) << 8) | ord($drawingString[$i]);
  }
  $glyphs = $font->glyphNumbersForCharacters($characters);
  $widths = $font->widthsForGlyphs($glyphs);
  $stringWidth = (array_sum($widths) / $font->getUnitsPerEm()) * $fontSize;

  return $stringWidth;
}

// ***************************** ENDE PDF


function getMail($type){
  $mail=array();
  // ggf. mit $this->_formatText_getICal statt mit rawurlencode

  switch ($type) {
    case 'zeitverlaengerung':
      $mail['zeitverlaengerung']['body']=
        rawurlencode($this->_formatText_getICal(
          "Sehr geehrter Herr Seminarleiter, "
          ."\nsehr geehrte Frau Seminarleiterin, "
          ."\n\nfür die 3. Prüfungslehrprobe von ".$this->plp_data['ref_vorname']." ".$this->plp_data['ref_nachname']
            ." wurde eine Zeitverlängerung beantragt und genehmigt. "
          ."\nBitte vereinbaren Sie mit der Einsatzschule einen neuen Beginn bzw. ein neues Ende der Prüfungslehrprobe. "
          ."\n\nMit freundlichen GrüßŸen "
          ."\n\n "
        ));
      $mail['zeitverlaengerung']['subject']=
        rawurlencode($this->_formatText_getICal('PLP3-Terminvereinbarung: Zeitverlängerung bei PLP3 - '
          .$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']
        ));
    break;
    case 'terminPLPok':
      $mail['terminPLPok']['body']=
        rawurlencode($this->_formatText_getICal(
          "Sehr geehrter Herr Seminarleiter, "
          ."\nsehr geehrte Frau Seminarleiterin, "
          ."\n\nder Termin für die Prüfungslehrprobe von ".$this->plp_data['ref_vorname']." "
          	.$this->plp_data['ref_nachname']." wurde für den "
            .substr($this->plp_data['plp3_datum'],8,2).'.'
            .substr($this->plp_data['plp3_datum'],5,2).'.' 
            .substr($this->plp_data['plp3_datum'],0,4)
            ." festgesetzt. "
          ."\nDie weiteren Daten der Lehrprobe können nun im BRN vervollständigt werden. "
          ."\n\nMit freundlichen GrüßŸen "
          ."\n\n "
        ));
      $mail['terminPLPok']['subject']=
        rawurlencode($this->_formatText_getICal(
          'PLP3-Terminvereinbarung - '.$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']
        ));
    break;
  }


/*
  switch ($type) {
    case 'zeitverlaengerung':
      $mail['zeitverlaengerung']['body']=
rawurlencode('Sehr geehrter Herr Seminarleiter,
sehr geehrte Frau Seminarleiterin,

f?r die 3. Pr?fungslehrprobe von '.$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname'].' wurde eine Zeitverl?ngerung beantragt und genehmigt.
Bitte vereinbaren Sie mit der Einsatzschule einen neuen Beginn bzw. ein neues Ende der Pr?fungslehrprobe.

Mit freundlichen Gr??en');
      $mail['zeitverlaengerung']['subject']=
rawurlencode('PLP3-Terminvereinbarung: Zeitverl?ngerung bei PLP3 - '.$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']);
    break;


    case 'terminPLPok':
      $mail['terminPLPok']['body']=
rawurlencode('Sehr geehrter Herr Seminarleiter,
sehr geehrte Frau Seminarleiterin,

der Termin f?r die Pr?fungslehrprobe von '.$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname'].' wurde f?r den '.$this->plp_data['plp3_datum'].' festgesetzt.
Die weiteren Daten der Lehrprobe k?nnen nun im BRN vervollst?ndigt werden.

Mit freundlichen Gr??en');
      $mail['terminPLPok']['subject']=
rawurlencode('PLP3-Terminvereinbarung - '.$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']);
    break;
  }
*/


  return $mail;
}


function checkZeitverlaengerung($sd) {

  return true;
}

function getFehlerBeiZeitverlaengerung() {
  global $db;

  $query=$this->querySelectFrom_PLP3s();
  $query.= " WHERE
    (
      ( snr_pruef = '".$this->schulnummer."' )
      AND
      ( schuljahr = '".$this->schuljahr."' )
    )
    AND (
      `plp3_zeit_von` <> ''
      AND `plp3_zeit_von` <> '00:00:00'
      AND `plp3_zeit_von` <> '00:00'
      AND `plp3_zeit_bis` <> ''
      AND `plp3_zeit_bis` <> '00:00:00'
      AND `plp3_zeit_bis` <> '00:00'
      AND `plp3_zeitverlaengerung`
      AND `plp3_zeitverlaengerung_auf_minuten` >0
    )
    AND (
      ADDTIME( `plp3_zeit_von` , SEC_TO_TIME( `plp3_zeitverlaengerung_auf_minuten` *60 ) ) <> `plp3_zeit_bis`
    )
  ";
  $query.=$this->querySelectFrom_ORDER_PLP3s('ps');

  if ($this->debug>=3) { echo $this->html_newline, $query, $this->html_newline; }

  $fehler_bei_zeitverlaengerung=array();

  $rs = $db->Execute($query);

  while (!$rs->EOF) {
    $fehler_bei_zeitverlaengerung[] = $this->_my_stripslashes_array($rs->fields);
    $rs->MoveNext();
  }

  return $fehler_bei_zeitverlaengerung;
}


function getFehlerBeiEroeffnung() {
  global $db;

  $query=$this->querySelectFrom_PLP3s();
  $query.= " WHERE
    (
      ( snr_gs = '".$this->schulnummer."' )
      AND
      ( schuljahr = '".$this->schuljahr."' )
    )
    AND (
      `plp3_datum` <> ''
      AND `plp3_datum` <> '0000-00-00'
      AND `eroeffnung_datum` <> ''
      AND `eroeffnung_datum` <> '0000-00-00'
    )
    AND (
      DATEDIFF( `plp3_datum`, `eroeffnung_datum`) <> 14
    )
  ";

  // $query.=$this->querySelectFrom_ORDER_PLP3s('ps');

  if ($this->debug>=3) { echo $this->html_newline, $query, $this->html_newline; }

  $fehler_bei_eroeffnung=array();

  $rs = $db->Execute($query);

  while (!$rs->EOF) {
    $fehler_bei_eroeffnung[] = $this->_my_stripslashes_array($rs->fields);
    $rs->MoveNext();
  }

  return $fehler_bei_eroeffnung;
}


function csvExport(){
  $schulnummer=$this->schulnummer;
  $filname='PLP3_SemDB_SNr'.$schulnummer.'.csv';

  $setSize=false;
  $csv_export=$this->_getExportSettings($setSize);

  $csvdata='';

  //headlines
  foreach ($csv_export as $csvD) {
    $csvdata.=$this->_formatCsvData( $csvD['headline'] , $csvD['size'], $csvD['setSize']);
  }
  $csvdata.="\n";

  //data
  foreach( $this->grund_refs as $refdata ){
    foreach ($csv_export as $csvD_key => $csvD) {
      $csvdata.=$this->_formatCsvData($refdata[$csvD_key], $csvD['size'], $csvD['setSize']);
    }
    $csvdata.="\n";
  }

  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Cache-Control: private",false);
  header("content-type: application/csv-tab-delimited-table");
  header("content-length: ".strlen($csvdata));
  header('content-disposition: attachment; filename="'.$filname.'"');
  header("Content-Transfer-Encoding: binary");


  echo $csvdata;
  exit;
}


private function _formatCsvData($data, $size, $setSize=true) {
	$data=utf8_decode($data);
  if ($setSize) {
    $str_lenth=strlen($data);
    if ($str_lenth>$size) {
      $data='"'.$this->_formatCsvData_inner_Gaensefuesschen(substr($data,0,$size)).'";';
    }
    else { // ($str_lenth<4)
      $data=(str_pad('"'.$this->_formatCsvData_inner_Gaensefuesschen($data).'"', $size+2, " ")).';';
    }
  }
  else {
    $data='"'.$this->_formatCsvData_inner_Gaensefuesschen($data).'";';
  }
  
  return $data;
}
private function _formatCsvData_inner_Gaensefuesschen($s) {
	$suchmuster = '/\"/i';
	$ersetzung = '""';
	return preg_replace($suchmuster, $ersetzung, $s);
}

function getICal($schule, $typ) {
  $organizer = (array) array(); // (array) array('www.realschule.bayern.de', 'mbino@realschule-bayern.info');
  $categories = array('3. PLP');
  $end_date = '';
  $start_date = '';
  $title=$this->_formatText_getICal('3. PLP, '.($this->plp_data['ref_anrede'] ? $this->plp_data['ref_anrede'].' ' : '')
    .$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']);
  $location='';
  $beschreibung  = $this->_formatText_getICal("Daten zur 3. Prüfungslehrprobe:\n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal("Referendar/in:\n");
  $beschreibung .= $this->_formatText_getICal('_  '.($this->plp_data['ref_anrede'] ? $this->plp_data['ref_anrede'].' ' : '').$this->plp_data['ref_vorname'].' '.$this->plp_data['ref_nachname']."\n");
  $beschreibung .= $this->_formatText_getICal('_  '.'PLP im Fach:'.' '.$this->plp_data['plp3_fach']."\n");
  $beschreibung .= $this->_formatText_getICal('_  '.'Fächerkombination: '.$this->plp_data['fach1'].' / '.$this->plp_data['fach2'].' / '.$this->plp_data['fach3']."\n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal("Termine:\n");
  $beschreibung .= $this->_formatText_getICal('_  '.'Eröffnung:'.' '.($this->plp_data['eroeffnung_datum'] ? $this->plp_data['eroeffnung_datum'] : '')."\n");
  $beschreibung .= $this->_formatText_getICal('_  '.'Vorstunde:'.' '.($this->plp_data['vorstunde_datum']  ? $this->plp_data['vorstunde_datum']  : '').($this->plp_data['vorstunde_zeit_von'] ? ', '.$this->plp_data['vorstunde_zeit_von'].' - '.$this->plp_data['vorstunde_zeit_bis'] : ' ')."\n");
  $beschreibung .= $this->_formatText_getICal('_  '.'Prüfung:'  .' '.($this->plp_data['plp3_datum']       ? $this->plp_data['plp3_datum']       : '').($this->plp_data['plp3_zeit_von']      ? ', '.$this->plp_data['plp3_zeit_von']     .' - '.$this->plp_data['plp3_zeit_bis']      : ' ')."\n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal("Daten der Einsatzschule:\n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal('_  '.$this->plp_data['schulenES_Schulname'].($this->plp_data['schulenES_Schulname2'] ? ', '.$this->plp_data['schulenES_Schulname2'] : '')."\n");
  $beschreibung .= $this->_formatText_getICal('_  '.$this->plp_data['schulenES_Strasse']."\n");
  $beschreibung .= $this->_formatText_getICal('_  '.$this->plp_data['schulenES_PLZ'].' '.$this->plp_data['schulenES_Ort']."\n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal('_  '.'Telefonnummer: '.$this->plp_data['schulenES_Telefon']." \n");
  $beschreibung .= $this->_formatText_getICal('_  '.'Geodaten: L: '
    .($this->plp_data['schulen_geodatenES_Laenge'] ? $this->plp_data['schulen_geodatenES_Laenge'] : '-').' B: '
    .($this->plp_data['schulen_geodatenES_Breite'] ? $this->plp_data['schulen_geodatenES_Breite'] : '-')." \n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal('_  '.'im BRN: http://www.realschule.bayern.de/schulen/info/?Schulnr='.$this->plp_data['snr_einsatz']." \n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal("beteiligte Schulen:\n");
  $beschreibung .= $this->_formatText_getICal("\n");
  $beschreibung .= $this->_formatText_getICal('_  '.'grundständige Seminarschule:'.' '.$this->plp_data['schulenGS_Schulname'].($this->plp_data['schulenGS_Schulname2'] ? ', '.$this->plp_data['schulenGS_Schulname2'] : '').' in '.$this->plp_data['schulenGS_Ort']."\n");
  $beschreibung .= $this->_formatText_getICal('_  '.'Einsatzschule:'.' '.$this->plp_data['schulenES_Schulname'].($this->plp_data['schulenES_Schulname2'] ? ', '.$this->plp_data['schulenES_Schulname2'] : '').' in '.$this->plp_data['schulenES_Ort']."\n");
  $beschreibung .= $this->_formatText_getICal('_  '.'prüfende Seminarschule:'.' '.$this->plp_data['schulenPS_Schulname'].($this->plp_data['schulenPS_Schulname2'] ? ', '.$this->plp_data['schulenPS_Schulname2'] : '').' in '.$this->plp_data['schulenPS_Ort']."\n");
  $beschreibung .= $this->_formatText_getICal("\n");

  $attendees = (array) array(
    'unknow' => ',1'
    //'RS-Bayreuth' => 'verwaltunq@r2-bayreuth.de,1',   //GEHT NICHT???
    //'Michi' => 'flaimo@gmx.net,1'
    // 'unknow' => ',1'
  );  // Name => e-mail,role (see iCalEvent class)
  $days = (array) array (2,3);

  if ($schule=='gs' and $this->plp_data['snr_gs']) {
    // Termin Eroeffnung
    if ($typ=='eroeffnung' and $this->plp_data['eroeffnung_datum']) {
      $start_date = strtotime($this->plp_data['eroeffnung_datum'].' 09:00:00');
      $end_date = $start_date;
      $title=$this->_formatText_getICal("Eröffnung ").$title;
      $location=$this->_formatText_getICal($this->plp_data['schulenGS_Ort']);
        $location.=$this->_formatText_getICal(', '.$this->plp_data['schulenGS_Schulname']);
        if ($this->plp_data['schulenGS_Schulname2']) {
          $location.=$this->_formatText_getICal(', '.$this->plp_data['schulenGS_Schulname2']);
        }
    }
  }
  elseif ($schule=='es' and $this->plp_data['snr_einsatz']) {
    // Termin Pruefung
    if ($typ=='pruefung' and $this->plp_data['plp3_datum'] and $this->plp_data['plp3_zeit_von'] and $this->plp_data['plp3_zeit_bis']) {
      $start_date = strtotime($this->plp_data['plp3_datum'].' '.($this->plp_data['plp3_zeit_von']!='00:00:00' ? $this->plp_data['plp3_zeit_von'] : '00:00:01'));
      $end_date   = strtotime($this->plp_data['plp3_datum'].' '.($this->plp_data['plp3_zeit_bis']!='00:00:00' ? $this->plp_data['plp3_zeit_bis'] : '00:00:01'));
      // $title=$this->_formatText_getICal("Termin ").$title;
      $location=$this->_formatText_getICal($this->plp_data['schulenES_Ort']);
        $location.=$this->_formatText_getICal(', '.$this->plp_data['schulenES_Schulname']);
        if ($this->plp_data['schulenES_Schulname2']) {
          $location.=$this->_formatText_getICal(', '.$this->plp_data['schulenES_Schulname2']);
        }
    }
    // Termin Vorstunde
    elseif ($typ=='vorstunde' and $this->plp_data['vorstunde_datum'] and $this->plp_data['vorstunde_zeit_von'] and $this->plp_data['vorstunde_zeit_bis']) {
      $start_date = strtotime($this->plp_data['vorstunde_datum'].' '.($this->plp_data['vorstunde_zeit_von']!='00:00:00' ? $this->plp_data['vorstunde_zeit_von'] : '00:00:01') );
      $end_date   = strtotime($this->plp_data['vorstunde_datum'].' '.($this->plp_data['vorstunde_zeit_bis']!='00:00:00' ? $this->plp_data['vorstunde_zeit_bis'] : '00:00:01'));
      $title=$this->_formatText_getICal("Vorstunde ").$title;
      $location=$this->_formatText_getICal($this->plp_data['schulenES_Ort']);
        $location.=$this->_formatText_getICal(', '.$this->plp_data['schulenES_Schulname']);
        if ($this->plp_data['schulenES_Schulname2']) {
          $location.=$this->_formatText_getICal(', '.$this->plp_data['schulenES_Schulname2']);
        }
    }
  }
  elseif ($schule=='ps' and $this->plp_data['snr_pruef']) {
    // Termin Pruefung
    if ($typ=='pruefung' and $this->plp_data['plp3_datum'] and $this->plp_data['plp3_zeit_von'] and $this->plp_data['plp3_zeit_bis']) {
      $start_date = strtotime($this->plp_data['plp3_datum'].' '.($this->plp_data['plp3_zeit_von']!='00:00:00' ? $this->plp_data['plp3_zeit_von'] : '00:00:01'));
      $end_date   = strtotime($this->plp_data['plp3_datum'].' '.($this->plp_data['plp3_zeit_bis']!='00:00:00' ? $this->plp_data['plp3_zeit_bis'] : '00:00:01'));
      // $title=$this->_formatText_getICal("Termin ").$title;
      $location=$this->_formatText_getICal($this->plp_data['schulenES_Ort']);
        $location.=$this->_formatText_getICal(', '.$this->plp_data['schulenES_Schulname']);
        if ($this->plp_data['schulenES_Schulname2']) {
          $location.=$this->_formatText_getICal(', '.$this->plp_data['schulenES_Schulname2']);
        }
    }
  }
  else {
  }

  $plp3UID='plp3tv'.'-'.$this->plp_data['schuljahr'].'-'.$typ.'-'.$this->plp_data['pkz'].'@realschule.bayern.de'; //???
  $plp3UID=md5($plp3UID);

  $iCal = (object) new iCal('', 1, ''); // (ProgrammID, Method (1 = Publish | 0 = Request), Download Directory)
  $iCal->addEvent(
    $organizer, // Organizer
    $start_date, // Start Time (timestamp; for an allday event the startdate has to start at YYYY-mm-dd 00:00:00)
    $end_date, // End Time (write 'allday' for an allday event instead of a timestamp)
    $location, // Location
    1, // Transparancy (0 = OPAQUE | 1 = TRANSPARENT)
    $categories, // Array with Strings
    $beschreibung, // ."\n\n\nUID: ".$plp3UID, // Description
    $title, // Title
    2, // Class (0 = PRIVATE | 1 = PUBLIC | 2 = CONFIDENTIAL)
    $attendees, // Array (key = attendee name, value = e-mail, second value = role of the attendee [0 = CHAIR | 1 = REQ | 2 = OPT | 3 =NON])
    5, // Priority = 0-9
    0, // frequency: 0 = once, secoundly - yearly = 1-7
    10, // recurrency end: ('' = forever | integer = number of times | timestring = explicit date)
    2, // Interval for frequency (every 2,3,4 weeks...)
    $days, // Array with the number of the days the event accures (example: array(0,1,5) = Sunday, Monday, Friday
    0, // Startday of the Week ( 0 = Sunday - 6 = Saturday)
    '', // exeption dates: Array with timestamps of dates that should not be includes in the recurring event
    0, // kein Arlarm
    //$alarm,  // Sets the time in minutes an alarm appears before the event in the programm. no alarm if empty string or 0
    1, // Status of the event (0 = TENTATIVE, 1 = CONFIRMED, 2 = CANCELLED)
    '', // optional URL for that event
    'de', // Language of the Strings
    $plp3UID //'' // Optional UID for this event
  );

  $iCal->outputFile('ics'); // output file as ics (xcs and rdf possible)
}

private function _formatText_getICal($s){
  // return utf8_encode($s);
  $umlaute = Array(
"/À/",
"/Á/",
"/Â/",
"/Ä/",
"/È/",
"/É/",
"/Ì/",
"/Í/",
"/Î/",
"/Ò/",
"/Ó/",
"/Ô/",
"/Ö/",
"/Ù/",
"/Ú/",
"/Û/",
"/Ü/",
"/Ý/",
"/ß/",
"/à/",
"/á/",
"/â/",
"/ä/",
"/è/",
"/é/",
"/ê/",
"/ì/",
"/í/",
"/î/",
"/ò/",
"/ó/",
"/ô/",
"/ö/",
"/ù/",
"/ú/",
"/ü/",
"/ý/"
	);
  $replace = Array(
"A",  
"A",  
"A",  
"Ae", 
"E",  
"E",  
"I",  
"I",  
"I",  
"O",  
"O",  
"O",  
"Oe", 
"U",  
"U",  
"U",  
"Ue", 
"Y",  
"ss", 
"a",  
"a",  
"a",  
"ae", 
"e",  
"e",  
"e",  
"i",  
"i",  
"i",  
"o",  
"o",  
"o",  
"oe", 
"u",  
"u",  
"ue", 
"y"
	);
  $s_neu = preg_replace($umlaute, $replace, $s);
  return $s_neu;
}


} // END: class plp3_terminvereinbarung

// **************************************************
// * class textblock2
// **************************************************
class textblock2 {
  var $maxwidth=0;
  var $font="";
  var $fontSize=0;
  var $lines=array();
  var $encodeUTF8=false;

function textblock2($tb_maxwidth, $tb_font, $bt_fontSize, $bf_encodeUTF8) {
  $this->maxwidth=$tb_maxwidth;
  $this->font=$tb_font;
  $this->fontSize=$bt_fontSize;
  $this->encodeUTF8=$bf_encodeUTF8;
  $this->lines[0]="";
}

function addWord($word2) {
  $word = $this->encodeUTF8 ? utf8_encode($word2) : $word2;
  $i=count($this->lines)-1;
  if ( $this->_fontStringWidth($this->lines[$i].$word, $this->font, $this->fontSize) > $this->maxwidth ) {
    $this->lines[$i+1] = $word;
  }
  else {
    $this->lines[$i].=$word;
  }
}

function addText($text) {
  $words=split( " ", $text );
  for ($i=0; $i<count($words); $i++) {
    if ($words[$i]) { $this->addWord($words[$i]." "); }
  }
}

function getLineCount() {
  return count($this->lines);
}

function getLine($i) {
  return $this->lines[$i];
}

function _fontStringWidth($string, $font, $fontSize){
  // #if (strpos($string,utf8_encode('?'))!==false) { echo $string; die(); }
//   $pattern_s = array(utf8_encode('ö'),utf8_encode('ü'),utf8_encode('ä'),
//              utf8_encode('Ö'),utf8_encode('Ü'),utf8_encode('Ä'),
//              utf8_encode('ß'));
//   $replace_s = array(utf8_encode('o'),utf8_encode('u'),utf8_encode('a'),
//              utf8_encode('O'),utf8_encode('U'),utf8_encode('A'),
//              utf8_encode('S'));
  $pattern_s = array(('ö'),('ü'),('ä'),
             ('Ö'),('Ü'),('Ä'),
             ('ß'));
  $replace_s = array(('o'),('u'),('a'),
             ('O'),('U'),('A'),
             ('S'));
  $string = str_replace($pattern_s,$replace_s,$string);
  $string = preg_replace('/[^a-zA-Z0-9 .,\-\+]/', 'W', $string);
  // # Inoffizielle Funktion aus dem Zend-WiKi
  // #$drawingString = iconv('', 'UTF-16BE', $string);
  $drawingString = iconv('', 'UTF-16BE', $string);
  $characters = array();
  for ($i = 0; $i < strlen($drawingString); $i++) {
    $characters[] = (ord($drawingString[$i++]) << 8) | ord($drawingString[$i]);
  }
  $glyphs = $font->glyphNumbersForCharacters($characters);
  $widths = $font->widthsForGlyphs($glyphs);
  $stringWidth = (array_sum($widths) / $font->getUnitsPerEm()) * $fontSize;
  return $stringWidth;
}


} // ende class textblock2






// *************************
// *************************

// *************************
// *************************
// * class plp3_table_admin
// *************************
class plp3_table_admin {

var $schuljahr=0;

function plp3_table_admin($schuljahr) { $this->schuljahr=$schuljahr; }

function backupTable() {
  global $db;
  $zeit=date("Y_m_d__H_i_s");
  $query='CREATE TABLE plp_tv_main_'.$zeit.' SELECT * FROM plp_tv_main';

  $rs = $db->Execute($query);

}

function clearTable() {
  global $db;

  $query='TRUNCATE TABLE plp_tv_main';

  $rs = $db->Execute($query);
}

function importTable( $options=array() ) {
  global $db;
  $import_errors=array();
  $pseudo=false; if ( isset($options['pseudo']) ) { $pseudo=$options['pseudo']; };
  $semfaecher=$this->getSeminarfaecher(true);

  $query= "
    SELECT * FROM plp_tv_import
  ";

  $rs = $db->Execute($query);
  $count_import=0;
  while (!$rs->EOF) {
    $rs->fields['idplptvmain']=md5(rand(0,1000).$rs->fields['pkz'].$rs->fields['nachname'].$rs->fields['vorname'].date("YmdHis"));

  	// Anrede
  	if ($rs->fields['ref_anrede']!='M' and $rs->fields['ref_anrede']!='W') { $import_errors[ $rs->fields['idplptvmain'] ]['ref_anrede']='Geschlecht fehlt, also Stud.-Ref./in'; }
    $rs->fields['ref_anrede']=( ($rs->fields['ref_anrede']=='W') ? 'Stud.-Refin.' : ( ($rs->fields['ref_anrede']=='M') ? 'Stud.-Ref.' :  'Stud.-Ref./in') );

	// GS
    $rs->fields['snr_gs']=$this->_vierstelligeSchulnummer($rs->fields['snr_gs']);
  	if ($rs->fields['snr_gs']=='0000') { $import_errors[ $rs->fields['idplptvmain'] ]['snr_gs']='Grundst&auml;ndige Seminarschule fehlt.'; }
	elseif ( !$this->_existiert_Schule_mit_Schulnummer($rs->fields['snr_gs']) ) { $import_errors[ $rs->fields['idplptvmain'] ]['snr_gs']='Grundst&auml;ndige Seminarschule: Die Schulnummer '.$rs->fields['snr_gs'].' existiert nicht.'; }
	
	// ES
    $rs->fields['snr_einsatz']=$this->_vierstelligeSchulnummer($rs->fields['snr_einsatz']);
  	if ($rs->fields['snr_einsatz']=='0000') { $import_errors[ $rs->fields['idplptvmain'] ]['snr_einsatz']='Einsatzschule fehlt.'; }
	elseif ( !$this->_existiert_Schule_mit_Schulnummer($rs->fields['snr_einsatz']) ) { $import_errors[ $rs->fields['idplptvmain'] ]['snr_einsatz']='Einsatzschule: Die Schulnummer '.$rs->fields['snr_gs'].' existiert nicht.'; }

	// PS
    $rs->fields['snr_pruef']=$this->_vierstelligeSchulnummer($rs->fields['snr_pruef']);
  	if ($rs->fields['snr_pruef']=='0000') { $import_errors[ $rs->fields['idplptvmain'] ]['snr_pruef']='Pr&uuml;fende Seminarschule fehlt.'; }
	elseif ( !$this->_existiert_Schule_mit_Schulnummer($rs->fields['snr_pruef']) ) { $import_errors[ $rs->fields['idplptvmain'] ]['snr_pruef']='Pr&uuml;fende Seminarschule: Die Schulnummer '.$rs->fields['snr_gs'].' existiert nicht.'; }

	// PKZ
  	if (!$rs->fields['pkz'] ) { $import_errors[ $rs->fields['idplptvmain'] ]['pkz']='Die PKZ-Nummer fehlt.'; }

	// Nachname
  	if (!$rs->fields['ref_nachname'] ) { $import_errors[ $rs->fields['idplptvmain'] ]['ref_nachname']='Der Nachname fehlt.'; }
	
	// Vorname
  	if (!$rs->fields['ref_vorname'] ) { $import_errors[ $rs->fields['idplptvmain'] ]['ref_vorname']='Der Vorname fehlt.'; }
	
	// fach1
  	if (!$rs->fields['fach1'] or $rs->fields['fach1']=='' or $rs->fields['fach1']=='-' ) { $import_errors[ $rs->fields['idplptvmain'] ]['fach1']='Das 1. Fach fehlt.'; }
	
	// fach2
  	if (!$rs->fields['fach2'] or $rs->fields['fach2']=='' or $rs->fields['fach2']=='-' ) { $import_errors[ $rs->fields['idplptvmain'] ]['fach2']='Das 2. Fach fehlt.'; }
	
	// plp_fach
  	if (!$rs->fields['plp3_fach'] or $rs->fields['plp3_fach']=='' or $rs->fields['plp3_fach']=='-' ) { $import_errors[ $rs->fields['idplptvmain'] ]['plp3_fach']='Das PLP-Fach fehlt.'; }
	else {
	  	if ($rs->fields['plp3_fach'] != $rs->fields['fach1'] and $rs->fields['plp3_fach'] != $rs->fields['fach2'] and $rs->fields['plp3_fach'] != $rs->fields['fach3']) { 
			if ( $semfaecher[ $rs->fields['plp3_fach'] ]['fach_alternativ'] != $rs->fields['fach1'] and $semfaecher[ $rs->fields['plp3_fach'] ]['fach_alternativ'] != $rs->fields['fach2'] and $semfaecher[ $rs->fields['plp3_fach'] ]['fach_alternativ'] != $rs->fields['fach3']) { 
				$import_errors[ $rs->fields['idplptvmain'] ]['plp3_fach']='Das PLP-Fach stimmt nicht mit den angegebenen F&auml;chern &uuml;berein: ';
				$import_errors[ $rs->fields['idplptvmain'] ]['plp3_fach'].=$rs->fields['plp3_fach']." &lt;=&gt; ".$rs->fields['fach1'].", ".$rs->fields['fach2'].", ".$rs->fields['fach3'];
			}	
		}	
	}
	if ( isset($import_errors[ $rs->fields['idplptvmain'] ]) ) {
		$import_errors[ $rs->fields['idplptvmain'] ]['data']=$rs->fields;
	}

	$rs->fields['schuljahr']=$this->schuljahr;
    if (!$pseudo) {
    	$insertSQL = $db->AutoExecute("plp_tv_main", $rs->fields, 'INSERT');
	}

    $count_import++;
    $rs->MoveNext();
  }
  
  return array (
	'pseudo'        =>  $pseudo,
  	'import_count'  =>  $count_import,
  	'error_count'   =>  count($import_errors),
  	'error_data'    =>  $import_errors
  );
}

private function getSeminarfaecher() {
  global $db;
  $result=array();
  $fach1='';

  if (!$all) {
    $fach1=$this->plp_data['fach1'];
    $fach2=$this->plp_data['fach2'];
    $fach3=$this->plp_data['fach3'];
  }

  $query= "SELECT * FROM plp_tv_sem_faecher";
  $order= " ORDER BY plp_tv_sem_faecher.bezeichnung ASC";

  $rs = $db->Execute($query.$order);

  while (!$rs->EOF) {
    $result[$rs->fields['fach']] = $rs->fields;
    $rs->MoveNext();
  }

  return $result;
}


private function _vierstelligeSchulnummer($snr){
  $str_lenth=strlen($snr);
  if ($str_lenth>4) {
    return substr($snr,0,4);
  }
  else { // ($str_lenth<4)
    return (str_pad($snr, 4, "0", STR_PAD_LEFT));
  }
}

private function _existiert_Schule_mit_Schulnummer($snr){
	global $db;

	if     ( $snr=='9999' )     { return false; }
	elseif ( strlen($snr)!=4 ) { return false; }
	
    $query= "
    	SELECT * 
    	FROM schulen
    	WHERE ( Schulnr = '$snr' )
      ";

    $rs = $db->Execute($query);

	if (!$rs->EOF) { return true; }
	else { return false; }
}	

} // END: class plp3_table_admin



?>
