File: exporthelper.cpp

package info (click to toggle)
postbooks 4.10.0-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 112,660 kB
  • ctags: 22,890
  • sloc: cpp: 310,358; sh: 607; xml: 214; python: 140; awk: 104; makefile: 50
file content (906 lines) | stat: -rw-r--r-- 31,043 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
/*
 * This file is part of the xTuple ERP: PostBooks Edition, a free and
 * open source Enterprise Resource Planning software suite,
 * Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
 * It is licensed to you under the Common Public Attribution License
 * version 1.0, the full text of which (including xTuple-specific Exhibits)
 * is available at www.xtuple.com/CPAL.  By using this software, you agree
 * to be bound by its terms.
 */

#include "exporthelper.h"

#include <QDir>
#include <QDomDocument>
#include <QFileInfo>
#include <QMessageBox>
#include <QProcess>
#include <QScriptEngine>
#include <QScriptValue>
#include <QSqlError>
#include <QSqlRecord>
#include <QTemporaryFile>
#include <QTextCursor>
#include <QTextDocument>

#include "metasql.h"
#include "mqlutil.h"
#include "xsqlquery.h"

#define DEBUG false

bool ExportHelper::exportHTML(const int qryheadid, ParameterList &params, QString &filename, QString &errmsg)
{
  if (DEBUG)
    qDebug("ExportHelper::exportHTML(%d, %d params, %s, errmsg) entered",
           qryheadid, params.size(), qPrintable(filename));
  bool returnVal = false;

  XSqlQuery setq;
  setq.prepare("SELECT * FROM qryhead WHERE qryhead_id=:id;");
  setq.bindValue(":id", qryheadid);
  setq.exec();
  if (setq.first())
  {
    if (filename.isEmpty())
    {
      QFileInfo fileinfo(setq.value("qryhead_name").toString());
      filename = fileinfo.absoluteFilePath();
    }

    QFile *exportfile = new QFile(filename);
    if (! exportfile->open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text))
      errmsg = tr("Could not open %1: %2.")
                                      .arg(filename, exportfile->errorString());
    else
    {
      if (exportfile->write(generateHTML(qryheadid, params, errmsg).toUtf8()) < 0)
        errmsg = tr("Error writing to %1: %2")
                                      .arg(filename, exportfile->errorString());
      exportfile->close();
    }
  }
  else if (setq.lastError().type() != QSqlError::NoError)
    errmsg = setq.lastError().text();
  else
    errmsg = tr("<p>Cannot export data because the query set with "
                "id %1 was not found.").arg(qryheadid);

  if (DEBUG)
    qDebug("ExportHelper::exportHTML returning %d, filename %s, and errmsg %s",
           returnVal, qPrintable(filename), qPrintable(errmsg));

  return returnVal;
}

/** \brief Export the results of a query set to an XML file.

  Run all of the queries in the given Query Set in the given order and write
  the results to an XML file. The XML file is constructed very simply:
  \verbatim
  <tablename>
    <column1name>columnvalue</column1name>
    <column2name>columnvalue</column2name>
    ...
  </tablename>
  \endverbatim

  If the caller passes in an XSLT map id, the simple XML will be processed
  using the export XSLT.

  \param qryheadid   The internal ID of the query set (qryhead record) to run.
  \param params      A list of parameters and values to use when building SQL
                     statements from MetaSQL statements.
  \param[in,out] filename The name of the file to create. If passed in empty,
                          a file named after the query set will be created
                          in the current directory (context-dependent) and
                          this filename will be passed back out.
  \param[out]    errmsg An message describing why the processing failed if there
                        was a problem.
  \param xsltmapid   An optional parameter. If this is set, it should be
                     the internal ID of an xsltmap record. The xsltmap_export
                     field of this record and the XSLTDefaultDir will be used
                     to find the XSLT script to run on the generated XML.
  */
bool ExportHelper::exportXML(const int qryheadid, ParameterList &params, QString &filename, QString &errmsg, const int xsltmapid)
{
  if (DEBUG)
    qDebug("ExportHelper::exportXML(%d, %d params, %s, errmsg, %d) entered",
           qryheadid, params.size(), qPrintable(filename), xsltmapid);
  bool returnVal = false;

  XSqlQuery setq;
  setq.prepare("SELECT * FROM qryhead WHERE qryhead_id=:id;");
  setq.bindValue(":id", qryheadid);
  setq.exec();
  if (setq.first())
  {
    if (filename.isEmpty())
    {
      QFileInfo fileinfo(setq.value("qryhead_name").toString());
      filename = fileinfo.absoluteFilePath();
    }

    QFile exportfile(filename);
    if (! exportfile.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text))
      errmsg = tr("Could not open %1 (%2).").arg(filename,exportfile.error());
    else
    {
      exportfile.write(generateXML(qryheadid, params, errmsg, xsltmapid).toUtf8());
      exportfile.close();
    }
  }
  else if (setq.lastError().type() != QSqlError::NoError)
    errmsg = setq.lastError().text();
  else
    errmsg = tr("<p>Cannot export data because the query set with "
                "id %1 was not found.").arg(qryheadid);

  if (DEBUG)
    qDebug("ExportHelper::exportXML returning %d, filename %s, and errmsg %s",
           returnVal, qPrintable(filename), qPrintable(errmsg));

  returnVal = errmsg.isEmpty();
  return returnVal;
}

QString ExportHelper::generateDelimited(const int qryheadid, ParameterList &params, QString &errmsg)
{
  if (DEBUG)
    qDebug("ExportHelper::exportDelimited(%d, %d params, errmsgd) entered",
           qryheadid, params.size());

  QStringList result;

  XSqlQuery itemq;
  itemq.prepare("SELECT *"
                "  FROM qryitem"
                " WHERE qryitem_qryhead_id=:id"
                " ORDER BY qryitem_order;");
  itemq.bindValue(":id", qryheadid);
  itemq.exec();
  while (itemq.next())
  {
    QString qtext;
    if (itemq.value("qryitem_src").toString() == "REL")
    {
      QString schemaName = itemq.value("qryitem_group").toString();
      qtext = "SELECT * FROM " +
              (schemaName.isEmpty() ? QString("") : schemaName + QString(".")) +
              itemq.value("qryitem_detail").toString();
    }
    else if (itemq.value("qryitem_src").toString() == "MQL")
    {
      QString tmpmsg;
      bool valid;
      qtext = MQLUtil::mqlLoad(itemq.value("qryitem_group").toString(),
                               itemq.value("qryitem_detail").toString(),
                               tmpmsg, &valid);
      if (! valid)
        errmsg = tmpmsg;
    }
    else if (itemq.value("qryitem_src").toString() == "CUSTOM")
      qtext = itemq.value("qryitem_detail").toString();

    if (! qtext.isEmpty())
    {
      QString oneresult = generateDelimited(qtext, params, errmsg);
      if (! oneresult.isEmpty())
        result.append(oneresult);
    }
  }
  if (itemq.lastError().type() != QSqlError::NoError)
    errmsg = itemq.lastError().text();

  return result.join("\n");
}

QString ExportHelper::generateDelimited(QString qtext, ParameterList &params, QString &errmsg)
{
  if (DEBUG)
    qDebug("ExportHelper::generateDelimited(%s..., %d params, errmsg) entered",
           qPrintable(qtext.left(80)), params.size());
  if (qtext.isEmpty())
    return QString::null;

  if (DEBUG)
  {
    QStringList plist;
    for (int i = 0; i < params.size(); i++)
      plist.append("\t" + params.name(i) + ":\t" + params.value(i).toString());
    qDebug("generateDelimited parameters:\n%s", qPrintable(plist.join("\n")));
  }

  bool valid;
  QString delim = params.value("delim", &valid).toString();
  if (! valid)
    delim = ",";
  if (DEBUG)
    qDebug("generateDelimited(qtest, params, errmsg) delim = %s, valid = %d",
           qPrintable(delim), valid);

  QVariant includeheaderVar = params.value("includeHeaderLine", &valid);
  bool includeheader = (valid ? includeheaderVar.toBool() : false);
  if (DEBUG)
    qDebug("generateDelimited(qtest, params, errmsg) includeheader = %d, valid = %d",
           includeheader, valid);

  QStringList line;
  MetaSQLQuery mql(qtext);
  XSqlQuery qry = mql.toQuery(params);
  if (qry.first())
  {
    QStringList field;
    int cols = qry.record().count();
    if (includeheader)
    {
      for (int p = 0; p < cols; p++)
        field.append(qry.record().fieldName(p));
      line.append(field.join(delim));
    }

    QString tmp;
    do {
      field.clear();
      for (int p = 0; p < cols; p++)
      {
        tmp = qry.value(p).toString();
        if (tmp.contains(delim))
        {
          tmp.replace("\"", "\"\"");
          tmp = "\"" + tmp + "\"";
        }
        field.append(tmp);
      }
      line.append(field.join(delim));
    } while (qry.next());
  }
  if (qry.lastError().type() != QSqlError::NoError)
    errmsg = qry.lastError().text();

  return line.join("\n");
}

QString ExportHelper::generateHTML(const int qryheadid, ParameterList &params, QString &errmsg)
{
  if (DEBUG)
    qDebug("ExportHelper::generateHTML(%d, %d params, errmsg) entered",
           qryheadid, params.size());
  QTextDocument doc(0);
  QTextCursor   cursor(&doc);

  XSqlQuery itemq;
  itemq.prepare("SELECT * FROM qryitem WHERE qryitem_qryhead_id=:id ORDER BY qryitem_order;");
  itemq.bindValue(":id", qryheadid);
  itemq.exec();
  while (itemq.next())
  {
    QString qtext;
    if (itemq.value("qryitem_src").toString() == "REL")
    {
      QString schemaName = itemq.value("qryitem_group").toString();
      qtext = "SELECT * FROM " +
              (schemaName.isEmpty() ? QString("") : schemaName + QString(".")) +
              itemq.value("qryitem_detail").toString();
    }
    else if (itemq.value("qryitem_src").toString() == "MQL")
    {
      QString tmpmsg;
      bool valid;
      qtext = MQLUtil::mqlLoad(itemq.value("qryitem_group").toString(),
                               itemq.value("qryitem_detail").toString(),
                               tmpmsg, &valid);
      if (! valid)
        errmsg = tmpmsg;
    }
    else if (itemq.value("qryitem_src").toString() == "CUSTOM")
      qtext = itemq.value("qryitem_detail").toString();

    if (! qtext.isEmpty())
      cursor.insertHtml(generateHTML(qtext, params, errmsg));
  }
  if (itemq.lastError().type() != QSqlError::NoError)
    errmsg = itemq.lastError().text();

  return doc.toHtml();
}

QString ExportHelper::generateHTML(QString qtext, ParameterList &params, QString &errmsg)
{
  if (DEBUG)
    qDebug("ExportHelper::generateHTML(%s..., %d params, errmsg) entered",
           qPrintable(qtext.left(80)), params.size());
  if (qtext.isEmpty())
    return QString::null;

  QTextDocument    doc(0);
  QTextCursor      cursor(&doc);
  QTextTableFormat tablefmt;

  bool valid;
  QVariant includeheaderVar = params.value("includeHeaderLine", &valid);
  bool includeheader = (valid ? includeheaderVar.toBool() : false);
  if (DEBUG)
    qDebug("generateHTML(qtest, params, errmsg) includeheader = %d, valid = %d",
           includeheader, valid);

  MetaSQLQuery mql(qtext);
  XSqlQuery qry = mql.toQuery(params);
  if (qry.first())
  {
    int cols = qry.record().count();
    int expected = qry.size();
    if (includeheader)
      expected++;

    // presize the table
    cursor.insertTable((expected < 0 ? 1 : expected), cols, tablefmt);
    if (includeheader)
    {
      tablefmt.setHeaderRowCount(1);
      for (int p = 0; p < cols; p++)
      {
        cursor.insertText(qry.record().fieldName(p));
        cursor.movePosition(QTextCursor::NextCell);
      }
    }

    do {
      for (int i = 0; i < cols; i++)
      {
        cursor.insertText(qry.value(i).toString());
        cursor.movePosition(QTextCursor::NextCell);
      }
    } while (qry.next());
  }
  if (qry.lastError().type() != QSqlError::NoError)
    errmsg = qry.lastError().text();

  return doc.toHtml();
}

QString ExportHelper::generateXML(const int qryheadid, ParameterList &params, QString &errmsg, int xsltmapid)
{
  if (DEBUG)
    qDebug("ExportHelper::generateXML(%d, %d params, errmsg, %d) entered",
           qryheadid, params.size(), xsltmapid);
  if (DEBUG)
  {
    QStringList plist;
    for (int i = 0; i < params.size(); i++)
      plist.append("\t" + params.name(i) + ":\t" + params.value(i).toString());
    qDebug("generateXML parameters:\n%s", qPrintable(plist.join("\n")));
  }

  QDomDocument xmldoc("xtupleimport");
  QDomElement rootelem = xmldoc.createElement("xtupleimport");
  xmldoc.appendChild(rootelem);

  XSqlQuery itemq;
  QString tableElemName;
  QString schemaName;
  itemq.prepare("SELECT * FROM qryitem WHERE qryitem_qryhead_id=:id ORDER BY qryitem_order;");
  itemq.bindValue(":id", qryheadid);
  itemq.exec();
  while (itemq.next())
  {
    QString qtext;
    tableElemName = itemq.value("qryitem_name").toString();
    if (itemq.value("qryitem_src").toString() == "REL")
    {
      schemaName = itemq.value("qryitem_group").toString();
      qtext = "SELECT * FROM " +
              (schemaName.isEmpty() ? QString("") : schemaName + QString(".")) +
              itemq.value("qryitem_detail").toString();
    }
    else if (itemq.value("qryitem_src").toString() == "MQL")
    {
      QString tmpmsg;
      bool valid;
      qtext = MQLUtil::mqlLoad(itemq.value("qryitem_group").toString(),
                               itemq.value("qryitem_detail").toString(),
                               tmpmsg, &valid);
      if (! valid)
        errmsg = tmpmsg;
    }
    else if (itemq.value("qryitem_src").toString() == "CUSTOM")
      qtext = itemq.value("qryitem_detail").toString();

    if (! qtext.isEmpty())
    {
      MetaSQLQuery mql(qtext);
      XSqlQuery qry = mql.toQuery(params);
      if (qry.first())
      {
        do {
          QDomElement tableElem = xmldoc.createElement(tableElemName);

          if (DEBUG)
            qDebug("exportXML starting %s", qPrintable(tableElemName));
          if (! schemaName.isEmpty())
            tableElem.setAttribute("schema", schemaName);
          for (int i = 0; i < qry.record().count(); i++)
          {
            QDomElement fieldElem = xmldoc.createElement(qry.record().fieldName(i));
            if (qry.record().value(i).isNull())
              fieldElem.appendChild(xmldoc.createTextNode("[NULL]"));
            else
              fieldElem.appendChild(xmldoc.createTextNode(qry.record().value(i).toString()));
            tableElem.appendChild(fieldElem);
          }
          rootelem.appendChild(tableElem);
        } while (qry.next());
      }
      if (qry.lastError().type() != QSqlError::NoError)
        errmsg = qry.lastError().text();
    }
  }
  if (itemq.lastError().type() != QSqlError::NoError)
    errmsg = itemq.lastError().text();

  if (xsltmapid < 0)
    return xmldoc.toString();
  else
    return XSLTConvertString(xmldoc.toString(), xsltmapid, errmsg);
}

QString ExportHelper::generateXML(QString qtext, QString tableElemName, ParameterList &params, QString &errmsg, int xsltmapid)
{
  if (DEBUG)
    qDebug("ExportHelper::generateXML(%s..., %s, %d params, errmsg, %d) entered",
           qPrintable(qtext.left(80)), qPrintable(tableElemName),
           params.size(), xsltmapid);
  if (DEBUG)
  {
    QStringList plist;
    for (int i = 0; i < params.size(); i++)
      plist.append("\t" + params.name(i) + ":\t" + params.value(i).toString());
    qDebug("generateXML parameters:\n%s", qPrintable(plist.join("\n")));
  }

  QDomDocument xmldoc("xtupleimport");
  QDomElement rootelem = xmldoc.createElement("xtupleimport");
  xmldoc.appendChild(rootelem);

  if (! qtext.isEmpty())
  {
    MetaSQLQuery mql(qtext);
    XSqlQuery qry = mql.toQuery(params);
    if (qry.first())
    {
      do {
        QDomElement tableElem = xmldoc.createElement(tableElemName);

        if (DEBUG)
          qDebug("generateXML starting %s", qPrintable(tableElemName));
        for (int i = 0; i < qry.record().count(); i++)
        {
          QDomElement fieldElem = xmldoc.createElement(qry.record().fieldName(i));
          if (qry.record().value(i).isNull())
            fieldElem.appendChild(xmldoc.createTextNode("[NULL]"));
          else
            fieldElem.appendChild(xmldoc.createTextNode(qry.record().value(i).toString()));
          tableElem.appendChild(fieldElem);
        }
        rootelem.appendChild(tableElem);
      } while (qry.next());
    }
    if (qry.lastError().type() != QSqlError::NoError)
      errmsg = qry.lastError().text();
  }

  if (xsltmapid < 0)
    return xmldoc.toString();
  else
    return XSLTConvertString(xmldoc.toString(), xsltmapid, errmsg);
}

bool ExportHelper::XSLTConvertFile(QString inputfilename, QString outputfilename, int xsltmapid, QString &errmsg)
{
  if (DEBUG)
    qDebug("ExportHelper::XSLTConvertFile(%s, %s, %d, errmsg) entered",
           qPrintable(inputfilename), qPrintable(outputfilename), xsltmapid);
  bool returnVal = false;

  XSqlQuery xsltq;
  xsltq.prepare("SELECT xsltmap_export"
                "  FROM xsltmap"
                " WHERE xsltmap_id=:id;");

  xsltq.bindValue(":id", xsltmapid);
  xsltq.exec();
  if (xsltq.first())
    return XSLTConvertFile(inputfilename, outputfilename,
                           xsltq.value("xsltmap_export").toString(), errmsg);
  else  if (xsltq.lastError().type() != QSqlError::NoError)
    errmsg = xsltq.lastError().text();
  else
    errmsg = tr("Could not find XSLT mapping with internal id %1.")
               .arg(xsltmapid);

  return returnVal;
}

bool ExportHelper::XSLTConvertFile(QString inputfilename, QString outputfilename, QString xsltfilename, QString &errmsg)
{
  QString xsltdir;
  QString xsltcmd;

  XSqlQuery q;
  q.prepare("SELECT fetchMetricText(:xsltdir) AS dir,"
            "       fetchMetricText(:xsltcmd) AS cmd;");
#if defined Q_OS_MAC
  q.bindValue(":xsltdir", "XSLTDefaultDirMac");
  q.bindValue(":xsltcmd", "XSLTProcessorMac");
#elif defined Q_OS_WIN
  q.bindValue(":xsltdir", "XSLTDefaultDirWindows");
  q.bindValue(":xsltcmd", "XSLTProcessorWindows");
#elif defined Q_OS_LINUX
  q.bindValue(":xsltdir", "XSLTDefaultDirLinux");
  q.bindValue(":xsltcmd", "XSLTProcessorLinux");
#endif
  q.exec();
  if (q.first())
  {
    xsltdir = q.value("dir").toString();
    xsltcmd = q.value("cmd").toString();
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    errmsg = q.lastError().text();
    return false;
  }
  else
  {
    errmsg = tr("Could not find the XSLT directory and command metrics.");
    return false;
  }

  QStringList args = xsltcmd.split(" ", QString::SkipEmptyParts);
  QString command = args[0];
  args.removeFirst();
  args.replaceInStrings("%f", inputfilename);

  if (QFile::exists(xsltfilename))
    args.replaceInStrings("%x", xsltfilename);
  else if (QFile::exists(xsltdir + QDir::separator() + xsltfilename))
    args.replaceInStrings("%x", xsltdir + QDir::separator() + xsltfilename);
  else
  {
    errmsg = tr("Cannot find the XSLT file as either %1 or %2")
                .arg(xsltfilename, xsltdir + QDir::separator() + xsltfilename);
    return false;
  }

  QProcess xslt;
  xslt.setStandardOutputFile(outputfilename);
  xslt.start(command, args);
  QString commandline = command + " " + args.join(" ");
  errmsg = "";
  /* TODO: make the file-processing asynchronous
     this will keep the UI snappy and handle spurious errors
     like the occasional waitForFinished failure if the processing
     runs faster than expected.
   */
  if (! xslt.waitForStarted())
    errmsg = tr("Error starting XSLT Processing: %1\n%2")
                      .arg(commandline)
                      .arg(QString(xslt.readAllStandardError()));
  if (! xslt.waitForFinished())
    errmsg = tr("The XSLT Processor encountered an error: %1\n%2")
                      .arg(commandline)
                      .arg(QString(xslt.readAllStandardError()));
  if (xslt.exitStatus() !=  QProcess::NormalExit)
    errmsg = tr("The XSLT Processor did not exit normally: %1\n%2")
                      .arg(commandline)
                      .arg(QString(xslt.readAllStandardError()));
  if (xslt.exitCode() != 0)
    errmsg = tr("The XSLT Processor returned an error code: %1\nreturned %2\n%3")
                      .arg(commandline)
                      .arg(xslt.exitCode())
                      .arg(QString(xslt.readAllStandardError()));

  return errmsg.isEmpty();
}

QString ExportHelper::XSLTConvertString(QString input, int xsltmapid, QString &errmsg)
{
  if (DEBUG)
    qDebug("ExportHelper::XSLTConvertString(%s..., %d, errmsg) entered",
           qPrintable(input.left(200)), xsltmapid);
  QString returnVal;

  XSqlQuery xsltq;
  xsltq.prepare("SELECT xsltmap_name, xsltmap_export"
                "  FROM xsltmap"
                " WHERE xsltmap_id=:id;");

  xsltq.bindValue(":id", xsltmapid);
  xsltq.exec();
  if (xsltq.first())
  {
    /* tempfile handling is messy because windows doesn't handle them as you
       might expect.
       TODO: find a simpler way
     */
    QString xsltmap = xsltq.value("xsltmap_name").toString();
    QTemporaryFile *inputfile = new QTemporaryFile(QDir::tempPath()
                                                   + QDir::separator()
                                                   + xsltmap
                                                   + "Input.XXXXXX.xml");
    inputfile->setAutoRemove(false);
    if (! inputfile->open())
      errmsg = tr("Could not open temporary input file (%1).")
                  .arg(inputfile->error());
    else
    {
      QString inputfileName = inputfile->fileName();
      inputfile->write(input.toUtf8());
      inputfile->close();
      delete inputfile;
      inputfile = 0;

      QTemporaryFile *outputfile = new QTemporaryFile(QDir::tempPath()
                                                      + QDir::separator()
                                                      + xsltmap
                                                      + "Output.XXXXXX.xml");
      outputfile->setAutoRemove(false);
      if (! outputfile->open())
        errmsg = tr("Could not open temporary output file (%1).")
                  .arg(outputfile->error());
      else
      {
        QString outputfileName = outputfile->fileName();

        if (DEBUG)
          qDebug("ExportHelper::XSLTConvertString writing from %s to %s",
                 qPrintable(inputfileName), qPrintable(outputfileName));

        if (XSLTConvertFile(inputfileName, outputfileName,
                            xsltq.value("xsltmap_export").toString(), errmsg))
          returnVal = outputfile->readAll();

        outputfile->close();
        delete outputfile;
        outputfile = 0;

        if (errmsg.isEmpty())
        {
          QFile::remove(outputfileName);
          QFile::remove(inputfileName);
        }
      }
    }
  }
  else  if (xsltq.lastError().type() != QSqlError::NoError)
    errmsg = xsltq.lastError().text();
  else
    errmsg = tr("Could not find XSLT mapping with internal id %1.")
               .arg(xsltmapid);

  if (! errmsg.isEmpty())
    qWarning("%s", qPrintable(errmsg));
  return returnVal;
}

// scripting exposure //////////////////////////////////////////////////////////

Q_DECLARE_METATYPE(ParameterList)

static QScriptValue exportHTML(QScriptContext *context,
                               QScriptEngine  * /*engine*/)
{
  if (context->argumentCount() < 1)
    context->throwError(QScriptContext::UnknownError,
                        "not enough args passed to exportHTML");

  int           qryheadid = context->argument(0).toInt32();
  ParameterList params;
  QString       filename;
  QString       errmsg;

  if (context->argumentCount() >= 2)
    params = qscriptvalue_cast<ParameterList>(context->argument(1));
  if (context->argumentCount() >= 3)
    filename = context->argument(2).toString();
  if (context->argumentCount() >= 4)
    errmsg = context->argument(3).toString();

  if (DEBUG)
    qDebug("exportHTML(%d, %d params, %s, %s) called with %d args",
           qryheadid, params.size(), qPrintable(filename),
           qPrintable(errmsg), context->argumentCount());

  bool result = ExportHelper::exportHTML(qryheadid, params, filename, errmsg);
  // TODO: how to we pass back filename and errmsg output parameters?

  return QScriptValue(result);
}

static QScriptValue exportXML(QScriptContext *context,
                              QScriptEngine  * /*engine*/)
{
  if (context->argumentCount() < 1)
    context->throwError(QScriptContext::UnknownError,
                        "not enough args passed to exportXML");

  int           qryheadid = context->argument(0).toInt32();
  ParameterList params;
  QString       filename;
  QString       errmsg;
  int           xsltmapid = -1;

  if (context->argumentCount() >= 2)
    params = qscriptvalue_cast<ParameterList>(context->argument(1));
  if (context->argumentCount() >= 3)
    filename = context->argument(2).toString();
  if (context->argumentCount() >= 4)
    errmsg = context->argument(3).toString();
  if (context->argumentCount() >= 5)
    xsltmapid = context->argument(4).toInt32();

  if (DEBUG)
    qDebug("exportXML(%d, %d params, %s, %s, %d) called with %d args",
           qryheadid, params.size(), qPrintable(filename),
           qPrintable(errmsg), xsltmapid, context->argumentCount());

  bool result = ExportHelper::exportXML(qryheadid, params, filename,
                                        errmsg, xsltmapid);
  // TODO: how to we pass back filename and errmsg output parameters?

  return QScriptValue(result);
}

static QScriptValue generateDelimited(QScriptContext *context,
                                      QScriptEngine  * /*engine*/)
{
  QString result = QString::null;
  QString errmsg = QString::null;

  if (context->argumentCount() < 2)
    context->throwError(QScriptContext::UnknownError,
                        "not enough args passed to generateHTML");

  if (context->argument(0).isNumber())
  {
    int        qryheadid = context->argument(0).toInt32();
    ParameterList params = qscriptvalue_cast<ParameterList>(context->argument(1));

    result = ExportHelper::generateDelimited(qryheadid, params, errmsg);
  }
  else
  {
    QString         qtext = context->argument(0).toString();
    ParameterList  params = qscriptvalue_cast<ParameterList>(context->argument(1));
    result = ExportHelper::generateDelimited(qtext, params, errmsg);
  }

  // TODO: how to we pass back errmsg output parameter?

  return QScriptValue(result);
}

static QScriptValue generateHTML(QScriptContext *context,
                                 QScriptEngine  * /*engine*/)
{
  QString result = QString::null;
  QString errmsg = QString::null;

  if (context->argumentCount() < 2)
    context->throwError(QScriptContext::UnknownError,
                        "not enough args passed to generateHTML");

  if (context->argument(0).isNumber())
  {
    int        qryheadid = context->argument(0).toInt32();
    ParameterList params = qscriptvalue_cast<ParameterList>(context->argument(1));

    result = ExportHelper::generateHTML(qryheadid, params, errmsg);
  }
  else
  {
    QString         qtext = context->argument(0).toString();
    ParameterList  params = qscriptvalue_cast<ParameterList>(context->argument(1));
    result = ExportHelper::generateHTML(qtext, params, errmsg);
  }

  // TODO: how to we pass back errmsg output parameter?

  return QScriptValue(result);
}

static QScriptValue generateXML(QScriptContext *context,
                                QScriptEngine  * /*engine*/)
{
  QString result = QString::null;
  QString errmsg = QString::null;

    
  if (context->argument(0).isNumber() && context->argumentCount() == 3)
  {
    int        qryheadid = context->argument(0).toInt32();
    ParameterList params = qscriptvalue_cast<ParameterList>(context->argument(1));

    result = ExportHelper::generateXML(qryheadid, params, errmsg);
  }
  else if (context->argument(0).isNumber() && context->argumentCount() == 4)
  {
    int        qryheadid = context->argument(0).toInt32();
    ParameterList params = qscriptvalue_cast<ParameterList>(context->argument(1));
    int        xsltmapid = context->argument(3).toInt32();

    result = ExportHelper::generateXML(qryheadid, params, errmsg, xsltmapid);
  }
  else if (context->argumentCount() >= 3)
  {
    QString         qtext = context->argument(0).toString();
    QString tableElemName = context->argument(1).toString();
    ParameterList  params = qscriptvalue_cast<ParameterList>(context->argument(2));
    if (context->argumentCount() >= 5)
    {
      int xsltmapid = context->argument(4).toInt32();
      result = ExportHelper::generateXML(qtext, tableElemName, params, errmsg, xsltmapid);
    }
    else
      result = ExportHelper::generateXML(qtext, tableElemName, params, errmsg);
  }
  else
    context->throwError(QScriptContext::UnknownError,
                        "Don't know which version of generateXML to call");

  // TODO: how to we pass back errmsg output parameter?

  return QScriptValue(result);
}

static QScriptValue XSLTConvertFile(QScriptContext *context,
                                    QScriptEngine  * /*engine*/)
{
  QString inputfilename  = context->argument(0).toString();
  QString outputfilename = context->argument(1).toString();
  QString errmsg;

  bool result = false;

  if (context->argument(2).isNumber())
    result = ExportHelper::XSLTConvertFile(inputfilename, outputfilename,
                                           context->argument(2).toInt32(),
                                           errmsg);
  else
    result = ExportHelper::XSLTConvertFile(inputfilename, outputfilename,
                                           context->argument(2).toString(),
                                           errmsg);


  // TODO: how to we pass back errmsg output parameter?

  return QScriptValue(result);
}

static QScriptValue XSLTConvertString(QScriptContext *context,
                                      QScriptEngine  * /*engine*/)
{
  QString input     = context->argument(0).toString();
  int     xsltmapid = context->argument(1).toInt32();
  QString errmsg;

  QString result = ExportHelper::XSLTConvertString(input, xsltmapid, errmsg);

  // TODO: how to we pass back errmsg output parameter?

  return QScriptValue(result);
}

void setupExportHelper(QScriptEngine *engine)
{
  QScriptValue obj = engine->newObject();
  obj.setProperty("exportHTML", engine->newFunction(exportHTML),    QScriptValue::ReadOnly | QScriptValue::Undeletable);
  obj.setProperty("exportXML", engine->newFunction(exportXML),      QScriptValue::ReadOnly | QScriptValue::Undeletable);
  obj.setProperty("generateDelimited", engine->newFunction(generateDelimited),QScriptValue::ReadOnly | QScriptValue::Undeletable);
  obj.setProperty("generateHTML", engine->newFunction(generateHTML),QScriptValue::ReadOnly | QScriptValue::Undeletable);
  obj.setProperty("generateXML", engine->newFunction(generateXML),  QScriptValue::ReadOnly | QScriptValue::Undeletable);
  obj.setProperty("XSLTConvertFile", engine->newFunction(XSLTConvertFile), QScriptValue::ReadOnly | QScriptValue::Undeletable);
  obj.setProperty("XSLTConvertString", engine->newFunction(XSLTConvertString), QScriptValue::ReadOnly | QScriptValue::Undeletable);

  engine->globalObject().setProperty("ExportHelper", obj, QScriptValue::ReadOnly | QScriptValue::Undeletable);
}