File: mh_xslt.cpp

package info (click to toggle)
recoll 1.43.12-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 16,952 kB
  • sloc: cpp: 104,785; python: 9,933; xml: 7,314; ansic: 6,447; sh: 1,252; perl: 166; makefile: 72
file content (443 lines) | stat: -rw-r--r-- 15,590 bytes parent folder | download | duplicates (3)
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
/* Copyright (C) 2005-2025 J.F.Dockes 
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#include "autoconfig.h"

#if defined(HAVE_MALLOC_H)
#include <malloc.h>
#elif defined(HAVE_MALLOC_MALLOC_H)
#include <malloc/malloc.h>
#endif
#include <fnmatch.h>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxslt/transform.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/xsltutils.h>

#include "cstr.h"
#include "mh_xslt.h"
#include "log.h"
#include "smallut.h"
#include "md5ut.h"
#include "rclconfig.h"
#include "readfile.h"
#include "pathut.h"

using namespace std;

// Do we need this? It would need to be called from recollinit
// Call once, not reentrant
// xmlInitParser();
// LIBXML_TEST_VERSION;
// Probably not:    xmlCleanupParser();
        
// XML parser as FileScan sink. We just call libxml with the data chunks. Once done, call getDoc to
// obtain the parsed document.
class FileScanXML : public FileScanDo {
public:
    virtual ~FileScanXML() {
        if (ctxt) {
            xmlFreeParserCtxt(ctxt);
            // This should not be necessary (done by free), but see
            // http://xmlsoft.org/xmlmem.html#Compacting The
            // malloc_trim() and mallopt() doc seems to be a bit
            // misleading, there is probably a frag size under which
            // free() does not try to malloc_trim() at all
#ifdef HAVE_MALLOC_TRIM
            malloc_trim(0);
#endif /* HAVE_MALLOC_TRIM */
        }
    }

    xmlDocPtr getDoc() {
        int ret;
        if ((ret = xmlParseChunk(ctxt, nullptr, 0, 1))) {
            const xmlError *error = xmlGetLastError();
            LOGERR("FileScanXML: final xmlParseChunk failed with error " << ret << " error: " <<
                   (error ? error->message : " null return from xmlGetLastError()") << "\n");
            return nullptr;
        }
        return ctxt->myDoc;
    }

    virtual bool init(int64_t, string *) {
        ctxt = xmlCreatePushParserCtxt(NULL, NULL, NULL, 0, NULL);
        if (ctxt == nullptr) {
            LOGERR("FileScanXML: xmlCreatePushParserCtxt failed\n");
            return false;
        } else {
            // Replaces setting global variables through the following in the module init:
            // xmlSubstituteEntitiesDefault(0); // No XML_PARSE_NOENT
            // xmlLoadExtDtdDefaultValue = 0;   // No XML_PARSE_DTDLOAD
            xmlCtxtUseOptions(ctxt, 0);
            return true;
        }
    }
    
    virtual bool data(const char *buf, int cnt, string*) {
        if (0) {
            string dt(buf, cnt);
            LOGDEB1("FileScanXML: data: cnt " << cnt << " data " << dt << '\n');
        } else {
            LOGDEB1("FileScanXML: data: cnt " << cnt << '\n');
        }            
        int ret;
        if ((ret = xmlParseChunk(ctxt, buf, cnt, 0))) {
            const xmlError *error = xmlGetLastError();
            LOGERR("FileScanXML: xmlParseChunk failed with error " << ret << " for [" << buf <<
                   "] error " <<
                   (error ? error->message : " null return from xmlGetLastError()") << "\n");
            return false;
        } else {
            LOGDEB1("xmlParseChunk ok (sent " << cnt << " bytes)\n");
            return true;
        }
    }

private:
    xmlParserCtxtPtr ctxt{nullptr};
};

/// Helper code to get a list of a zip archive members which match a wildcard expression
class ZLister : public FileScanDo {
public:
    ZLister(const std::string& pattern) : m_pattern(pattern) {}
    bool data(const char *buf, int cnt, std::string *reason) override {
        if (fnmatch(m_pattern.c_str(), buf, 0) == 0) {
            m_result.emplace_back(buf, cnt);
        }
        return true;
    }
    std::vector<std::string> m_result;
    std::string m_pattern;
};
static std::vector<std::string>
nameList(std::shared_ptr<FileScanSourceZip> zip, const std::string& pattern)
{
    // If there are no wildcard characters, the pattern is the result
    if (pattern.find_first_of("*?") == std::string::npos) {
        // Note that we don't bother with escaping or supporting
        // character ranges. This should be enough for our current use
        return {pattern};
    }

    ZLister doer(pattern);
    if (!zip_scan(zip, "*", &doer)) {
        LOGERR("nameList: listing members failed\n");
        return {};
    }
    sortAlphanumStrings(doer.m_result);
    return doer.m_result;
}


// Handler for XML-based documents. The data can come from a memory string or from a
// file. Additionally, it can be stored in zip archive format (e.g.: openxml, opendocument etc.). In
// this case, there can be multiple members to process and multiple style sheets, and the relevant
// methods get the member name (internal path) to process.
// We have two jobs:
//  - Read and parse the XSLT style sheets associated to metadata and body parts, as defined in
//    mimeconf, which is done during initialisation in the public constructor.
//  - For each document we then get passed, apply the style sheets to obtain
//    a concatenated HTML document.
class MimeHandlerXslt::Internal {
public:
    Internal(MimeHandlerXslt *_p)
        : p(_p) {}
    ~Internal() {
        for (auto& entry : metaOrAllSS) {
            xsltFreeStylesheet(entry.second);
        }
        for (auto& entry : bodySS) {
            xsltFreeStylesheet(entry.second);
        }
    }

    xsltStylesheet *prepare_stylesheet(const string& ssnm);
    bool process_doc_or_string(bool forpv, const string& fn, const string& data);
    bool apply_stylesheet(
        const string& fn, const string& data, std::shared_ptr<FileScanSourceZip> zip,
        const string& member, xsltStylesheet *ssp, string& result, string *md5p);

    MimeHandlerXslt *p;
    bool ok{false};

    // Pairs of zip archive member names and style sheet names for the
    // metadata, and map of style sheets refd by their names.
    // Exception: there can be a single entry which does meta and
    // body, in which case bodymembers/bodySS are empty.
    vector<pair<string,string>> metaMembers;
    map <string, xsltStylesheet*> metaOrAllSS;
    // Same for body data
    vector<pair<string,string>> bodyMembers;
    map<string, xsltStylesheet*> bodySS;
    string result;
    string filtersdir;
};

MimeHandlerXslt::~MimeHandlerXslt()
{
    delete m;
}

MimeHandlerXslt::MimeHandlerXslt(
    RclConfig *cnf, const std::string& id, const std::vector<std::string>& params)
    : RecollFilter(cnf, id), m(new Internal(this))
{
    LOGDEB("MimeHandlerXslt: params: " << stringsToString(params) << '\n');
    m->filtersdir = path_cat(cnf->getDatadir(), "filters");

    // params can be "xsltproc stylesheetall" or
    // "xslt meta/body memberpath stylesheetnm [... ... ...] ...
    if (params.size() == 2) {
        auto ss = m->prepare_stylesheet(params[1]);
        if (ss) {
            m->ok = true;
            m->metaOrAllSS[""] = ss;
        }
    } else if (params.size() > 3 && params.size() % 3 == 1) {
        auto it = params.begin();
        it++;
        // Read and prepare the style sheets and associate them to the body or meta names (a style
        // sheet can be used for several parts).
        // We have a list of <member name, stylesheet name> pairs and a map of stylesheet named to
        // parsed style sheet data.
        while (it != params.end()) {
            // meta/body membername ssname
            const string& tp = *it++;
            const string& znm = *it++;
            const string& ssnm = *it++;
            vector<pair<string, string>> *mbrv;
            map<string,xsltStylesheet*> *ssmp;
            if (tp == "meta") {
                mbrv = &m->metaMembers;
                ssmp = &m->metaOrAllSS;
            } else if (tp == "body") {
                mbrv = &m->bodyMembers;
                ssmp = &m->bodySS;
            } else {
                LOGERR("MimeHandlerXslt: bad member type " << tp << '\n');
                return;
            }
            if (ssmp->find(ssnm) == ssmp->end()) {
                auto ss = m->prepare_stylesheet(ssnm);
                if (nullptr == ss) {
                    return;
                }
                ssmp->insert({ssnm, ss});
            }
            mbrv->push_back({znm, ssnm});
        }
        m->ok = true;
    } else {
        LOGERR("MimeHandlerXslt: constructor with wrong param vector: " <<
               stringsToString(params) << '\n');
    }
}

xsltStylesheet *MimeHandlerXslt::Internal::prepare_stylesheet(const string& ssnm)
{
    string ssfn;
    if (path_isabsolute(ssnm)) {
        ssfn = ssnm;
    } else {
        ssfn = path_cat(filtersdir, ssnm);
    }
    FileScanXML XMLstyle;
    string reason;
    if (!file_scan(ssfn, &XMLstyle, &reason)) {
        LOGERR("MimeHandlerXslt: file_scan error for: " << ssfn << " : " << reason << '\n');
        return nullptr;
    }
    xmlDoc *stl = XMLstyle.getDoc();
    if (stl == nullptr) {
        LOGERR("MimeHandlerXslt: getDoc failed for style sheet " << ssfn << '\n');
        return nullptr;
    }
    return xsltParseStylesheetDoc(stl);
}

// Apply a given style sheet to some data, which can be stored in a system file, a memory string, or
// a zip file object. In the latter case, we also get a member name.
bool MimeHandlerXslt::Internal::apply_stylesheet(
    const string& fn, const string& data, std::shared_ptr<FileScanSourceZip> zip,
    const string& member, xsltStylesheet *ssp, string& result, string *md5p)
{
    FileScanXML XMLdoc;
    string md5, reason;
    bool res;
    LOGDEB0("MimeHandlerXslt::Internal::apply_stylesheet: fn [" << fn << "] data.size() " <<
            data.size() << " zip " << zip << " member " << member << "\n");
    if (member.empty()) {
        // Not a zip
        if (!fn.empty()) {
            res = file_scan(fn, &XMLdoc, 0, -1, &reason, md5p);
        } else {
            res = string_scan(data.c_str(), data.size(), &XMLdoc, &reason, md5p);
        }
    } else {
        res = zip_scan(zip, member, &XMLdoc);
    }
    if (!res) {
        LOGERR("MimeHandlerXslt::set_document_: scan failed for "<<
               fn << " " << member << " : " << reason << '\n');
        return false;
    }

    xmlDocPtr doc = XMLdoc.getDoc();
    if (nullptr == doc) {
        LOGERR("MimeHandlerXslt::set_document_: no parsed doc\n");
        return false;
    }
    xmlDocPtr transformed = xsltApplyStylesheet(ssp, doc, NULL);
    if (nullptr == transformed) {
        LOGERR("MimeHandlerXslt::set_document_: xslt transform failed\n");
        xmlFreeDoc(doc);
        return false;
    }
    xmlChar *outstr;
    int outlen;
    xsltSaveResultToString(&outstr, &outlen, transformed, ssp);
    result = string((const char*)outstr, outlen);
    xmlFree(outstr);
    xmlFreeDoc(transformed);
    xmlFreeDoc(doc);
    return true;
}

// Call apply_stylesheet() for the single file or data string, or, for a zip to all members which
// need processing.
bool MimeHandlerXslt::Internal::process_doc_or_string(
    bool forpreview, const string& fn, const string& data)
{
    p->m_metaData[cstr_dj_keycharset] = cstr_utf8;
    if (bodySS.empty()) {
        auto ssp = metaOrAllSS.find("");
        if (ssp == metaOrAllSS.end()) {
            LOGERR("MimeHandlerXslt::process: no style sheet !\n");
            return false;
        }
        string md5;
        if (apply_stylesheet(fn, data, std::shared_ptr<FileScanSourceZip>(), std::string(),
                             ssp->second, result, forpreview ? nullptr : &md5)) {
            if (!forpreview) {
                p->m_metaData[cstr_dj_keymd5] = md5;
            }
            return true;
        }
        return false;
    } else {
        result = "<html>\n<head>\n<meta http-equiv=\"Content-Type\""
            "content=\"text/html; charset=UTF-8\">";

        // We initialize the zip object once, and reuse it for all catalog or data accesses.
        std::shared_ptr<FileScanSourceZip> zip;
        std::string reason;
        if (fn.empty()) {
            zip = init_scan(data.c_str(), data.size(), &reason);
        } else {
            zip = init_scan(fn, &reason);
        }
        for (auto& member : metaMembers) {
            auto it = metaOrAllSS.find(member.second);
            if (it == metaOrAllSS.end()) {
                LOGERR("MimeHandlerXslt::process: no style sheet found for " <<
                       member.first << ":" << member.second << "!\n");
                return false;
            }
            auto names = nameList(zip, member.first);
            for (const auto& nm : names) {
                string part;
                if (!apply_stylesheet(fn, data, zip, nm, it->second, part, nullptr)) {
                    LOGERR("apply_stylesheet failed: " << reason << '\n');
                    return false;
                }
                result += part;
            }
        }
        result += "</head>\n<body>\n";
        
        for (auto& member : bodyMembers) {
            auto it = bodySS.find(member.second);
            if (it == bodySS.end()) {
                LOGERR("MimeHandlerXslt::process: no style sheet found for " <<
                       member.first << ":" << member.second << "!\n");
                return false;
            }
            auto names = nameList(zip, member.first);
            for (const auto& nm : names) {
                string part;
                if (!apply_stylesheet(fn, data, zip, nm, it->second, part, nullptr)) {
                    LOGERR("apply_stylesheet failed: " << reason << '\n');
                    return false;
                }
                if (forpreview)
                    result += std::string("<h2>") + nm + "</h2>";
                result += part;
            }
        }
        result += "</body></html>";
    }
    return true;
}

bool MimeHandlerXslt::set_document_file_impl(const string&, const string &fn)
{
    LOGDEB0("MimeHandlerXslt::set_document_file_: fn: " << fn << '\n');
    if (!m || !m->ok) {
        return false;
    }
    bool ret = m->process_doc_or_string(m_forPreview, fn, string());
    if (ret) {
        m_havedoc = true;
    }
    return ret;
}

bool MimeHandlerXslt::set_document_string_impl(const string&, const string& txt)
{
    LOGDEB0("MimeHandlerXslt::set_document_string_\n");
    if (!m || !m->ok) {
        return false;
    }
    bool ret = m->process_doc_or_string(m_forPreview, string(), txt);
    if (ret) {
        m_havedoc = true;
    }
    return ret;
}

bool MimeHandlerXslt::next_document()
{
    if (!m || !m->ok) {
        return false;
    }
    if (m_havedoc == false)
        return false;
    m_havedoc = false;
    m_metaData[cstr_dj_keymt] = cstr_texthtml;
    m_metaData[cstr_dj_keycontent].swap(m->result);
    LOGDEB1("MimeHandlerXslt::next_document: result: [" << m_metaData[cstr_dj_keycontent] << "]\n");
    return true;
}

void MimeHandlerXslt::clear_impl()
{
    m_havedoc = false;
    m->result.clear();
}