summaryrefslogtreecommitdiff
path: root/xmloff/source/meta/xmlversion.cxx
blob: 1bd1f19bf2a0ed525ce5689bebc836a6b4979554 (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
/* -*- 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 <com/sun/star/embed/ElementModes.hpp>
#include <tools/debug.hxx>
#include <unotools/streamwrap.hxx>
#include <xmlversion.hxx>
#include <xmloff/xmlmetae.hxx>

#include <xmloff/xmltoken.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/util/DateTime.hpp>
#include <com/sun/star/util/MeasureUnit.hpp>
#include <com/sun/star/xml/sax/InputSource.hpp>
#include <com/sun/star/xml/sax/Parser.hpp>
#include <com/sun/star/xml/sax/Writer.hpp>

using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;

const char XMLN_VERSIONSLIST[] = "VersionList.xml";

// #110897#
XMLVersionListExport::XMLVersionListExport(
    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > xContext,
    const com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& rVersions,
    const OUString &rFileName,
    Reference< XDocumentHandler > &rHandler )
:   SvXMLExport( xContext, "", rFileName, util::MeasureUnit::CM, rHandler ),
    maVersions( rVersions )
{
    _GetNamespaceMap().AddAtIndex( XML_NAMESPACE_DC_IDX, xmloff::token::GetXMLToken(xmloff::token::XML_NP_DC),
                                   xmloff::token::GetXMLToken(xmloff::token::XML_N_DC), XML_NAMESPACE_DC );
    _GetNamespaceMap().AddAtIndex( XML_NAMESPACE_FRAMEWORK_IDX, xmloff::token::GetXMLToken(xmloff::token::XML_NP_VERSIONS_LIST),
                                   xmloff::token::GetXMLToken(xmloff::token::XML_N_VERSIONS_LIST), XML_NAMESPACE_FRAMEWORK );
}

sal_uInt32 XMLVersionListExport::exportDoc( enum ::xmloff::token::XMLTokenEnum )
{
    GetDocHandler()->startDocument();

    addChaffWhenEncryptedStorage();

    sal_uInt16 nPos = _GetNamespaceMap().GetIndexByKey( XML_NAMESPACE_DC );

    AddAttribute( XML_NAMESPACE_NONE, _GetNamespaceMap().GetAttrNameByIndex( nPos ),
                             _GetNamespaceMap().GetNameByIndex ( nPos ) );

    nPos = _GetNamespaceMap().GetIndexByKey( XML_NAMESPACE_FRAMEWORK );
    AddAttribute( XML_NAMESPACE_NONE, _GetNamespaceMap().GetAttrNameByIndex( nPos ),
                             _GetNamespaceMap().GetNameByIndex ( nPos ) );

    {
        // the following object will write all collected attributes in its dtor
        SvXMLElementExport aRoot( *this, XML_NAMESPACE_FRAMEWORK, xmloff::token::XML_VERSION_LIST, true, true );

        for ( sal_Int32 n=0; n<maVersions.getLength(); n++ )
        {
            const util::RevisionTag& rInfo = maVersions[n];
            AddAttribute( XML_NAMESPACE_FRAMEWORK,
                          xmloff::token::XML_TITLE,
                          OUString( rInfo.Identifier ) );
            AddAttribute( XML_NAMESPACE_FRAMEWORK,
                          xmloff::token::XML_COMMENT,
                          OUString( rInfo.Comment ) );
            AddAttribute( XML_NAMESPACE_FRAMEWORK,
                          xmloff::token::XML_CREATOR,
                          OUString( rInfo.Author ) );

            OUString aDateStr =
                SvXMLMetaExport::GetISODateTimeString( rInfo.TimeStamp );

            AddAttribute( XML_NAMESPACE_DC, xmloff::token::XML_DATE_TIME, aDateStr );

            // the following object will write all collected attributes in its dtor
            SvXMLElementExport aEntry( *this, XML_NAMESPACE_FRAMEWORK, xmloff::token::XML_VERSION_ENTRY, true, true );
        }
    }
    GetDocHandler()->endDocument();
    return 0;
}

XMLVersionListImport::XMLVersionListImport(
    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > xContext,
    com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& rVersions )
:   SvXMLImport(xContext, ""),
    maVersions( rVersions )
{
    GetNamespaceMap().AddAtIndex( XML_NAMESPACE_FRAMEWORK_IDX, xmloff::token::GetXMLToken(xmloff::token::XML_NP_VERSIONS_LIST),
                                  xmloff::token::GetXMLToken(xmloff::token::XML_N_VERSIONS_LIST), XML_NAMESPACE_FRAMEWORK );
}

XMLVersionListImport::~XMLVersionListImport( void ) throw()
{}

SvXMLImportContext *XMLVersionListImport::CreateContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    if ( XML_NAMESPACE_FRAMEWORK == nPrefix &&
        rLocalName == xmloff::token::GetXMLToken(xmloff::token::XML_VERSION_LIST) )
    {
        pContext = new XMLVersionListContext( *this, nPrefix, rLocalName, xAttrList );
    }
    else
    {
        pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );
    }

    return pContext;
}

XMLVersionListContext::XMLVersionListContext( XMLVersionListImport& rImport,
                                        sal_uInt16 nPrefix,
                                        const OUString& rLocalName,
                                        const Reference< XAttributeList > & )
    : SvXMLImportContext( rImport, nPrefix, rLocalName )
    , rLocalRef( rImport )
{
}

XMLVersionListContext::~XMLVersionListContext( void )
{}

SvXMLImportContext *XMLVersionListContext::CreateChildContext( sal_uInt16 nPrefix,
                                        const OUString& rLocalName,
                                        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    if ( nPrefix == XML_NAMESPACE_FRAMEWORK &&
         rLocalName == xmloff::token::GetXMLToken(xmloff::token::XML_VERSION_ENTRY) )
    {
        pContext = new XMLVersionContext( rLocalRef, nPrefix, rLocalName, xAttrList );
    }
    else
    {
        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName );
    }

    return pContext;
}

XMLVersionContext::XMLVersionContext( XMLVersionListImport& rImport,
                                        sal_uInt16 nPref,
                                        const OUString& rLocalName,
                                        const Reference< XAttributeList > & xAttrList )
    : SvXMLImportContext( rImport, nPref, rLocalName )
    , rLocalRef( rImport )
{
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;

    if ( !nAttrCount )
        return;

    util::RevisionTag aInfo;
    for ( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        OUString        aLocalName;
        const OUString& rAttrName   = xAttrList->getNameByIndex( i );
        sal_uInt16      nPrefix     = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );

        if ( XML_NAMESPACE_FRAMEWORK == nPrefix )
        {
            if ( aLocalName == xmloff::token::GetXMLToken(xmloff::token::XML_TITLE) )
            {
                const OUString& rAttrValue = xAttrList->getValueByIndex( i );
                aInfo.Identifier = rAttrValue;
            }
            else if ( aLocalName == xmloff::token::GetXMLToken(xmloff::token::XML_COMMENT) )
            {
                const OUString& rAttrValue = xAttrList->getValueByIndex( i );
                aInfo.Comment = rAttrValue;
            }
            else if ( aLocalName == xmloff::token::GetXMLToken(xmloff::token::XML_CREATOR) )
            {
                const OUString& rAttrValue = xAttrList->getValueByIndex( i );
                aInfo.Author = rAttrValue;
            }
        }
        else if ( ( XML_NAMESPACE_DC == nPrefix ) &&
                  ( aLocalName == xmloff::token::GetXMLToken(xmloff::token::XML_DATE_TIME) ) )
        {
            const OUString& rAttrValue = xAttrList->getValueByIndex( i );
            util::DateTime aTime;
            if ( ParseISODateTimeString( rAttrValue, aTime ) )
                aInfo.TimeStamp = aTime;
        }
    }

    uno::Sequence < util::RevisionTag >& aList = rLocalRef.GetList();
    sal_Int32 nLength = aList.getLength();
    aList.realloc( nLength+1 );
    aList[nLength] = aInfo;
}

XMLVersionContext::~XMLVersionContext( void )
{}

bool XMLVersionContext::ParseISODateTimeString(
                                const OUString& rString,
                                util::DateTime& rDateTime )
{
    bool bSuccess = true;

    OUString aDateStr, aTimeStr;
    sal_Int32 nPos = rString.indexOf( (sal_Unicode) 'T' );
    if ( nPos >= 0 )
    {
        aDateStr = rString.copy( 0, nPos );
        aTimeStr = rString.copy( nPos + 1 );
    }
    else
        aDateStr = rString;         // no separator: only date part

    sal_Int32 nYear  = 0;
    sal_Int32 nMonth = 1;
    sal_Int32 nDay   = 1;
    sal_Int32 nHour  = 0;
    sal_Int32 nMin   = 0;
    sal_Int32 nSec   = 0;

    const sal_Unicode* pStr = aDateStr.getStr();
    sal_Int32 nDateTokens = 1;
    while ( *pStr )
    {
        if ( *pStr == '-' )
            nDateTokens++;
        pStr++;
    }
    if ( nDateTokens > 3 || aDateStr.isEmpty() )
        bSuccess = false;
    else
    {
        sal_Int32 n = 0;
        nYear = aDateStr.getToken( 0, '-', n ).toInt32();
        if ( nYear > 9999 )
            bSuccess = false;
        else if ( nDateTokens >= 2 )
        {
            nMonth = aDateStr.getToken( 0, '-', n ).toInt32();
            if ( nMonth > 12 )
                bSuccess = false;
            else if ( nDateTokens >= 3 )
            {
                nDay = aDateStr.getToken( 0, '-', n ).toInt32();
                if ( nDay > 31 )
                    bSuccess = false;
            }
        }
    }

    if ( bSuccess && !aTimeStr.isEmpty() )         // time is optional
    {
        pStr = aTimeStr.getStr();
        sal_Int32 nTimeTokens = 1;
        while ( *pStr )
        {
            if ( *pStr == ':' )
                nTimeTokens++;
            pStr++;
        }
        if ( nTimeTokens > 3 )
            bSuccess = false;
        else
        {
            sal_Int32 n = 0;
            nHour = aTimeStr.getToken( 0, ':', n ).toInt32();
            if ( nHour > 23 )
                bSuccess = false;
            else if ( nTimeTokens >= 2 )
            {
                nMin = aTimeStr.getToken( 0, ':', n ).toInt32();
                if ( nMin > 59 )
                    bSuccess = false;
                else if ( nTimeTokens >= 3 )
                {
                    nSec = aTimeStr.getToken( 0, ':', n ).toInt32();
                    if ( nSec > 59 )
                        bSuccess = false;
                }
            }
        }
    }

    if ( bSuccess )
    {
        rDateTime.Day = sal::static_int_cast< sal_uInt16 >(nDay);
        rDateTime.Month = sal::static_int_cast< sal_uInt16 >(nMonth);
        rDateTime.Year = sal::static_int_cast< sal_uInt16 >(nYear);
        rDateTime.Hours = sal::static_int_cast< sal_uInt16 >(nHour);
        rDateTime.Minutes = sal::static_int_cast< sal_uInt16 >(nMin);
        rDateTime.Seconds = sal::static_int_cast< sal_uInt16 >(nSec);
    }

    return bSuccess;
}

void SAL_CALL XMLVersionListPersistence::store( const uno::Reference< embed::XStorage >& xRoot, const uno::Sequence< util::RevisionTag >& rVersions )
    throw (::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception)
{
    // no storage, no version list!
    if ( xRoot.is() )
    {
        // get the services needed for writing the xml data
        Reference< uno::XComponentContext > xContext =
                comphelper::getProcessComponentContext();

        Reference< XWriter > xWriter = Writer::create(xContext);

        // check whether there's already a sub storage with the version info
        // and delete it
        OUString sVerName( XMLN_VERSIONSLIST  );

        try {
            // open (create) the sub storage with the version info
            uno::Reference< io::XStream > xVerStream = xRoot->openStreamElement(
                                            sVerName,
                                            embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE );
            if ( !xVerStream.is() )
                throw uno::RuntimeException();

            Reference< io::XOutputStream > xOut = xVerStream->getOutputStream();
            if ( !xOut.is() )
                throw uno::RuntimeException(); // the stream was successfully opened for writing already

            Reference< io::XActiveDataSource > xSrc( xWriter, uno::UNO_QUERY );
            xSrc->setOutputStream(xOut);

            Reference< XDocumentHandler > xHandler( xWriter, uno::UNO_QUERY );

            XMLVersionListExport aExp( xContext, rVersions, sVerName, xHandler );

            aExp.exportDoc( ::xmloff::token::XML_VERSION );

            xVerStream = uno::Reference< io::XStream >(); // use refcounting for now to dispose
        }
        catch( uno::Exception& )
        {
            // TODO: error handling
        }
    }
}

uno::Sequence< util::RevisionTag > SAL_CALL XMLVersionListPersistence::load( const uno::Reference< embed::XStorage >& xRoot )
        throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception)
{
    com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag > aVersions;

    const OUString sDocName( XMLN_VERSIONSLIST  );
    uno::Reference< container::XNameAccess > xRootNames( xRoot, uno::UNO_QUERY );

    try {
        if ( xRootNames.is() && xRootNames->hasByName( sDocName ) && xRoot->isStreamElement( sDocName ) )
        {
            Reference< uno::XComponentContext > xContext = comphelper::getProcessComponentContext();

            InputSource aParserInput;

            uno::Reference< beans::XPropertySet > xProps( xRoot, uno::UNO_QUERY );
            OSL_ENSURE( xProps.is(), "Storage must implement XPropertySet!\n" );
            if ( xProps.is() )
            {
                try {
                    xProps->getPropertyValue("URL") >>= aParserInput.sSystemId;
                }
                catch( uno::Exception& )
                {}
            }

            uno::Reference< io::XStream > xDocStream = xRoot->openStreamElement(
                                                            sDocName,
                                                            embed::ElementModes::READ );
            if ( !xDocStream.is() )
                throw uno::RuntimeException();

            aParserInput.aInputStream = xDocStream->getInputStream();
            OSL_ENSURE( aParserInput.aInputStream.is(),
                        "The stream was successfully opened for reading, the input part must be accessible!\n" );
            if ( !aParserInput.aInputStream.is() )
                throw uno::RuntimeException();

            // get filter
            Reference< XDocumentHandler > xFilter = new XMLVersionListImport( xContext, aVersions );

            // connect parser and filter
            Reference< XParser > xParser = xml::sax::Parser::create(xContext);
            xParser->setDocumentHandler( xFilter );

            // parse
            try
            {
                xParser->parseStream( aParserInput );
            }
            catch( SAXParseException&  ) {}
            catch( SAXException&  )      {}
            catch( io::IOException& )    {}
        }
    }
    catch( uno::Exception& )
    {
        // TODO: error handling
    }

    return aVersions;
}

extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * SAL_CALL
XMLVersionListPersistence_get_implementation(
    css::uno::XComponentContext *,
    css::uno::Sequence<css::uno::Any> const &)
{
    return cppu::acquire(new XMLVersionListPersistence());
}

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