﻿<?php

class control
  {
    private $errorCount = 0;                 /* number of error messages sent */
    private $index = 0;                       /* line index from control file */
    private $matches = array ();                    /* info from control file */

/*----------------------------------------------------------------------------*/

    public function __construct ($zone, $ctlPath)
      {
        date_default_timezone_set ($zone);  /* prepare log file time stamping */

        if (! file_exists ($ctlPath))
          $this->error ("Control file missing '$ctlPath'", 1);

        $ctl = file_get_contents ($ctlPath);       /* ctl file coded in UTF-8 */

        preg_match_all ("/\[([0-9a-zA-Z]{3,10})\](.+)\r/u", $ctl, $this->matches, PREG_SET_ORDER);
      }

    public function __destruct ()
      {
        if (file_exists ("temp.pdf")) unlink ("temp.pdf");
        if (file_exists ("result.pdf")) unlink ("result.pdf");
        if (file_exists ("embedding.ps")) unlink ("embedding.ps");
      }

/*----------------------------------------------------------------------------*/

    public function error ($msg, $severity = 0)
      {
        file_put_contents ("control.log",
                           "[" . date ('Y-m-d H:i:s', time ()) . "] " .
                           $msg . "\n", FILE_APPEND);
        if ($severity != 0)
          die ();

        $this->errorCount++;
      }

/*----------------------------------------------------------------------------*/

    public function errorsFound ()
      {
        return $this->errorCount;
      }

/*----------------------------------------------------------------------------*/

    public function getIndex ()
      {
        return $this->matches [$this->index] [1];
      }

/*----------------------------------------------------------------------------*/

    public function setIndex ($lineIndex)
      {
        for ($idx = 0; $idx < count ($this->matches); $idx++)
          if ($this->matches [$idx] [1] == $lineIndex)
            break;

        if ($idx == count ($this->matches))
          return "";

        $this->index = $idx;
        return trim ($this->matches [$idx] [2]);
      }

/*----------------------------------------------------------------------------*/

    public function getLine ($lineIndex)
      {
        $line = "";

        do
          {
            for ($idx = 0; $idx < count ($this->matches); $idx++)
              if ($this->matches [$idx] [1] == $lineIndex)
                break;

            if ($idx == count ($this->matches))
              return "";

            $lineIndex = $this->matches [$idx + 1] [1];
            $lineidx = substr ($this->matches [$idx] [1], 0, 6);
            $line .= $this->matches [$idx] [2];
          }
        while (substr ($lineIndex, 0, 6) == $lineidx);

        return $line;
      }

/*----------------------------------------------------------------------------*/

    public function fetch ($lineIndex, & $target, $regEx, $idx)
      {
        $line = ($lineIndex == "")
                   ? $this->matches [$this->index++] [2]      /* current line */
                   : $this->setIndex ($lineIndex);          /* requested line */

        if (preg_match ("/" . $regEx . "/u", $line, $m) == 1)
          $target [$idx] = $m [1];
        else
          $target [$idx] = "";
      }

/*----------------------------------------------------------------------------*/

    public function substitute ($tmpl, $vars)
      {
        /* Replace placeholders in template */

        foreach ($vars as $key => $value)
          $tmpl = str_replace( "@$key@" , $value , $tmpl);

        return $tmpl;
      }

/*----------------------------------------------------------------------------*/

    public function createPdf ($pcl, $company, $reference, $keywords)
      {
        if (! file_exists ($pcl))
          {
            $this->error ("PCL file missing '$pcl'", 0);
            return "";
          }

        /* Convert PCL file to PDF/A format using GhostPCL first */

        system ("\"converter/gpcl6win64.exe\" \"-otemp.pdf\" " .
                "-sPDFCompatibillityPolicy=2 -sDEVICE=pdfwrite -dPDFA=1 " .
                "-dCompressPages=false -dCompressFonts=false \"$pcl\"", $result);

        if ($result != 0)
          {
            $this->error ("Conversion to pdf failed for '$pcl'", 0);
            return "";
          }

        /* Write postscript file to setup meta data for pdf file creation */

        file_put_contents ("embedding.ps",
                           "%!PS\n" .
                           "[ /Title ($company - $reference)\n" .
                           "  /Author ($company)\n" .
                           "  /Subject (Rechnung im PDF-Format)\n " .
                           "  /Keywords ($keywords)\n" .
                           "  /Creator (print2forms)\n" .
                           "  /DOCINFO\n" .
                           "pdfmark\n" .
                           "%%EOF");

        /* Convert PDF/A once again to integrate meta data using GhostScript.
           This is neccessary because newer versions of gpcl6win64.exe fail
           in processing a PJL command with meta data.
        */

        $internal = "result.pdf";      /* dafault name for resulting document */

        system ("\"converter/gswin64.exe\" " .
                "-sDEVICE=pdfwrite " .
                "-dPDFA=1 " .
                "-o $internal " .
                "temp.pdf " .
                "embedding.ps", $result);

        if ($result != 0)
          {
            $this->error ("Appending meta data to pdf failed for '$pcl'", 0);
            return "";
          }

        return $internal;          /* internal name of the pdf file as result */
      }
  }
?>