summaryrefslogtreecommitdiff
path: root/unotools/source/misc/mediadescriptor.cxx
blob: c8c2ec98ea911a6048b8719595683ba8823ce92c (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
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
/* -*- 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 <comphelper/docpasswordhelper.hxx>
#include <sal/log.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/mediadescriptor.hxx>
#include <unotools/securityoptions.hxx>
#include <unotools/ucbhelper.hxx>
#include <comphelper/namedvaluecollection.hxx>
#include <comphelper/stillreadwriteinteraction.hxx>

#include <com/sun/star/ucb/XContent.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/XActiveDataSink.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/ucb/InteractiveIOException.hpp>
#include <com/sun/star/ucb/UnsupportedDataSinkException.hpp>
#include <com/sun/star/ucb/CommandFailedException.hpp>
#include <com/sun/star/task/XInteractionAbort.hpp>
#include <com/sun/star/uri/UriReferenceFactory.hpp>
#include <com/sun/star/uri/XUriReference.hpp>
#include <com/sun/star/ucb/PostCommandArgument2.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <officecfg/Office/Common.hxx>
#include <ucbhelper/interceptedinteraction.hxx>
#include <ucbhelper/content.hxx>
#include <ucbhelper/commandenvironment.hxx>
#include <ucbhelper/activedatasink.hxx>
#include <comphelper/processfactory.hxx>
#include <tools/urlobj.hxx>
#include <osl/diagnose.h>

namespace utl {

namespace {

OUString removeFragment(OUString const & uri) {
    css::uno::Reference< css::uri::XUriReference > ref(
        css::uri::UriReferenceFactory::create(
            comphelper::getProcessComponentContext())->
        parse(uri));
    if (ref.is()) {
        ref->clearFragment();
        return ref->getUriReference();
    } else {
        SAL_WARN("unotools.misc", "cannot parse <" << uri << ">");
        return uri;
    }
}

}

const OUString& MediaDescriptor::PROP_ABORTED()
{
    static const OUString sProp("Aborted");
    return sProp;
}

const OUString& MediaDescriptor::PROP_ASTEMPLATE()
{
    static const OUString sProp("AsTemplate");
    return sProp;
}

const OUString& MediaDescriptor::PROP_COMPONENTDATA()
{
    static const OUString sProp("ComponentData");
    return sProp;
}

const OUString& MediaDescriptor::PROP_DOCUMENTSERVICE()
{
    static const OUString sProp("DocumentService");
    return sProp;
}

const OUString& MediaDescriptor::PROP_ENCRYPTIONDATA()
{
    static const OUString sProp("EncryptionData");
    return sProp;
}

const OUString& MediaDescriptor::PROP_FILENAME()
{
    static const OUString sProp("FileName");
    return sProp;
}

const OUString& MediaDescriptor::PROP_FILTERNAME()
{
    static const OUString sProp("FilterName");
    return sProp;
}

const OUString& MediaDescriptor::PROP_FILTERPROVIDER()
{
    static const OUString aProp("FilterProvider");
    return aProp;
}

const OUString& MediaDescriptor::PROP_FILTEROPTIONS()
{
    static const OUString sProp("FilterOptions");
    return sProp;
}

const OUString& MediaDescriptor::PROP_FRAME()
{
    static const OUString sProp("Frame");
    return sProp;
}

const OUString& MediaDescriptor::PROP_FRAMENAME()
{
    static const OUString sProp("FrameName");
    return sProp;
}

const OUString& MediaDescriptor::PROP_HIDDEN()
{
    static const OUString sProp("Hidden");
    return sProp;
}

const OUString& MediaDescriptor::PROP_INPUTSTREAM()
{
    static const OUString sProp("InputStream");
    return sProp;
}

const OUString& MediaDescriptor::PROP_INTERACTIONHANDLER()
{
    static const OUString sProp("InteractionHandler");
    return sProp;
}

const OUString& MediaDescriptor::PROP_AUTHENTICATIONHANDLER()
{
    static const OUString sProp("AuthenticationHandler");
    return sProp;
}

 const OUString& MediaDescriptor::PROP_JUMPMARK()
{
    static const OUString sProp("JumpMark");
    return sProp;
}

const OUString& MediaDescriptor::PROP_MACROEXECUTIONMODE()
{
    static const OUString sProp("MacroExecutionMode");
    return sProp;
}

const OUString& MediaDescriptor::PROP_MEDIATYPE()
{
    static const OUString sProp("MediaType");
    return sProp;
}

const OUString& MediaDescriptor::PROP_MINIMIZED()
{
    static const OUString sProp("Minimized");
    return sProp;
}

const OUString& MediaDescriptor::PROP_NOAUTOSAVE()
{
    static const OUString sProp("NoAutoSave");
    return sProp;
}

const OUString& MediaDescriptor::PROP_OPENNEWVIEW()
{
    static const OUString sProp("OpenNewView");
    return sProp;
}

const OUString& MediaDescriptor::PROP_OUTPUTSTREAM()
{
    static const OUString sProp("OutputStream");
    return sProp;
}

const OUString& MediaDescriptor::PROP_POSTDATA()
{
    static const OUString sProp("PostData");
    return sProp;
}

const OUString& MediaDescriptor::PROP_PREVIEW()
{
    static const OUString sProp("Preview");
    return sProp;
}

const OUString& MediaDescriptor::PROP_READONLY()
{
    static const OUString sProp("ReadOnly");
    return sProp;
}

const OUString& MediaDescriptor::PROP_REFERRER()
{
    static const OUString sProp("Referer");
    return sProp;
}

const OUString& MediaDescriptor::PROP_STATUSINDICATOR()
{
    static const OUString sProp("StatusIndicator");
    return sProp;
}

const OUString& MediaDescriptor::PROP_STREAM()
{
    static const OUString sProp("Stream");
    return sProp;
}

const OUString& MediaDescriptor::PROP_STREAMFOROUTPUT()
{
    static const OUString sProp("StreamForOutput");
    return sProp;
}

const OUString& MediaDescriptor::PROP_TEMPLATENAME()
{
    static const OUString sProp("TemplateName");
    return sProp;
}

const OUString& MediaDescriptor::PROP_TYPENAME()
{
    static const OUString sProp("TypeName");
    return sProp;
}

const OUString& MediaDescriptor::PROP_UCBCONTENT()
{
    static const OUString sProp("UCBContent");
    return sProp;
}

const OUString& MediaDescriptor::PROP_UPDATEDOCMODE()
{
    static const OUString sProp("UpdateDocMode");
    return sProp;
}

const OUString& MediaDescriptor::PROP_URL()
{
    static const OUString sProp("URL");
    return sProp;
}

const OUString& MediaDescriptor::PROP_VERSION()
{
    static const OUString sProp("Version");
    return sProp;
}

const OUString& MediaDescriptor::PROP_DOCUMENTTITLE()
{
    static const OUString sProp("DocumentTitle");
    return sProp;
}

const OUString& MediaDescriptor::PROP_MODEL()
{
    static const OUString sProp("Model");
    return sProp;
}

const OUString& MediaDescriptor::PROP_PASSWORD()
{
    static const OUString sProp("Password");
    return sProp;
}

const OUString& MediaDescriptor::PROP_TITLE()
{
    static const OUString sProp("Title");
    return sProp;
}

const OUString& MediaDescriptor::PROP_SALVAGEDFILE()
{
    static const OUString sProp("SalvagedFile");
    return sProp;
}

const OUString& MediaDescriptor::PROP_VIEWONLY()
{
    static const OUString sProp("ViewOnly");
    return sProp;
}

const OUString& MediaDescriptor::PROP_DOCUMENTBASEURL()
{
    static const OUString sProp("DocumentBaseURL");
    return sProp;
}

MediaDescriptor::MediaDescriptor()
    : SequenceAsHashMap()
{
}

MediaDescriptor::MediaDescriptor(const css::uno::Sequence< css::beans::PropertyValue >& lSource)
    : SequenceAsHashMap(lSource)
{
}

bool MediaDescriptor::isStreamReadOnly() const
{
    static bool READONLY_FALLBACK = false;

    bool bReadOnly = READONLY_FALLBACK;

    // check for explicit readonly state
    const_iterator pIt = find(MediaDescriptor::PROP_READONLY());
    if (pIt != end())
    {
        pIt->second >>= bReadOnly;
        return bReadOnly;
    }

    // streams based on post data are readonly by definition
    pIt = find(MediaDescriptor::PROP_POSTDATA());
    if (pIt != end())
        return true;

    // A XStream capsulate XInputStream and XOutputStream ...
    // If it exists - the file must be open in read/write mode!
    pIt = find(MediaDescriptor::PROP_STREAM());
    if (pIt != end())
        return false;

    // Only file system content provider is able to provide XStream
    // so for this content impossibility to create XStream triggers
    // switch to readonly mode.
    try
    {
        css::uno::Reference< css::ucb::XContent > xContent = getUnpackedValueOrDefault(MediaDescriptor::PROP_UCBCONTENT(), css::uno::Reference< css::ucb::XContent >());
        if (xContent.is())
        {
            css::uno::Reference< css::ucb::XContentIdentifier > xId(xContent->getIdentifier(), css::uno::UNO_QUERY);
            OUString aScheme;
            if (xId.is())
                aScheme = xId->getContentProviderScheme();

            if (aScheme.equalsIgnoreAsciiCase("file"))
                bReadOnly = true;
            else
            {
                ::ucbhelper::Content aContent(xContent,
                                              utl::UCBContentHelper::getDefaultCommandEnvironment(),
                                              comphelper::getProcessComponentContext());
                aContent.getPropertyValue("IsReadOnly") >>= bReadOnly;
            }
        }
    }
    catch(const css::uno::RuntimeException& )
        { throw; }
    catch(const css::uno::Exception&)
        {}

    return bReadOnly;
}

css::uno::Any MediaDescriptor::getComponentDataEntry( const OUString& rName ) const
{
    comphelper::SequenceAsHashMap::const_iterator aPropertyIter = find( PROP_COMPONENTDATA() );
    if( aPropertyIter != end() )
        return comphelper::NamedValueCollection( aPropertyIter->second ).get( rName );
    return css::uno::Any();
}

void MediaDescriptor::setComponentDataEntry( const OUString& rName, const css::uno::Any& rValue )
{
    if( rValue.hasValue() )
    {
        // get or create the 'ComponentData' property entry
        css::uno::Any& rCompDataAny = operator[]( PROP_COMPONENTDATA() );
        // insert the value (retain sequence type, create NamedValue elements by default)
        bool bHasNamedValues = !rCompDataAny.hasValue() || rCompDataAny.has< css::uno::Sequence< css::beans::NamedValue > >();
        bool bHasPropValues = rCompDataAny.has< css::uno::Sequence< css::beans::PropertyValue > >();
        OSL_ENSURE( bHasNamedValues || bHasPropValues, "MediaDescriptor::setComponentDataEntry - incompatible 'ComponentData' property in media descriptor" );
        if( bHasNamedValues || bHasPropValues )
        {
            // insert or overwrite the passed value
            comphelper::SequenceAsHashMap aCompDataMap( rCompDataAny );
            aCompDataMap[ rName ] = rValue;
            // write back the sequence (restore sequence with correct element type)
            rCompDataAny = aCompDataMap.getAsConstAny( bHasPropValues );
        }
    }
    else
    {
        // if an empty Any is passed, clear the entry
        clearComponentDataEntry( rName );
    }
}

void MediaDescriptor::clearComponentDataEntry( const OUString& rName )
{
    comphelper::SequenceAsHashMap::iterator aPropertyIter = find( PROP_COMPONENTDATA() );
    if( aPropertyIter != end() )
    {
        css::uno::Any& rCompDataAny = aPropertyIter->second;
        bool bHasNamedValues = rCompDataAny.has< css::uno::Sequence< css::beans::NamedValue > >();
        bool bHasPropValues = rCompDataAny.has< css::uno::Sequence< css::beans::PropertyValue > >();
        OSL_ENSURE( bHasNamedValues || bHasPropValues, "MediaDescriptor::clearComponentDataEntry - incompatible 'ComponentData' property in media descriptor" );
        if( bHasNamedValues || bHasPropValues )
        {
            // remove the value with the passed name
            comphelper::SequenceAsHashMap aCompDataMap( rCompDataAny );
            aCompDataMap.erase( rName );
            // write back the sequence, or remove it completely if it is empty
            if( aCompDataMap.empty() )
                erase( aPropertyIter );
            else
                rCompDataAny = aCompDataMap.getAsConstAny( bHasPropValues );
        }
    }
}

css::uno::Sequence< css::beans::NamedValue > MediaDescriptor::requestAndVerifyDocPassword(
        comphelper::IDocPasswordVerifier& rVerifier,
        comphelper::DocPasswordRequestType eRequestType,
        const ::std::vector< OUString >* pDefaultPasswords )
{
    css::uno::Sequence< css::beans::NamedValue > aMediaEncData = getUnpackedValueOrDefault(
        PROP_ENCRYPTIONDATA(), css::uno::Sequence< css::beans::NamedValue >() );
    OUString aMediaPassword = getUnpackedValueOrDefault(
        PROP_PASSWORD(), OUString() );
    css::uno::Reference< css::task::XInteractionHandler > xInteractHandler = getUnpackedValueOrDefault(
        PROP_INTERACTIONHANDLER(), css::uno::Reference< css::task::XInteractionHandler >() );
    OUString aDocumentName = getUnpackedValueOrDefault(
        PROP_URL(), OUString() );

    bool bIsDefaultPassword = false;
    css::uno::Sequence< css::beans::NamedValue > aEncryptionData = comphelper::DocPasswordHelper::requestAndVerifyDocPassword(
        rVerifier, aMediaEncData, aMediaPassword, xInteractHandler, aDocumentName, eRequestType, pDefaultPasswords, &bIsDefaultPassword );

    erase( PROP_PASSWORD() );
    erase( PROP_ENCRYPTIONDATA() );

    // insert valid password into media descriptor (but not a default password)
    if( (aEncryptionData.getLength() > 0) && !bIsDefaultPassword )
        (*this)[ PROP_ENCRYPTIONDATA() ] <<= aEncryptionData;

    return aEncryptionData;
}

bool MediaDescriptor::addInputStream()
{
    return impl_addInputStream( true );
}

/*-----------------------------------------------*/
bool MediaDescriptor::addInputStreamOwnLock()
{
    const bool bLock = !utl::ConfigManager::IsAvoidConfig()
        && officecfg::Office::Common::Misc::UseDocumentSystemFileLocking::get();
    return impl_addInputStream(bLock);
}

/*-----------------------------------------------*/
bool MediaDescriptor::impl_addInputStream( bool bLockFile )
{
    // check for an already existing stream item first
    const_iterator pIt = find(MediaDescriptor::PROP_INPUTSTREAM());
    if (pIt != end())
        return true;

    try
    {
        // No stream available - create a new one
        // a) data comes as PostData ...
        pIt = find(MediaDescriptor::PROP_POSTDATA());
        if (pIt != end())
        {
            const css::uno::Any& rPostData = pIt->second;
            css::uno::Reference< css::io::XInputStream > xPostData;
            rPostData >>= xPostData;

            return impl_openStreamWithPostData( xPostData );
        }

        // b) ... or we must get it from the given URL
        OUString sURL = getUnpackedValueOrDefault(MediaDescriptor::PROP_URL(), OUString());
        if (sURL.isEmpty())
            throw css::uno::Exception("Found no URL.",
                    css::uno::Reference< css::uno::XInterface >());

        return impl_openStreamWithURL( removeFragment(sURL), bLockFile );
    }
    catch(const css::uno::Exception& ex)
    {
        SAL_WARN(
            "unotools.misc",
            "invalid MediaDescriptor detected: " << ex.Message);
        return false;
    }
}

bool MediaDescriptor::impl_openStreamWithPostData( const css::uno::Reference< css::io::XInputStream >& _rxPostData )
{
    if ( !_rxPostData.is() )
        throw css::lang::IllegalArgumentException("Found invalid PostData.",
                css::uno::Reference< css::uno::XInterface >(), 1);

    // PostData can't be used in read/write mode!
    (*this)[MediaDescriptor::PROP_READONLY()] <<= true;

    // prepare the environment
    css::uno::Reference< css::task::XInteractionHandler > xInteraction = getUnpackedValueOrDefault(
        MediaDescriptor::PROP_INTERACTIONHANDLER(),
        css::uno::Reference< css::task::XInteractionHandler >());
    css::uno::Reference< css::ucb::XProgressHandler > xProgress;
    ::ucbhelper::CommandEnvironment* pCommandEnv = new ::ucbhelper::CommandEnvironment(xInteraction, xProgress);
    css::uno::Reference< css::ucb::XCommandEnvironment > xCommandEnv(static_cast< css::ucb::XCommandEnvironment* >(pCommandEnv), css::uno::UNO_QUERY);

    // media type
    OUString sMediaType = getUnpackedValueOrDefault(MediaDescriptor::PROP_MEDIATYPE(), OUString());
    if (sMediaType.isEmpty())
    {
        sMediaType = "application/x-www-form-urlencoded";
        (*this)[MediaDescriptor::PROP_MEDIATYPE()] <<= sMediaType;
    }

    // url
    OUString sURL( getUnpackedValueOrDefault( PROP_URL(), OUString() ) );

    css::uno::Reference< css::io::XInputStream > xResultStream;
    try
    {
        // seek PostData stream to the beginning
        css::uno::Reference< css::io::XSeekable > xSeek( _rxPostData, css::uno::UNO_QUERY );
        if ( xSeek.is() )
            xSeek->seek( 0 );

        // a content for the URL
        ::ucbhelper::Content aContent( sURL, xCommandEnv, comphelper::getProcessComponentContext() );

        // use post command
        css::ucb::PostCommandArgument2 aPostArgument;
        aPostArgument.Source = _rxPostData;
        css::uno::Reference< css::io::XActiveDataSink > xSink( new ucbhelper::ActiveDataSink );
        aPostArgument.Sink = xSink;
        aPostArgument.MediaType = sMediaType;
        aPostArgument.Referer = getUnpackedValueOrDefault( PROP_REFERRER(), OUString() );

        OUString sCommandName( "post" );
        aContent.executeCommand( sCommandName, css::uno::makeAny( aPostArgument ) );

        // get result
        xResultStream = xSink->getInputStream();
    }
    catch( const css::uno::Exception& )
    {
    }

    // success?
    if ( !xResultStream.is() )
    {
        OSL_FAIL( "no valid reply to the HTTP-Post" );
        return false;
    }

    (*this)[MediaDescriptor::PROP_INPUTSTREAM()] <<= xResultStream;
    return true;
}

/*-----------------------------------------------*/
bool MediaDescriptor::impl_openStreamWithURL( const OUString& sURL, bool bLockFile )
{
    OUString referer(getUnpackedValueOrDefault(PROP_REFERRER(), OUString()));
    if (SvtSecurityOptions().isUntrustedReferer(referer)) {
        return false;
    }

    // prepare the environment
    css::uno::Reference< css::task::XInteractionHandler > xOrgInteraction = getUnpackedValueOrDefault(
        MediaDescriptor::PROP_INTERACTIONHANDLER(),
        css::uno::Reference< css::task::XInteractionHandler >());

    css::uno::Reference< css::task::XInteractionHandler > xAuthenticationInteraction = getUnpackedValueOrDefault(
        MediaDescriptor::PROP_AUTHENTICATIONHANDLER(),
        css::uno::Reference< css::task::XInteractionHandler >());

    comphelper::StillReadWriteInteraction* pInteraction = new comphelper::StillReadWriteInteraction(xOrgInteraction,xAuthenticationInteraction);
    css::uno::Reference< css::task::XInteractionHandler > xInteraction(static_cast< css::task::XInteractionHandler* >(pInteraction), css::uno::UNO_QUERY);

    css::uno::Reference< css::ucb::XProgressHandler > xProgress;
    ::ucbhelper::CommandEnvironment* pCommandEnv = new ::ucbhelper::CommandEnvironment(xInteraction, xProgress);
    css::uno::Reference< css::ucb::XCommandEnvironment > xCommandEnv(static_cast< css::ucb::XCommandEnvironment* >(pCommandEnv), css::uno::UNO_QUERY);

    // try to create the content
    // no content -> no stream => return immediately with FALSE
    ::ucbhelper::Content                      aContent;
    css::uno::Reference< css::ucb::XContent > xContent;
    try
    {
        aContent = ::ucbhelper::Content(sURL, xCommandEnv, comphelper::getProcessComponentContext());
        xContent = aContent.get();
    }
    catch(const css::uno::RuntimeException&)
        { throw; }
    catch(const css::ucb::ContentCreationException& e)
        {
            SAL_WARN(
                "unotools.misc",
                "caught ContentCreationException \"" << e.Message
                    << "\" while opening <" << sURL << ">");
            return false; // TODO error handling
        }
    catch(const css::uno::Exception& e)
        {
            SAL_WARN(
                "unotools.misc",
                "caught Exception \"" << e.Message << "\" while opening <"
                    << sURL << ">");
            return false; // TODO error handling
        }

    // try to open the file in read/write mode
    // (if its allowed to do so).
    // But handle errors in a "hidden mode". Because
    // we try it readonly later - if read/write is not an option.
    css::uno::Reference< css::io::XStream >      xStream;
    css::uno::Reference< css::io::XInputStream > xInputStream;

    bool bReadOnly = false;
    bool bModeRequestedExplicitly = false;
    const_iterator pIt = find(MediaDescriptor::PROP_READONLY());
    if (pIt != end())
    {
        pIt->second >>= bReadOnly;
        bModeRequestedExplicitly = true;
    }

    if ( !bReadOnly && bLockFile )
    {
        try
        {
            // TODO: use "special" still interaction to suppress error messages
            xStream = aContent.openWriteableStream();
            if (xStream.is())
                xInputStream = xStream->getInputStream();
        }
        catch(const css::uno::RuntimeException&)
            { throw; }
        catch(const css::uno::Exception& e)
            {
                // ignore exception, if reason was problem reasoned on
                // open it in WRITEABLE mode! Then we try it READONLY
                // later a second time.
                // All other errors must be handled as real error an
                // break this method.
                if (!pInteraction->wasWriteError() || bModeRequestedExplicitly)
                {
                    SAL_WARN(
                        "unotools.misc",
                        "caught Exception \"" << e.Message
                            << "\" while opening <" << sURL << ">");
                    // If the protocol is webdav, then we need to treat the stream as readonly, even if the
                    // operation was requested as read/write explicitly (the WebDAV UCB implementation is monodirectional
                    // read or write not both at the same time).
                    if ( !INetURLObject( sURL ).isAnyKnownWebDAVScheme() )
                        return false;
                }
                xStream.clear();
                xInputStream.clear();
            }
    }

    // If opening of the stream in read/write mode was not allowed
    // or failed by an error - we must try it in readonly mode.
    if (!xInputStream.is())
    {
        OUString aScheme;

        try
        {
            css::uno::Reference< css::ucb::XContentIdentifier > xContId(
                aContent.get().is() ? aContent.get()->getIdentifier() : nullptr );

            if ( xContId.is() )
                aScheme = xContId->getContentProviderScheme();

            // Only file system content provider is able to provide XStream
            // so for this content impossibility to create XStream triggers
            // switch to readonly mode in case of opening with locking on
            if( bLockFile && aScheme.equalsIgnoreAsciiCase("file") )
                bReadOnly = true;
            else
            {
                bool bRequestReadOnly = bReadOnly;
                aContent.getPropertyValue("IsReadOnly") >>= bReadOnly;
                if ( bReadOnly && !bRequestReadOnly && bModeRequestedExplicitly )
                        return false; // the document is explicitly requested with WRITEABLE mode
            }
        }
        catch(const css::uno::RuntimeException&)
            { throw; }
        catch(const css::uno::Exception&)
            { /* no error handling if IsReadOnly property does not exist for UCP */ }

        if ( bReadOnly )
               (*this)[MediaDescriptor::PROP_READONLY()] <<= bReadOnly;

        pInteraction->resetInterceptions();
        pInteraction->resetErrorStates();
        try
        {
            // all the contents except file-URLs should be opened as usual
            if ( bLockFile || !aScheme.equalsIgnoreAsciiCase("file") )
                xInputStream = aContent.openStream();
            else
                xInputStream = aContent.openStreamNoLock();
        }
        catch(const css::uno::RuntimeException&)
        {
            throw;
        }
        catch(const css::uno::Exception& e)
        {
            SAL_INFO(
                "unotools.misc",
                "caught Exception \"" << e.Message << "\" while opening <"
                    << sURL << ">");
            return false;
        }
    }

    // add streams to the descriptor
    if (xContent.is())
        (*this)[MediaDescriptor::PROP_UCBCONTENT()] <<= xContent;
    if (xStream.is())
        (*this)[MediaDescriptor::PROP_STREAM()] <<= xStream;
    if (xInputStream.is())
        (*this)[MediaDescriptor::PROP_INPUTSTREAM()] <<= xInputStream;

    // At least we need an input stream. The r/w stream is optional ...
    return xInputStream.is();
}

} // namespace comphelper

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