summaryrefslogtreecommitdiff
path: root/filter/source/xsltfilter/XSLTFilter.cxx
blob: 47d9e380ae14cd9d775670026991654674a84ff9 (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */


#include <cppuhelper/factory.hxx>
#include <cppuhelper/implbase.hxx>

#include <sax/tools/documenthandleradapter.hxx>

#include <osl/time.h>
#include <osl/conditn.hxx>
#include <rtl/strbuf.hxx>
#include <tools/urlobj.hxx>

#include <comphelper/interaction.hxx>
#include <comphelper/processfactory.hxx>

#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/EventObject.hpp>

#include <com/sun/star/uno/Any.hxx>

#include <com/sun/star/beans/PropertyValue.hpp>

#include <com/sun/star/xml/sax/Parser.hpp>
#include <com/sun/star/xml/sax/InputSource.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#include <com/sun/star/xml/sax/XFastParser.hpp>
#include <com/sun/star/xml/sax/SAXException.hpp>
#include <com/sun/star/xml/sax/Writer.hpp>
#include <com/sun/star/xml/XImportFilter.hpp>
#include <com/sun/star/xml/XExportFilter.hpp>

#include <com/sun/star/util/theMacroExpander.hpp>

#include <com/sun/star/io/Pipe.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XActiveDataSink.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/io/XStreamListener.hpp>
#include <com/sun/star/util/PathSubstitution.hpp>
#include <com/sun/star/util/XStringSubstitution.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/task/XInteractionRequest.hpp>
#include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp>
#include <com/sun/star/xml/xslt/XSLT2Transformer.hpp>
#include <com/sun/star/xml/xslt/XSLTTransformer.hpp>

#include <xmloff/attrlist.hxx>

#include <LibXSLTTransformer.hxx>

#define TRANSFORMATION_TIMEOUT_SEC 60

using namespace ::cppu;
using namespace ::osl;
using namespace ::sax;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::xml;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::task;

namespace XSLT
{
    /*
     * XSLTFilter reads flat XML streams from the XML filter framework and passes
     * them to an XSLT transformation service. XSLT transformation errors are
     * reported to XSLTFilter.
     *
     * Currently, our transformation service is libxslt based, so it
     * only supports XSLT 1.0. There is a possibility to use XSLT 2.0
     * supporting service from an extension for a specific filter; the
     * service must support com.sun.star.xml.xslt.XSLT2Transformer.
     */
    class XSLTFilter : public WeakImplHelper<XImportFilter, XExportFilter,
            XStreamListener, ExtendedDocumentHandlerAdapter>
    {
    private:

        // the UNO ServiceFactory
        css::uno::Reference<XComponentContext> m_xContext;

        // DocumentHandler interface of the css::xml::sax::Writer service
        css::uno::Reference<XOutputStream> m_rOutputStream;

        css::uno::Reference<xslt::XXSLTTransformer> m_tcontrol;

        osl::Condition m_cTransformed;
        bool m_bTerminated;
        bool m_bError;

        OUString m_aExportBaseUrl;

        OUString
        rel2abs(const OUString&);
        OUString
        expandUrl(const OUString&);

        css::uno::Reference<xslt::XXSLTTransformer> impl_createTransformer(const OUString& rTransformer, const Sequence<Any>& rArgs);

    public:

        // ctor...
        explicit XSLTFilter(const css::uno::Reference<XComponentContext> &r);

        // XStreamListener
        virtual void SAL_CALL
        error(const Any& a) override;
        virtual void SAL_CALL
        closed() override;
        virtual void SAL_CALL
        terminated() override;
        virtual void SAL_CALL
        started() override;
        virtual void SAL_CALL
        disposing(const EventObject& e) override;

        // XImportFilter
        virtual sal_Bool SAL_CALL
        importer(const Sequence<PropertyValue>& aSourceData, const css::uno::Reference<
                XDocumentHandler>& xHandler,
                const Sequence<OUString>& msUserData) override;

        // XExportFilter
        virtual sal_Bool SAL_CALL
        exporter(const Sequence<PropertyValue>& aSourceData, const Sequence<
                OUString>& msUserData) override;

        // XDocumentHandler
        virtual void SAL_CALL
        startDocument() override;
        virtual void SAL_CALL
        endDocument() override;
    };

    XSLTFilter::XSLTFilter(const css::uno::Reference<XComponentContext> &r):
        m_xContext(r), m_bTerminated(false), m_bError(false)
    {}

    void
    XSLTFilter::disposing(const EventObject&)
    {
    }

    OUString
    XSLTFilter::expandUrl(const OUString& sUrl)
    {
        OUString sExpandedUrl;
        try
            {
                css::uno::Reference<XMacroExpander>
                        xMacroExpander = theMacroExpander::get(m_xContext);
                sExpandedUrl = xMacroExpander->expandMacros(sUrl);
                sal_Int32 nPos = sExpandedUrl.indexOf( "vnd.sun.star.expand:" );
                if (nPos != -1)
                    sExpandedUrl = sExpandedUrl.copy(nPos + 20);
            }
        catch (const Exception&)
            {
            }
        return sExpandedUrl;
    }

    css::uno::Reference<xslt::XXSLTTransformer>
    XSLTFilter::impl_createTransformer(const OUString& rTransformer, const Sequence<Any>& rArgs)
    {
        css::uno::Reference<xslt::XXSLTTransformer> xTransformer;

        // check if the filter needs XSLT-2.0-capable transformer
        // COMPATIBILITY: libreoffice 3.5/3.6 used to save the impl.
        // name of the XSLT 2.0 transformation service there, so check
        // for that too (it is sufficient to check that there is _a_
        // service name there)
        if (rTransformer.toBoolean() || rTransformer.startsWith("com.sun."))
        {
            try
            {
                xTransformer = xslt::XSLT2Transformer::create(m_xContext, rArgs);
            }
            catch (const Exception&)
            {
                // TODO: put a dialog telling about the need to install
                // xslt2-transformer extension here
                SAL_WARN("filter.xslt", "could not create XSLT 2.0 transformer");
                throw;
            }
        }

        // instantiation of XSLT 2.0 transformer service failed, or the
        // filter does not need it
        if (!xTransformer.is())
        {
            xTransformer = xslt::XSLTTransformer::create(m_xContext, rArgs);
        }

        return xTransformer;
    }

    void
    XSLTFilter::started()
    {
        m_cTransformed.reset();
    }
    void
    XSLTFilter::error(const Any& a)
    {
        Exception e;
        if (a >>= e)
        {
            SAL_WARN("filter.xslt", "XSLTFilter::error was called: " << e.Message);
        }
        m_bError = true;
        m_cTransformed.set();
    }
    void
    XSLTFilter::closed()
    {
        m_cTransformed.set();
    }
    void
    XSLTFilter::terminated()
    {
        m_bTerminated = true;
        m_cTransformed.set();
    }

    OUString
    XSLTFilter::rel2abs(const OUString& s)
    {

        css::uno::Reference<XStringSubstitution>
                subs(css::util::PathSubstitution::create(m_xContext));
        OUString aWorkingDir(subs->getSubstituteVariableValue( "$(progurl)" ));
        INetURLObject aObj(aWorkingDir);
        aObj.setFinalSlash();
        bool bWasAbsolute;
        INetURLObject aURL = aObj.smartRel2Abs(s, bWasAbsolute, false,
                INetURLObject::EncodeMechanism::WasEncoded, RTL_TEXTENCODING_UTF8, true);
        return aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE);
    }

    sal_Bool
    XSLTFilter::importer(const Sequence<PropertyValue>& aSourceData,
            const css::uno::Reference<XDocumentHandler>& xHandler, const Sequence<
                    OUString>& msUserData)
    {
        if (msUserData.getLength() < 5)
            return false;

        OUString udStyleSheet = rel2abs(msUserData[4]);

        // get information from media descriptor
        // the input stream that represents the imported file
        // is most important here since we need to supply it to
        // the sax parser that drives the supplied document handler
        sal_Int32 nLength = aSourceData.getLength();
        OUString aName, aFileName, aURL;
        css::uno::Reference<XInputStream> xInputStream;
        css::uno::Reference<XInteractionHandler> xInterActionHandler;
        for (sal_Int32 i = 0; i < nLength; i++)
            {
                aName = aSourceData[i].Name;
                Any value = aSourceData[i].Value;
                if ( aName == "InputStream" )
                    value >>= xInputStream;
                else if ( aName == "FileName" )
                    value >>= aFileName;
                else if ( aName == "URL" )
                    value >>= aURL;
                else if ( aName == "InteractionHandler" )
                    value >>= xInterActionHandler;
            }
        OSL_ASSERT(xInputStream.is());
        if (!xInputStream.is())
            return false;

        // create SAX parser that will read the document file
        // and provide events to xHandler passed to this call
        css::uno::Reference<XParser> xSaxParser = Parser::create(m_xContext);

        // create transformer
        Sequence<Any> args(3);
        NamedValue nv;

        nv.Name = "StylesheetURL";
        nv.Value <<= expandUrl(udStyleSheet);
        args[0] <<= nv;
        nv.Name = "SourceURL";
        nv.Value <<= aURL;
        args[1] <<= nv;
        nv.Name = "SourceBaseURL";
        nv.Value <<= INetURLObject(aURL).getBase();
        args[2] <<= nv;

        m_tcontrol = impl_createTransformer(msUserData[1], args);

        OSL_ASSERT(xHandler.is());
        OSL_ASSERT(xInputStream.is());
        OSL_ASSERT(m_tcontrol.is());
        if (xHandler.is() && xInputStream.is() && m_tcontrol.is())
            {
                try
                    {
                        css::uno::Reference<css::io::XSeekable> xSeek(xInputStream, UNO_QUERY);
                        if (xSeek.is())
                            xSeek->seek(0);

                        // we want to be notfied when the processing is done...
                        m_tcontrol->addListener(css::uno::Reference<XStreamListener> (
                                this));

                        // connect input to transformer
                        css::uno::Reference<XActiveDataSink> tsink(m_tcontrol, UNO_QUERY);
                        tsink->setInputStream(xInputStream);

                        // create pipe
                        css::uno::Reference<XOutputStream> pipeout(
                                        Pipe::create(m_xContext),
                                        UNO_QUERY);
                        css::uno::Reference<XInputStream> pipein(pipeout, UNO_QUERY);

                        //connect transformer to pipe
                        css::uno::Reference<XActiveDataSource> tsource(m_tcontrol,
                                UNO_QUERY);
                        tsource->setOutputStream(pipeout);

                        // connect pipe to sax parser
                        InputSource aInput;
                        aInput.sSystemId = aURL;
                        aInput.sPublicId = aURL;
                        aInput.aInputStream = pipein;

                        // set doc handler
                        xSaxParser->setDocumentHandler(xHandler);
                        css::uno::Reference< css::xml::sax::XFastParser > xFastParser = dynamic_cast<
                            css::xml::sax::XFastParser* >( xHandler.get() );

                        // transform
                        m_tcontrol->start();
                        TimeValue timeout = { TRANSFORMATION_TIMEOUT_SEC, 0};
                        osl::Condition::Result result(m_cTransformed.wait(&timeout));
                        while (osl::Condition::result_timeout == result) {
                                if (xInterActionHandler.is()) {
                                        Sequence<Any> excArgs(0);
                                        css::ucb::InteractiveAugmentedIOException exc(
                                                "Timeout!",
                                                static_cast< OWeakObject * >( this ),
                                                InteractionClassification_ERROR,
                                                css::ucb::IOErrorCode_GENERAL,
                                                 excArgs);
                                        Any r;
                                        r <<= exc;
                                        ::comphelper::OInteractionRequest* pRequest = new ::comphelper::OInteractionRequest(r);
                                        css::uno::Reference< XInteractionRequest > xRequest(pRequest);
                                        ::comphelper::OInteractionRetry* pRetry = new ::comphelper::OInteractionRetry;
                                        ::comphelper::OInteractionAbort* pAbort = new ::comphelper::OInteractionAbort;
                                        pRequest->addContinuation(pRetry);
                                        pRequest->addContinuation(pAbort);
                                        xInterActionHandler->handle(xRequest);
                                        if (pAbort->wasSelected()) {
                                                m_bError = true;
                                                m_cTransformed.set();
                                        }
                                }
                                result = m_cTransformed.wait(&timeout);
                        };
                        if (!m_bError) {
                                if( xFastParser.is() )
                                    xFastParser->parseStream( aInput );
                                else
                                    xSaxParser->parseStream( aInput );
                        }
                        m_tcontrol->terminate();
                        return !m_bError;
                    }
                catch( const Exception& exc)
                    {
                        // something went wrong
                        OSL_FAIL(OUStringToOString(exc.Message, RTL_TEXTENCODING_ASCII_US).getStr());
                        return false;
                    }
            }
        else
            {
                return false;
            }
    }

    sal_Bool
    XSLTFilter::exporter(const Sequence<PropertyValue>& aSourceData,
            const Sequence<OUString>& msUserData)
    {
        if (msUserData.getLength() < 6)
            return false;

        // get interesting values from user data
        OUString udStyleSheet = rel2abs(msUserData[5]);

        // read source data
        // we are especially interested in the output stream
        // since that is where our xml-writer will push the data
        // from its data-source interface
        OUString aName, sURL;
        bool bIndent = false;
        OUString aDoctypePublic;
        // css::uno::Reference<XOutputStream> rOutputStream;
        sal_Int32 nLength = aSourceData.getLength();
        for (sal_Int32 i = 0; i < nLength; i++)
            {
                aName = aSourceData[i].Name;
                if ( aName == "Indent" )
                    aSourceData[i].Value >>= bIndent;
                if ( aName == "DocType_Public" )
                    aSourceData[i].Value >>= aDoctypePublic;
                if ( aName == "OutputStream" )
                    aSourceData[i].Value >>= m_rOutputStream;
                else if ( aName == "URL" )
                    aSourceData[i].Value >>= sURL;
            }

        if (!getDelegate().is())
            {
                // get the document writer
                setDelegate(css::uno::Reference<XExtendedDocumentHandler>(
                                Writer::create(m_xContext),
                                UNO_QUERY_THROW));
            }

        // create transformer
        Sequence<Any> args(4);
        NamedValue nv;
        nv.Name = "StylesheetURL";
        nv.Value <<= expandUrl(udStyleSheet);
        args[0] <<= nv;
        nv.Name = "TargetURL";
        nv.Value <<= sURL;
        args[1] <<= nv;
        nv.Name = "DoctypePublic";
        nv.Value <<= aDoctypePublic;
        args[2] <<= nv;
        nv.Name = "TargetBaseURL";
        INetURLObject ineturl(sURL);
        ineturl.removeSegment();
        m_aExportBaseUrl = ineturl.GetMainURL(INetURLObject::DecodeMechanism::NONE);
        nv.Value <<= m_aExportBaseUrl;
        args[3] <<= nv;

        m_tcontrol = impl_createTransformer(msUserData[1], args);

        OSL_ASSERT(m_rOutputStream.is());
        OSL_ASSERT(m_tcontrol.is());
        if (m_tcontrol.is() && m_rOutputStream.is())
            {
                // we want to be notfied when the processing is done...
                m_tcontrol->addListener(css::uno::Reference<XStreamListener> (this));

                // create pipe
                css::uno::Reference<XOutputStream> pipeout(
                                Pipe::create(m_xContext),
                                UNO_QUERY);
                css::uno::Reference<XInputStream> pipein(pipeout, UNO_QUERY);

                // connect sax writer to pipe
                css::uno::Reference<XActiveDataSource> xmlsource(getDelegate(),
                        UNO_QUERY);
                xmlsource->setOutputStream(pipeout);

                // connect pipe to transformer
                css::uno::Reference<XActiveDataSink> tsink(m_tcontrol, UNO_QUERY);
                tsink->setInputStream(pipein);

                // connect transformer to output
                css::uno::Reference<XActiveDataSource> tsource(m_tcontrol, UNO_QUERY);
                tsource->setOutputStream(m_rOutputStream);

                // we will start receiving events after returning 'true'.
                // we will start the transformation as soon as we receive the startDocument
                // event.
                return true;
            }
        else
            {
                return false;
            }
    }

    // for the DocumentHandler implementation, we just proxy the
    // events to the XML writer that we created upon the output stream
    // that was provided by the XMLFilterAdapter
    void
    XSLTFilter::startDocument()
    {
        ExtendedDocumentHandlerAdapter::startDocument();
        m_tcontrol->start();
    }

    void
    XSLTFilter::endDocument()
    {
        ExtendedDocumentHandlerAdapter::endDocument();
        // wait for the transformer to finish
        m_cTransformed.wait();
        m_tcontrol->terminate();
        if (!m_bError && !m_bTerminated)
            {
                return;
            }
        else
            {
                throw RuntimeException();
            }

    }


    // Component management

#define FILTER_SERVICE_NAME "com.sun.star.documentconversion.XSLTFilter"
#define FILTER_IMPL_NAME "com.sun.star.comp.documentconversion.XSLTFilter"
#define TRANSFORMER_SERVICE_NAME "com.sun.star.xml.xslt.XSLTTransformer"
#define TRANSFORMER_IMPL_NAME "com.sun.star.comp.documentconversion.LibXSLTTransformer"

    static css::uno::Reference<XInterface> SAL_CALL
    CreateTransformerInstance(const css::uno::Reference<XMultiServiceFactory> &r)
    {
        return css::uno::Reference<XInterface> (static_cast<OWeakObject *>(new LibXSLTTransformer( comphelper::getComponentContext(r) )));
    }

    static css::uno::Reference<XInterface> SAL_CALL
    CreateFilterInstance(const css::uno::Reference<XMultiServiceFactory> &r)
    {
        return css::uno::Reference<XInterface> (static_cast<OWeakObject *>(new XSLTFilter( comphelper::getComponentContext(r) )));
    }

}

using namespace XSLT;

extern "C"
{
    SAL_DLLPUBLIC_EXPORT void * SAL_CALL xsltfilter_component_getFactory(const sal_Char * pImplName,
            void * pServiceManager, void * /* pRegistryKey */)
    {
        void * pRet = nullptr;

        if (pServiceManager)
            {
                if (rtl_str_compare(pImplName, FILTER_IMPL_NAME) == 0)
                    {
                        Sequence<OUString> serviceNames { FILTER_SERVICE_NAME };

                        css::uno::Reference<XSingleServiceFactory>
                                xFactory(
                                        createSingleFactory(
                                                static_cast<XMultiServiceFactory *> (pServiceManager),
                                                OUString::createFromAscii(
                                                        pImplName),
                                                CreateFilterInstance,
                                                serviceNames));

                        if (xFactory.is())
                            {
                                xFactory->acquire();
                                pRet = xFactory.get();
                            }
                    }
                else if (rtl_str_compare(pImplName, TRANSFORMER_IMPL_NAME) == 0)
                    {
                        Sequence<OUString> serviceNames { TRANSFORMER_SERVICE_NAME };
                        css::uno::Reference<XSingleServiceFactory>
                                xFactory(
                                        createSingleFactory(
                                                static_cast<XMultiServiceFactory *> (pServiceManager),
                                                OUString::createFromAscii(
                                                        pImplName),
                                                CreateTransformerInstance,
                                                serviceNames));

                        if (xFactory.is())
                            {
                                xFactory->acquire();
                                pRet = xFactory.get();
                            }

                    }
            }
        return pRet;
    }

} // extern "C"

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */