Support PDF export of past orders as well
[misc/hallinta-metro] / utils.php
index 1829a8d..1784acc 100644 (file)
--- a/utils.php
+++ b/utils.php
@@ -5,6 +5,18 @@ define('TEMPLATE', 'ordersatz.tex');
 define('FNAME_VARS', 'ordersatz_vars.tex');
 define('FNAME_ITEMS', 'ordersatz_items.tex');
 define('FAXNUMBER','2002-364');
+define('ERROR_SAFT','joey@finlandia');
+define('ERROR_MAIL','joey@finlandia.infodrom.org');
+
+function is_done($id)
+{
+  global $db;
+
+  $query = sprintf('SELECT count(*) AS count FROM metro_ordersatz WHERE id = %d AND done IS NULL', $id);
+  $sth = $db->query($query);
+  $row = $sth->fetch();
+  return $row['count'] == 0;
+}
 
 function mk_tempdir()
 {
@@ -14,7 +26,6 @@ function mk_tempdir()
                    md5(date('c')));
   mkdir($tmpdir,0777);
 
-  error_log($tmpdir);
   return $tmpdir;
 }
 
@@ -23,11 +34,98 @@ function rm_tempdir($dir)
   system(sprintf("rm -rf %s", $dir));
 }
 
+function latexspecialchars($string)
+{
+  return preg_replace_callback("/([\^\%~\\\\#\$%&_\{\}])/",
+                              function($matches) {
+                                $map = array(
+                                             "#"=>"\\#",
+                                             "$"=>"\\$",
+                                             "%"=>"\\%",
+                                             "&"=>"\\&",
+                                             "~"=>"\\~{}",
+                                             "_"=>"\\_",
+                                             "^"=>"\\^{}",
+                                             "\\"=>"\\textbackslash",
+                                             "{"=>"\\{",
+                                             "}"=>"\\}",
+                                             );
+                                return $map[$matches[0]];
+                              },
+                              $string);
+}
+
 function latex_encode($text)
 {
-  return str_replace(array("\\",'%'),
-                    array('\\','\%'),
-                    utf8_decode($text));
+  return latexspecialchars(utf8_decode($text));
+}
+
+function ordersatz_archive($id, $title, $filename)
+{
+  global $db;
+
+  $parts = pathinfo($filename);
+
+  $base = $_SESSION['sys']['basedir'] . 'archive/' . MODULE;
+
+  if (!is_dir($base))
+    return 'Basis-Verzeichnis nicht vorhanden';
+
+  $base .= '/';
+
+  $path = date('Y');
+  if (!is_dir($base.$path))
+    if (mkdir($base.$path) === false)
+      return 'Kann Verzeichnis nicht anlegen: ' . $path;
+
+  $path .= '/' . date('m');
+  if (!is_dir($base.$path))
+    if (mkdir($base.$path) === false)
+      return 'Kann Verzeichnis nicht anlegen: ' . $path;
+
+
+  $parts['filename'] = utf8_encode($parts['filename']);
+  $path .= '/' . $parts['filename'];
+
+  $max = 100;
+  for ($i=0; $i < $max; $i++) {
+    $fname = $path;
+    if ($i > 0) $fname .= '('.$i.')';
+    if (!empty($parts['extension']))
+      $fname .= '.' . $parts['extension'];
+
+    if (!is_file($base.$fname)) {
+      if (copy($filename, $base.$fname) === false)
+       return 'Kann Datei nicht speichern';
+
+      chmod($base.$fname, 0640);
+      break;
+    }
+  }
+
+  $sql = sprintf("INSERT INTO metro_files (ordersatz,date,title,path,sys_user,sys_edit) " .
+                "VALUES (%d,now(),%s,%s,%s,now())",
+                $id,
+                $db->quote($title),
+                $db->quote($fname),
+                $db->quote($_SESSION['sys']['login']));
+  $sth = $db->query($sql);
+
+  return true;
+}
+
+function ordersatz_finish($id)
+{
+  global $db;
+
+  $sql = sprintf("DELETE FROM metro_ordersatz_pos WHERE ordersatz = %d AND anzahl IS NULL",
+                $id);
+  $sth = $db->query($sql);
+
+  $sql = sprintf("UPDATE metro_ordersatz SET done = now(), sys_edit = now(), sys_user = %s WHERE id = %d",
+                $db->quote($_SESSION['sys']['login']),
+                $id);
+  $sth = $db->query($sql);
 }
 
 function ordersatz_write($id, $dir, $send)
@@ -45,7 +143,7 @@ function ordersatz_write($id, $dir, $send)
   copy($fname, $dir . '/ordersatz.tex');
   chdir($dir);
 
-  $sql = sprintf("SELECT name,koch,email,telefon,datum,uhrzeit FROM metro_ordersatz WHERE id = %d",
+  $sql = sprintf("SELECT name,koch,email,telefon,datum,uhrzeit,owner FROM metro_ordersatz WHERE id = %d",
                 $id);
   $satz = query_db($sql);
 
@@ -59,65 +157,87 @@ function ordersatz_write($id, $dir, $send)
   fwrite($f, sprintf('\newcommand{\datum}{%d.%d.%d}'."\n", $d[2], $d[1], $d[0]));
   fclose($f);
 
-  $sql = sprintf("SELECT artnr,gang,metro_vpe.short AS vpname,menge,bezeichnung,hersteller,anzahl " .
+  $sql = sprintf("SELECT artnr,gang,metro_vpe.short AS vpname,menge,bezeichnung,hinweis,hersteller,anzahl " .
                 "FROM metro_ordersatz_pos " .
                 "JOIN metro_artikel ON artikel = metro_artikel.id " .
                 "JOIN metro_abteilung ON abteilung = metro_abteilung.id " .
                 "JOIN metro_vpe ON vpe = metro_vpe.id " .
                 "WHERE ordersatz = %d AND anzahl IS NOT NULL " .
-                "ORDER BY gang,metro_abteilung.name",
+                "ORDER BY sort,gang,metro_abteilung.name,bezeichnung",
                 $id);
 
-#  error_log($sql);
   $result = query_db($sql);
 
+  if (count($result) == 0)
+    return "Keine Artikel zur Bestellung ausgewählt";
+
   $f = fopen(FNAME_ITEMS, 'w');
 
   foreach ($result as $row) {
-    $bez = $row['bezeichnung'];
+    $bez = latex_encode($row['bezeichnung']);
     if (strlen($row['hersteller']))
-      $bez .= ' (' . $row['hersteller'] . ')';
+      $bez .= ' (' . latex_encode($row['hersteller']) . ')';
+    if (strlen($row['hinweis']))
+      $bez .= sprintf("\\newline\\textbf{%s}", latex_encode($row['hinweis']));
 
-    fwrite($f, sprintf('\order{%d}{%d}{%s %s}{%s}'."\n",
+    fwrite($f, sprintf('\order{%d}{%s}{%s %s}{%s}{%s}'."\n",
                       $row['anzahl'],
-                      $row['artnr'],
-                      $row['menge'],
-                      latex_encode($bez),
-                      latex_encode($row['vpname'])));
+                      $row['artnr'] ? (int)$row['artnr'] : '',
+                      latex_encode($row['menge']),
+                      $bez,
+                      latex_encode($row['vpname']),
+                      latex_encode($row['gang'])));
   }
 
   fclose($f);
 
-  system("latex ordersatz > ordersatz.out 2>&1 && dvips ordersatz >> ordersatz.out 2>&1 && ps2pdf ordersatz.ps", $ret);
-
-  if ($ret !== 0)
+  system("latex ordersatz > ordersatz.out 2>&1 && dvips ordersatz >> ordersatz.out 2>&1 && pdflatex ordersatz >> ordersatz.out", $ret);
+
+  if ($ret !== 0) {
+    $fname = sprintf("ordersatz-%d-%d.tar.bz2", $id, time());
+    $cmd = sprintf("tar cfj %s ordersatz.tex ordersatz_vars.tex ordersatz_items.tex ordersatz.out && " .
+                  "mpack -s 'Probleme beim Compilieren des Ordersatzes %d' -d ordersatz.out %s %s && " .
+                  "sendfile -Q -c='Probleme beim Compilieren des Ordersatzes %d' %s %s",
+                  $fname,
+                  $id, $fname, ERROR_MAIL,
+                  $id, $fname, ERROR_SAFT);
+    system($cmd);
     return "Probleme beim Compilieren des Ordersatzes";
+  }
 
   if (!file_exists('ordersatz.ps'))
     return "Postscript-Datei nicht erstellt";
 
   if ($send) {
-    $cmd = sprintf("faxspool -f joey@finlandia.infodrom.org %s %s > /dev/null 2>&1",
-                  FAXNUMBER,
-                  ordersatz.ps);
-    error_log($cmd);
-    # system($cmd);
+    $ret = ordersatz_archive($id, 'Ordersatz '.$satz[0]['name'], $dir . '/ordersatz.pdf');
 
-#      $fname = store_file($field, $info);
+    if ($ret !== true)
+      return $ret;
 
+    if (empty($satz[0]['email']))
+      $satz[0]['email'] = 'joey@infodrom.org';
 
-    $message = sprintf("Hallo %s!\n\nDer angehänge Ordersatz wurde gerade an Metro Oldenburg verschickt.\n\n",
-                      $satz[0]['koch']);
+    $cmd = sprintf("faxspool -f %s %s %s > /dev/null 2>&1",
+                  $satz[0]['email'],
+                  FAXNUMBER,
+                  'ordersatz.ps');
+    system($cmd);
+
+    $message = sprintf("Hallo %s!\n\nDer angehängte Ordersatz wurde gerade an Metro Oldenburg verschickt.\n" .
+                      "Eine Bestätigung über den Versand kommt per Mail.\n\n",
+                      utf8_decode($satz[0]['koch']));
 
     mail_attach($satz[0]['email'],
-               'Ordersatz ' . $satz[0]['name'],
+               mb_encode_mimeheader('Ordersatz ' . $satz[0]['name'],'latin1'),
                $satz[0]['email'],
-               'Infodrom ' . $satz[0]['koch'],
+               mb_encode_mimeheader('Infodrom ' . $satz[0]['koch'],'latin1'),
                array($dir . '/ordersatz.pdf'),
                $message);
+
+    ordersatz_finish($id);
   }
 
   return true;
 }
 
-?>
\ No newline at end of file
+?>