xref: /trunk/main/sfx2/source/doc/objmisc.cxx (revision fe4add9e)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_sfx2.hxx"
26 
27 #ifndef _INETMSG_HXX //autogen
28 #include <svl/inetmsg.hxx>
29 #endif
30 #include <tools/diagnose_ex.h>
31 #include <svl/eitem.hxx>
32 #include <svl/stritem.hxx>
33 #include <svl/intitem.hxx>
34 #include <svtools/svparser.hxx> // SvKeyValue
35 #include <vos/mutex.hxx>
36 #include <cppuhelper/exc_hlp.hxx>
37 
38 #include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
39 #include <com/sun/star/document/XDocumentProperties.hpp>
40 #include <com/sun/star/document/UpdateDocMode.hpp>
41 #include <com/sun/star/script/XTypeConverter.hpp>
42 #include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
43 #include <com/sun/star/script/FinishEngineEvent.hpp>
44 #include <com/sun/star/script/InterruptReason.hpp>
45 #include <com/sun/star/script/XEngineListener.hpp>
46 #include <com/sun/star/script/XDebugging.hpp>
47 #ifndef _COM_SUN_STAR_SCRIPT_XINVOKATION_HPP_
48 #include <com/sun/star/script/XInvocation.hpp>
49 #endif
50 #include <com/sun/star/script/ContextInformation.hpp>
51 #include <com/sun/star/script/FinishReason.hpp>
52 #include <com/sun/star/script/XEngine.hpp>
53 #include <com/sun/star/script/InterruptEngineEvent.hpp>
54 #include <com/sun/star/script/XLibraryAccess.hpp>
55 #include <com/sun/star/document/MacroExecMode.hpp>
56 #include <com/sun/star/document/XScriptInvocationContext.hpp>
57 #include <com/sun/star/embed/EmbedStates.hpp>
58 #include <com/sun/star/embed/XEmbedPersist.hpp>
59 #include <com/sun/star/util/XModifiable.hpp>
60 #include <com/sun/star/container/XChild.hpp>
61 #include <com/sun/star/ucb/XSimpleFileAccess.hpp>
62 
63 
64 #include <com/sun/star/script/provider/XScript.hpp>
65 #include <com/sun/star/script/provider/XScriptProvider.hpp>
66 #include <com/sun/star/script/provider/XScriptProviderSupplier.hpp>
67 
68 #ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
69 #include <toolkit/helper/vclunohelper.hxx>
70 #endif
71 
72 #include <com/sun/star/uno/Reference.h>
73 #include <com/sun/star/uno/Any.h>
74 #include <com/sun/star/ucb/XContent.hpp>
75 #include <com/sun/star/task/ErrorCodeRequest.hpp>
76 #include <unotools/securityoptions.hxx>
77 
78 #include "com/sun/star/uri/XUriReferenceFactory.hpp"
79 #include <com/sun/star/uri/XVndSunStarScriptUrlReference.hpp>
80 
81 #include <comphelper/processfactory.hxx>
82 #include <comphelper/componentcontext.hxx>
83 #include <comphelper/configurationhelper.hxx>
84 
85 #include <com/sun/star/security/XDocumentDigitalSignatures.hpp>
86 #include <com/sun/star/task/DocumentMacroConfirmationRequest.hpp>
87 #include <com/sun/star/task/InteractionClassification.hpp>
88 #include <com/sun/star/frame/XModel.hpp>
89 
90 using namespace ::com::sun::star;
91 using namespace ::com::sun::star::uno;
92 using namespace ::com::sun::star::ucb;
93 using namespace ::com::sun::star::document;
94 using namespace ::com::sun::star::frame;
95 using namespace ::com::sun::star::script;
96 using namespace ::com::sun::star::script::provider;
97 using namespace ::com::sun::star::container;
98 #include <basic/sbuno.hxx>
99 #include <basic/sbstar.hxx>
100 #ifndef _SB_BASMGR_HXX
101 #include <basic/basmgr.hxx>
102 #endif
103 #ifndef _VCL_MSGBOX_HXX
104 #include <vcl/msgbox.hxx>
105 #endif
106 #include <basic/sbx.hxx>
107 #include <svtools/sfxecode.hxx>
108 #include <svtools/ehdl.hxx>
109 
110 #include <unotools/pathoptions.hxx>
111 #include <unotools/ucbhelper.hxx>
112 #include <tools/inetmime.hxx>
113 #include <tools/urlobj.hxx>
114 #include <svl/inettype.hxx>
115 #include <svl/sharecontrolfile.hxx>
116 #include <osl/file.hxx>
117 #include <rtl/bootstrap.hxx>
118 #include <vcl/svapp.hxx>
119 #include <framework/interaction.hxx>
120 #include <framework/documentundoguard.hxx>
121 #include <comphelper/interaction.hxx>
122 #include <comphelper/storagehelper.hxx>
123 #include <comphelper/documentconstants.hxx>
124 
125 #include <sfx2/signaturestate.hxx>
126 #include <sfx2/app.hxx>
127 #include "appdata.hxx"
128 #include <sfx2/request.hxx>
129 #include <sfx2/bindings.hxx>
130 #include "sfx2/sfxresid.hxx"
131 #include <sfx2/docfile.hxx>
132 #include <sfx2/docfilt.hxx>
133 #include <sfx2/objsh.hxx>
134 #include "objshimp.hxx"
135 #include <sfx2/event.hxx>
136 #include "fltfnc.hxx"
137 #include <sfx2/sfx.hrc>
138 #include <sfx2/dispatch.hxx>
139 #include <sfx2/viewfrm.hxx>
140 #include <sfx2/viewsh.hxx>
141 #include <sfx2/ctrlitem.hxx>
142 #include "arrdecl.hxx"
143 #include <sfx2/module.hxx>
144 #include <sfx2/docfac.hxx>
145 #include "helper.hxx"
146 #include "doc.hrc"
147 #include "workwin.hxx"
148 #include "helpid.hrc"
149 #include "../appl/app.hrc"
150 #include <sfx2/sfxdlg.hxx>
151 #include "appbaslib.hxx"
152 #include <openflag.hxx> // SFX_STREAM_READWRITE
153 
154 #define C2S(cChar) String::CreateFromAscii( cChar )
155 
156 using namespace ::com::sun::star;
157 
158 // class SfxHeaderAttributes_Impl ----------------------------------------
159 
160 class SfxHeaderAttributes_Impl : public SvKeyValueIterator
161 {
162 private:
163 	SfxObjectShell* pDoc;
164 	SvKeyValueIteratorRef xIter;
165 	sal_Bool bAlert;
166 
167 public:
168 	SfxHeaderAttributes_Impl( SfxObjectShell* pSh ) :
169 		SvKeyValueIterator(), pDoc( pSh ),
170 		xIter( pSh->GetMedium()->GetHeaderAttributes_Impl() ),
171 		bAlert( sal_False ) {}
172 
173 	virtual sal_Bool GetFirst( SvKeyValue& rKV ) { return xIter->GetFirst( rKV ); }
174 	virtual sal_Bool GetNext( SvKeyValue& rKV ) { return xIter->GetNext( rKV ); }
175 	virtual void Append( const SvKeyValue& rKV );
176 
177 	void ClearForSourceView() { xIter = new SvKeyValueIterator; bAlert = sal_False; }
178 	void SetAttributes();
179 	void SetAttribute( const SvKeyValue& rKV );
180 };
181 
182 //=========================================================================
183 
184 sal_uInt16 __READONLY_DATA aTitleMap_Impl[3][2] =
185 {
186 								//	local				remote
187 	/*	SFX_TITLE_CAPTION	*/	{ 	SFX_TITLE_FILENAME, SFX_TITLE_TITLE },
188 	/*	SFX_TITLE_PICKLIST	*/	{ 	32,					SFX_TITLE_FULLNAME },
189 	/*	SFX_TITLE_HISTORY	*/	{ 	32,					SFX_TITLE_FULLNAME }
190 };
191 
192 //=========================================================================
193 
194 void SfxObjectShell::AbortImport()
195 {
196 	pImp->bIsAbortingImport = sal_True;
197 }
198 
199 //-------------------------------------------------------------------------
200 
201 sal_Bool SfxObjectShell::IsAbortingImport() const
202 {
203 	return pImp->bIsAbortingImport;
204 }
205 
206 //-------------------------------------------------------------------------
207 
208 uno::Reference<document::XDocumentProperties>
209 SfxObjectShell::getDocProperties()
210 {
211     uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
212         GetModel(), uno::UNO_QUERY_THROW);
213     uno::Reference<document::XDocumentProperties> xDocProps(
214         xDPS->getDocumentProperties());
215     DBG_ASSERT(xDocProps.is(),
216         "SfxObjectShell: model has no DocumentProperties");
217     return xDocProps;
218 }
219 
220 //-------------------------------------------------------------------------
221 
222 void SfxObjectShell::DoFlushDocInfo()
223 {
224 }
225 
226 //-------------------------------------------------------------------------
227 
228 // Note: the only thing that calls this is the modification event handler
229 // that is installed at the XDocumentProperties
230 void SfxObjectShell::FlushDocInfo()
231 {
232     if ( IsLoading() )
233         return;
234 
235 	SetModified(sal_True);
236     uno::Reference<document::XDocumentProperties> xDocProps(getDocProperties());
237     DoFlushDocInfo(); // call template method
238     ::rtl::OUString url(xDocProps->getAutoloadURL());
239     sal_Int32 delay(xDocProps->getAutoloadSecs());
240     SetAutoLoad( INetURLObject(url), delay * 1000,
241                  (delay > 0) || url.getLength() );
242 /*
243 	// bitte beachten:
244 	// 1. Titel in DocInfo aber nicht am Doc (nach HTML-Import)
245 	// 	=> auch am Doc setzen
246 	// 2. Titel in DocInfo leer (Briefumschlagsdruck)
247 	//	=> nicht am Doc setzen, da sonst "unbenanntX" daraus wird
248 	String aDocInfoTitle = GetDocInfo().GetTitle();
249 	if ( aDocInfoTitle.Len() )
250 		SetTitle( aDocInfoTitle );
251 	else
252 	{
253 		pImp->aTitle.Erase();
254 		SetNamedVisibility_Impl();
255     	if ( GetMedium() )
256     	{
257         	SfxShell::SetName( GetTitle(SFX_TITLE_APINAME) );
258         	Broadcast( SfxSimpleHint(SFX_HINT_TITLECHANGED) );
259     	}
260     }*/
261 }
262 
263 //-------------------------------------------------------------------------
264 
265 void SfxObjectShell::SetError( sal_uInt32 lErr, const ::rtl::OUString& aLogMessage )
266 {
267 	if(pImp->lErr==ERRCODE_NONE)
268     {
269 		pImp->lErr=lErr;
270 
271         if( lErr != ERRCODE_NONE && aLogMessage.getLength() )
272             AddLog( aLogMessage );
273     }
274 }
275 
276 //-------------------------------------------------------------------------
277 
278 sal_uInt32 SfxObjectShell::GetError() const
279 {
280 	return ERRCODE_TOERROR(GetErrorCode());
281 }
282 
283 //-------------------------------------------------------------------------
284 
285 sal_uInt32 SfxObjectShell::GetErrorCode() const
286 {
287 	sal_uInt32 lError=pImp->lErr;
288 	if(!lError && GetMedium())
289 		lError=GetMedium()->GetErrorCode();
290 	return lError;
291 }
292 
293 //-------------------------------------------------------------------------
294 
295 void SfxObjectShell::ResetError()
296 {
297     if( pImp->lErr != ERRCODE_NONE )
298         AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Resetting Error." ) ) );
299 
300 	pImp->lErr=0;
301 	SfxMedium * pMed = GetMedium();
302 	if( pMed )
303 		pMed->ResetError();
304 }
305 
306 //-------------------------------------------------------------------------
307 
308 sal_Bool SfxObjectShell::IsTemplate() const
309 {
310 	return pImp->bIsTemplate;
311 }
312 
313 //-------------------------------------------------------------------------
314 
315 void SfxObjectShell::SetTemplate(sal_Bool bIs)
316 {
317 	pImp->bIsTemplate=bIs;
318 	SfxFilterMatcher aMatcher( GetFactory().GetFactoryName() );
319 	SfxFilterMatcherIter aIter( &aMatcher, SFX_FILTER_TEMPLATEPATH );
320 	SfxMedium* pMed = GetMedium();
321 	if( pMed ) pMed->SetFilter( aIter.First() );
322 }
323 
324 //-------------------------------------------------------------------------
325 
326 void SfxObjectShell::EnableSetModified( sal_Bool bEnable )
327 {
328 #ifdef DBG_UTIL
329 	if ( bEnable == pImp->m_bEnableSetModified )
330 		DBG_WARNING( "SFX_PERSIST: EnableSetModified called twice with the same value" );
331 #endif
332 	pImp->m_bEnableSetModified = bEnable;
333 }
334 
335 //-------------------------------------------------------------------------
336 
337 sal_Bool SfxObjectShell::IsEnableSetModified() const
338 {
339     return pImp->m_bEnableSetModified && !IsReadOnly();
340 }
341 
342 //-------------------------------------------------------------------------
343 
344 sal_Bool SfxObjectShell::IsModified()
345 {
346     if ( pImp->m_bIsModified )
347         return sal_True;
348 
349     if ( !pImp->m_xDocStorage.is() || IsReadOnly() )
350     {
351         // if the document still has no storage and is not set to be modified explicitly it is not modified
352         // a readonly document is also not modified
353 
354         return sal_False;
355     }
356 
357     uno::Sequence < ::rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();
358     for ( sal_Int32 n=0; n<aNames.getLength(); n++ )
359     {
360         uno::Reference < embed::XEmbeddedObject > xObj = GetEmbeddedObjectContainer().GetEmbeddedObject( aNames[n] );
361         OSL_ENSURE( xObj.is(), "An empty entry in the embedded objects list!\n" );
362         if ( xObj.is() )
363         {
364             try
365             {
366                 sal_Int32 nState = xObj->getCurrentState();
367                 if ( nState != embed::EmbedStates::LOADED )
368                 {
369                     uno::Reference< util::XModifiable > xModifiable( xObj->getComponent(), uno::UNO_QUERY );
370                     if ( xModifiable.is() && xModifiable->isModified() )
371                         return sal_True;
372                 }
373             }
374             catch( uno::Exception& )
375             {}
376         }
377     }
378 
379     return sal_False;
380 }
381 
382 //-------------------------------------------------------------------------
383 
384 void SfxObjectShell::SetModified( sal_Bool bModifiedP )
385 {
386 #ifdef DBG_UTIL
387 	if ( !bModifiedP && !IsEnableSetModified() )
388 		DBG_WARNING( "SFX_PERSIST: SetModified( sal_False ), although IsEnableSetModified() == sal_False" );
389 #endif
390 
391 	if( !IsEnableSetModified() )
392 		return;
393 
394 	if( pImp->m_bIsModified != bModifiedP )
395 	{
396 		pImp->m_bIsModified = bModifiedP;
397 		ModifyChanged();
398 	}
399 }
400 
401 //-------------------------------------------------------------------------
402 
403 void SfxObjectShell::ModifyChanged()
404 {
405 	if ( pImp->bClosing )
406 		// SetModified aus dem dispose des Models!
407 		return;
408 
409 	{DBG_CHKTHIS(SfxObjectShell, 0);}
410 
411     SfxViewFrame* pViewFrame = SfxViewFrame::Current();
412     if ( pViewFrame )
413         pViewFrame->GetBindings().Invalidate( SID_SAVEDOCS );
414 
415     Invalidate( SID_SIGNATURE );
416     Invalidate( SID_MACRO_SIGNATURE );
417 	Broadcast( SfxSimpleHint( SFX_HINT_TITLECHANGED ) );	// xmlsec05, signed state might change in title...
418 
419     SFX_APP()->NotifyEvent( SfxEventHint( SFX_EVENT_MODIFYCHANGED, GlobalEventConfig::GetEventName(STR_EVENT_MODIFYCHANGED), this ) );
420 }
421 
422 //-------------------------------------------------------------------------
423 
424 sal_Bool SfxObjectShell::IsReadOnlyUI() const
425 
426 /* 	[Beschreibung]
427 
428 	Liefert sal_True, wenn das Dokument fuer die UI wie r/o behandelt werden
429 	soll. Dieses ist unabhaengig vom tatsaechlichen r/o, welches per
430 	<IsReadOnly()> erfragbar ist.
431 */
432 
433 {
434 	return pImp->bReadOnlyUI;
435 }
436 
437 //-------------------------------------------------------------------------
438 
439 sal_Bool SfxObjectShell::IsReadOnlyMedium() const
440 
441 /* 	[Beschreibung]
442 
443 	Liefert sal_True, wenn das Medium r/o ist bzw. r/o geoeffnet wurde.
444 */
445 
446 {
447 	if ( !pMedium )
448 		return sal_True;
449 	return pMedium->IsReadOnly();
450 }
451 
452 //-------------------------------------------------------------------------
453 
454 void SfxObjectShell::SetReadOnlyUI( sal_Bool bReadOnly )
455 
456 /* 	[Beschreibung]
457 
458 	Schaltet das Dokument in einen r/o bzw. r/w Zustand ohne es neu
459 	zu laden und ohne die Open-Modi des Mediums zu aendern.
460 */
461 
462 {
463 	sal_Bool bWasRO = IsReadOnly();
464 	pImp->bReadOnlyUI = bReadOnly;
465 	if ( bWasRO != IsReadOnly() )
466 	{
467 		Broadcast( SfxSimpleHint(SFX_HINT_MODECHANGED) );
468 		//if ( pImp->pDocInfo )
469 		//	pImp->pDocInfo->SetReadOnly( IsReadOnly() );
470 	}
471 }
472 
473 //-------------------------------------------------------------------------
474 
475 void SfxObjectShell::SetReadOnly()
476 {
477 	// Let the document be completely readonly, means that the
478 	// medium open mode is adjusted accordingly, and the write lock
479 	// on the file is removed.
480 
481  	if ( pMedium && !IsReadOnlyMedium() )
482     {
483         sal_Bool bWasROUI = IsReadOnly();
484 
485 		pMedium->UnlockFile( sal_False );
486 
487         // the storage-based mediums are already based on the temporary file
488         // so UnlockFile has already closed the locking stream
489         if ( !pMedium->HasStorage_Impl() && IsLoadingFinished() )
490             pMedium->CloseInStream();
491 
492         pMedium->SetOpenMode( SFX_STREAM_READONLY, pMedium->IsDirect(), sal_True );
493         pMedium->GetItemSet()->Put( SfxBoolItem( SID_DOC_READONLY, sal_True ) );
494 
495         if ( !bWasROUI )
496             Broadcast( SfxSimpleHint(SFX_HINT_MODECHANGED) );
497     }
498 }
499 //-------------------------------------------------------------------------
500 
501 sal_Bool SfxObjectShell::IsReadOnly() const
502 {
503 	return pImp->bReadOnlyUI || IsReadOnlyMedium();
504 }
505 
506 //-------------------------------------------------------------------------
507 
508 sal_Bool SfxObjectShell::IsInModalMode() const
509 {
510     return pImp->bModalMode || pImp->bRunningMacro;
511 }
512 
513 //<!--Added by PengYunQuan for Validity Cell Range Picker
514 sal_Bool SfxObjectShell::AcceptStateUpdate() const
515 {
516 	return !IsInModalMode();
517 }
518 //-->Added by PengYunQuan for Validity Cell Range Picker
519 
520 //-------------------------------------------------------------------------
521 
522 sal_Bool SfxObjectShell::HasModalViews() const
523 {
524 	SfxViewFrame* pFrame = SfxViewFrame::GetFirst( this );
525 	while( pFrame )
526 	{
527 		if ( pFrame->IsInModalMode() )
528 			return sal_True;
529 
530 		pFrame = SfxViewFrame::GetNext( *pFrame, this );
531 	}
532 
533 	return sal_False;
534 }
535 
536 //-------------------------------------------------------------------------
537 
538 void SfxObjectShell::SetMacroMode_Impl( sal_Bool bModal )
539 {
540     if ( !pImp->bRunningMacro != !bModal )
541 	{
542         pImp->bRunningMacro = bModal;
543 		Broadcast( SfxSimpleHint( SFX_HINT_MODECHANGED ) );
544 	}
545 }
546 
547 //-------------------------------------------------------------------------
548 
549 void SfxObjectShell::SetModalMode_Impl( sal_Bool bModal )
550 {
551 	// nur Broadcasten wenn modifiziert, sonst ggf. Endlosrekursion
552 	if ( !pImp->bModalMode != !bModal )
553 	{
554 		// zentral mitz"ahlen
555 		sal_uInt16 &rDocModalCount = SFX_APP()->Get_Impl()->nDocModalMode;
556 		if ( bModal )
557 			++rDocModalCount;
558 		else
559 			--rDocModalCount;
560 
561 		// umschalten
562 		pImp->bModalMode = bModal;
563 		Broadcast( SfxSimpleHint( SFX_HINT_MODECHANGED ) );
564 	}
565 }
566 
567 //--------------------------------------------------------------------
568 sal_Bool SfxObjectShell::SwitchToShared( sal_Bool bShared, sal_Bool bSave )
569 {
570     sal_Bool bResult = sal_True;
571 
572     if ( bShared != IsDocShared() )
573     {
574         ::rtl::OUString aOrigURL = GetMedium()->GetURLObject().GetMainURL( INetURLObject::NO_DECODE );
575 
576         if ( !aOrigURL.getLength() && bSave )
577         {
578             // this is a new document, let it be stored before switching to the shared mode;
579             // the storing should be done without shared flag, since it is possible that the
580             // target location does not allow to create sharing control file;
581             // the shared flag will be set later after creation of sharing control file
582             SfxViewFrame* pViewFrame = SfxViewFrame::GetFirst( this );
583 
584             if ( pViewFrame )
585             {
586                 // TODO/LATER: currently the application guards against the reentrance problem
587 				const SfxPoolItem* pItem = pViewFrame->GetBindings().ExecuteSynchron( HasName() ? SID_SAVEDOC : SID_SAVEASDOC );
588                 SfxBoolItem* pResult = PTR_CAST( SfxBoolItem, pItem );
589                 bResult = ( pResult && pResult->GetValue() );
590                 if ( bResult )
591                     aOrigURL = GetMedium()->GetURLObject().GetMainURL( INetURLObject::NO_DECODE );
592             }
593         }
594 
595         sal_Bool bOldValue = HasSharedXMLFlagSet();
596         SetSharedXMLFlag( bShared );
597 
598         sal_Bool bRemoveEntryOnError = sal_False;
599         if ( bResult && bShared )
600         {
601             try
602             {
603                 ::svt::ShareControlFile aControlFile( aOrigURL );
604                 aControlFile.InsertOwnEntry();
605                 bRemoveEntryOnError = sal_True;
606             }
607             catch( uno::Exception& )
608             {
609                 bResult = sal_False;
610             }
611         }
612 
613         if ( bResult && bSave )
614         {
615             SfxViewFrame* pViewFrame = SfxViewFrame::GetFirst( this );
616 
617             if ( pViewFrame )
618             {
619                 // TODO/LATER: currently the application guards against the reentrance problem
620                 SetModified( sal_True ); // the modified flag has to be set to let the document be stored with the shared flag
621 				const SfxPoolItem* pItem = pViewFrame->GetBindings().ExecuteSynchron( HasName() ? SID_SAVEDOC : SID_SAVEASDOC );
622                 SfxBoolItem* pResult = PTR_CAST( SfxBoolItem, pItem );
623                 bResult = ( pResult && pResult->GetValue() );
624             }
625         }
626 
627         if ( bResult )
628         {
629             // TODO/LATER: Is it possible that the following calls fail?
630             if ( bShared )
631             {
632                 pImp->m_aSharedFileURL = aOrigURL;
633                 GetMedium()->SwitchDocumentToTempFile();
634             }
635             else
636             {
637                 ::rtl::OUString aTempFileURL = pMedium->GetURLObject().GetMainURL( INetURLObject::NO_DECODE );
638                 GetMedium()->SwitchDocumentToFile( GetSharedFileURL() );
639                 pImp->m_aSharedFileURL = ::rtl::OUString();
640 
641                 // now remove the temporary file the document was based on
642                 ::utl::UCBContentHelper::Kill( aTempFileURL );
643 
644                 try
645                 {
646                     // aOrigURL can not be used since it contains an old value
647                     ::svt::ShareControlFile aControlFile( GetMedium()->GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) );
648                     aControlFile.RemoveFile();
649                 }
650                 catch( uno::Exception& )
651                 {
652                 }
653             }
654         }
655         else
656         {
657             // the saving has failed!
658             if ( bRemoveEntryOnError )
659             {
660                 try
661                 {
662                     ::svt::ShareControlFile aControlFile( aOrigURL );
663                     aControlFile.RemoveEntry();
664                 }
665                 catch( uno::Exception& )
666                 {}
667             }
668 
669             SetSharedXMLFlag( bOldValue );
670         }
671     }
672     else
673         bResult = sal_False; // the second switch to the same mode
674 
675     if ( bResult )
676         SetTitle( String() );
677 
678     return bResult;
679 }
680 
681 //--------------------------------------------------------------------
682 
683 void SfxObjectShell::DisconnectFromShared()
684 {
685     if ( IsDocShared() )
686     {
687         if ( pMedium && pMedium->GetStorage().is() )
688         {
689             // set medium to noname
690             pMedium->SetName( String(), sal_True );
691             pMedium->Init_Impl();
692 
693             // drop resource
694             SetNoName();
695             InvalidateName();
696 
697             // untitled document must be based on temporary storage
698             // the medium should not dispose the storage in this case
699             if ( pMedium->GetStorage() == GetStorage() )
700                 ConnectTmpStorage_Impl( pMedium->GetStorage(), pMedium );
701 
702             pMedium->Close();
703             FreeSharedFile();
704 
705             SfxMedium* pTmpMedium = pMedium;
706             ForgetMedium();
707             if( !DoSaveCompleted( pTmpMedium ) )
708                 SetError( ERRCODE_IO_GENERAL, ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ) );
709             else
710             {
711                 // the medium should not dispose the storage, DoSaveCompleted() has let it to do so
712                 pMedium->CanDisposeStorage_Impl( sal_False );
713             }
714 
715             pMedium->GetItemSet()->ClearItem( SID_DOC_READONLY );
716             pMedium->SetOpenMode( SFX_STREAM_READWRITE, sal_True, sal_True );
717 
718             SetTitle( String() );
719         }
720     }
721 }
722 
723 //--------------------------------------------------------------------
724 
725 void SfxObjectShell::FreeSharedFile()
726 {
727     if ( pMedium )
728         FreeSharedFile( pMedium->GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) );
729 }
730 
731 //--------------------------------------------------------------------
732 void SfxObjectShell::FreeSharedFile( const ::rtl::OUString& aTempFileURL )
733 {
734     SetSharedXMLFlag( sal_False );
735 
736     if ( IsDocShared() && aTempFileURL.getLength()
737       && !::utl::UCBContentHelper::EqualURLs( aTempFileURL, GetSharedFileURL() ) )
738     {
739         if ( pImp->m_bAllowShareControlFileClean )
740         {
741             try
742             {
743                 ::svt::ShareControlFile aControlFile( GetSharedFileURL() );
744                 aControlFile.RemoveEntry();
745             }
746             catch( uno::Exception& )
747             {
748             }
749         }
750 
751         // the cleaning is forbidden only once
752         pImp->m_bAllowShareControlFileClean = sal_True;
753 
754         // now remove the temporary file the document is based currently on
755         ::utl::UCBContentHelper::Kill( aTempFileURL );
756 
757         pImp->m_aSharedFileURL = ::rtl::OUString();
758     }
759 }
760 
761 //--------------------------------------------------------------------
762 void SfxObjectShell::DoNotCleanShareControlFile()
763 {
764     pImp->m_bAllowShareControlFileClean = sal_False;
765 }
766 
767 //--------------------------------------------------------------------
768 void SfxObjectShell::SetSharedXMLFlag( sal_Bool bFlag ) const
769 {
770     pImp->m_bSharedXMLFlag = bFlag;
771 }
772 
773 //--------------------------------------------------------------------
774 sal_Bool SfxObjectShell::HasSharedXMLFlagSet() const
775 {
776     return pImp->m_bSharedXMLFlag;
777 }
778 
779 //--------------------------------------------------------------------
780 
781 sal_Bool SfxObjectShell::IsDocShared() const
782 {
783     return ( pImp->m_aSharedFileURL.getLength() > 0 );
784 }
785 
786 //--------------------------------------------------------------------
787 
788 ::rtl::OUString SfxObjectShell::GetSharedFileURL() const
789 {
790     return pImp->m_aSharedFileURL;
791 }
792 
793 //--------------------------------------------------------------------
794 
795 Size SfxObjectShell::GetFirstPageSize()
796 {
797     return GetVisArea(ASPECT_THUMBNAIL).GetSize();
798 }
799 
800 
801 //--------------------------------------------------------------------
802 
803 IndexBitSet& SfxObjectShell::GetNoSet_Impl()
804 {
805 	return pImp->aBitSet;
806 }
807 
808 //--------------------------------------------------------------------
809 // changes the title of the document
810 
811 void SfxObjectShell::SetTitle
812 (
813 	const String& rTitle		// der neue Titel des Dokuments
814 )
815 
816 /*	[Beschreibung]
817 
818 	Mit dieser Methode kann der Titel des Dokuments gesetzt werden.
819 	Dieser entspricht initial dem kompletten Dateinamen. Ein Setzen
820 	des Titels wirkt jedoch nicht zurück auf den Dateinamen; er wird
821 	jedoch in den Caption-Bars der MDI-Fenster angezeigt.
822 */
823 
824 {
825 	DBG_CHKTHIS(SfxObjectShell, 0);
826 
827 	// nix zu tun?
828 	if ( ( ( HasName() && pImp->aTitle == rTitle )
829 		|| ( !HasName() && GetTitle() == rTitle ) )
830 	  && !IsDocShared() )
831 		return;
832 
833 	SfxApplication *pSfxApp = SFX_APP();
834 #if 0
835 	// wird 'unbenannt#' als Titel gesetzt
836 	String aNoName(SfxResId(STR_NONAME));
837 	if ( rTitle.Match(aNoName) <= aNoName.Len() )
838 	{
839 		// er ist es selbst => ignorieren
840 		pSfxApp->ReleaseIndex(pImp->nVisualDocumentNumber);
841 		pImp->bIsNamedVisible=0;
842 	}
843 #endif
844 
845 	// ggf. die unbenannt-Nummer freigeben
846 	if ( pImp->bIsNamedVisible && USHRT_MAX != pImp->nVisualDocumentNumber )
847 	{
848 		pSfxApp->ReleaseIndex(pImp->nVisualDocumentNumber);
849 		pImp->bIsNamedVisible = 0;
850 	}
851 
852 	// Title setzen
853 	pImp->aTitle = rTitle;
854 //	Wieso denn in der DocInfo?
855 //	GetDocInfo().SetTitle( rTitle );
856 //	FlushDocInfo();
857 
858 	// Benachrichtigungen
859     if ( GetMedium() )
860     {
861         SfxShell::SetName( GetTitle(SFX_TITLE_APINAME) );
862         Broadcast( SfxSimpleHint(SFX_HINT_TITLECHANGED) );
863     }
864 }
865 
866 //--------------------------------------------------------------------
867 
868 #if OSL_DEBUG_LEVEL > 1
869 String X(const String &rRet)
870 {
871 	if ( !rRet.Len() )
872 		return DEFINE_CONST_UNICODE( "-empty-" );
873 	return rRet;
874 }
875 #else
876 #define X(ret) ret
877 #endif
878 
879 //--------------------------------------------------------------------
880 //--------------------------------------------------------------------
881 String SfxObjectShell::GetTitle
882 (
883 	sal_uInt16	nMaxLength 		/*	0 (default)
884 								der Titel selbst, so wie er ist
885 
886 								1 (==SFX_TITLE_FILENAME)
887 								liefert den logischen Dateinamen ohne Pfad
888 								(unter WNT je nach Systemeinstellung ohne
889 								Extension)
890 
891 								2 (==SFX_TITLE_FULLNAME)
892 								liefert den mit komplettem logischen Dateinamen
893 								mit Pfad (remote => ::com::sun::star::util::URL)
894 
895 								3 (==SFX_TITLE_APINAME)
896 								liefert den logischen Dateinamen ohne Pfad
897 								und Extension
898 
899 								4 (==SFX_TITLE_DETECT)
900 								liefert den kompletten Titel, falls noch
901 								nicht gesetzt wird aber aus DocInfo oder
902 								dem Namen des Medium erzeugt
903 
904 								5 (==SFX_TITLE_CAPTION)
905 								liefert den Titel so, wie MB ihn heute in
906 								der CaptionBar anzeigen m"ochte
907 
908 								6 (==SFX_TITLE_PICKLIST)
909 								liefert den Titel so, wie MB ihn heute in
910 								der PickList anzeigen m"ochte
911 
912 								7 (==SFX_TITLE_HISTORY)
913 								liefert den Titel so, wie MB ihn heute in
914 								der History anzeigen m"ochte
915 
916 								10 bis USHRT_MAX
917 								liefert maximal 'nMaxLength' Zeichen vom logischen
918 								Dateinamen inkl. Pfad (remote => ::com::sun::star::util::URL)
919 								*/
920 ) const
921 
922 /*	[Beschreibung]
923 
924 	Liefert den Titel bzw. logischen Dateinamen des Dokuments, je nach
925 	'nMaxLength'.
926 
927 	Falls der Dateiname mit Pfad verwendet wird, wird die Namensk"urzung durch
928 	Ersetzung eines oder mehrerer Directory-Namen durch "..." durchgef"uhrt,
929 	URLs werden z.Zt. immer komplett geliefert.
930 */
931 
932 {
933 //    if ( GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
934 //        return String();
935     SfxMedium *pMed = GetMedium();
936     if ( IsLoading() )
937         return String();
938 
939 /*    if ( !nMaxLength && pImp->pDocInfo )
940     {
941         String aTitle = pImp->pDocInfo->GetTitle();
942         if ( aTitle.Len() )
943             return aTitle;
944     } */
945 
946 	// Titel erzeugen?
947 	if ( SFX_TITLE_DETECT == nMaxLength && !pImp->aTitle.Len() )
948 	{
949 		static sal_Bool bRecur = sal_False;
950 		if ( bRecur )
951 			return DEFINE_CONST_UNICODE( "-not available-" );
952 		bRecur = sal_True;
953 
954 		String aTitle;
955 		SfxObjectShell *pThis = (SfxObjectShell*) this;
956 
957 		if ( pMed )
958 		{
959 			SFX_ITEMSET_ARG( pMed->GetItemSet(), pNameItem, SfxStringItem, SID_DOCINFO_TITLE, sal_False );
960 			if ( pNameItem )
961 				aTitle = pNameItem->GetValue();
962 		}
963 
964 		if ( !aTitle.Len() )
965 			aTitle = GetTitle( SFX_TITLE_FILENAME );
966 
967 		if ( IsTemplate() )
968 			pThis->SetTitle( aTitle );
969 		bRecur = sal_False;
970 		return X(aTitle);
971 	}
972 	else if (SFX_TITLE_APINAME == nMaxLength )
973 		return X(GetAPIName());
974 
975 	// Sonderfall Vorlagen:
976 	if( IsTemplate() && pImp->aTitle.Len() &&
977 		 ( nMaxLength == SFX_TITLE_CAPTION || nMaxLength == SFX_TITLE_PICKLIST ) )
978 		return X(pImp->aTitle);
979 
980 	// Picklist/Caption wird gemappt
981 	if ( pMed && ( nMaxLength == SFX_TITLE_CAPTION || nMaxLength == SFX_TITLE_PICKLIST ) )
982 	{
983 		// Wenn ein spezieller Titel beim Öffnen mitgegeben wurde;
984 		// wichtig bei URLs, die INET_PROT_FILE verwenden, denn bei denen
985 		// wird der gesetzte Titel nicht beachtet.
986 		// (s.u., Auswertung von aTitleMap_Impl)
987 		SFX_ITEMSET_ARG( pMed->GetItemSet(), pNameItem, SfxStringItem, SID_DOCINFO_TITLE, sal_False );
988 		if ( pNameItem )
989 			return X( pNameItem->GetValue() );
990 	}
991 
992 	// noch unbenannt?
993 	DBG_ASSERT( !HasName() || pMed, "HasName() but no Medium?" );
994 	if ( !HasName() || !pMed )
995 	{
996 		// schon Titel gesetzt?
997 		if ( pImp->aTitle.Len() )
998 			return X(pImp->aTitle);
999 
1000 		// muß es durchnumeriert werden?
1001 		String aNoName( SfxResId( STR_NONAME ) );
1002 		if ( pImp->bIsNamedVisible ) {
1003 			// Leerzeichen und Nummer hinten anhängen
1004 			aNoName += C2S(" ");
1005 			aNoName += String::CreateFromInt32( pImp->nVisualDocumentNumber );
1006 		}
1007 
1008 		// Dokument heißt vorerst 'Unbenannt #'
1009 		return X(aNoName);
1010 	}
1011 
1012 	const INetURLObject aURL( IsDocShared() ? GetSharedFileURL() : ::rtl::OUString( GetMedium()->GetName() ) );
1013 	if ( nMaxLength > SFX_TITLE_CAPTION && nMaxLength <= SFX_TITLE_HISTORY )
1014 	{
1015 		sal_uInt16 nRemote;
1016 		if( !pMed || aURL.GetProtocol() == INET_PROT_FILE )
1017 			nRemote = 0;
1018 		else
1019 			nRemote = 1;
1020 		nMaxLength = aTitleMap_Impl[nMaxLength-SFX_TITLE_CAPTION][nRemote];
1021 	}
1022 
1023 	// local file?
1024 	if ( aURL.GetProtocol() == INET_PROT_FILE )
1025 	{
1026         String aName( aURL.HasMark() ? INetURLObject( aURL.GetURLNoMark() ).PathToFileName() : aURL.PathToFileName() );
1027 		if ( nMaxLength == SFX_TITLE_FULLNAME )
1028 			return X( aName );
1029 		else if ( nMaxLength == SFX_TITLE_FILENAME )
1030             return X( aURL.getName( INetURLObject::LAST_SEGMENT,
1031 				true, INetURLObject::DECODE_WITH_CHARSET ) );
1032 		else if ( !pImp->aTitle.Len() )
1033             pImp->aTitle = aURL.getBase( INetURLObject::LAST_SEGMENT,
1034 										 true, INetURLObject::DECODE_WITH_CHARSET );
1035 	}
1036 	else
1037 	{
1038 		// ::com::sun::star::util::URL-Versionen
1039 		if ( nMaxLength >= SFX_TITLE_MAXLEN )
1040 		{
1041             String aComplete( aURL.GetMainURL( INetURLObject::NO_DECODE ) );
1042 			if( aComplete.Len() > nMaxLength )
1043 			{
1044 				String aRet( DEFINE_CONST_UNICODE( "..." ) );
1045 				aRet += aComplete.Copy( aComplete.Len() - nMaxLength + 3, nMaxLength - 3 );
1046 				return X( aRet );
1047 			}
1048 			else
1049                 return X( aComplete );
1050 		}
1051 		else if ( nMaxLength == SFX_TITLE_FILENAME )
1052 		{
1053             String aName( aURL.GetBase() );
1054 			aName = INetURLObject::decode( aName, INET_HEX_ESCAPE, INetURLObject::DECODE_WITH_CHARSET );
1055 			if( !aName.Len() )
1056 				aName = aURL.GetURLNoPass();
1057 			return X(aName);
1058 		}
1059 		else if ( nMaxLength == SFX_TITLE_FULLNAME )
1060 			return X(aURL.GetMainURL( INetURLObject::DECODE_TO_IURI ));
1061 
1062 		// ggf. Titel aus Dateiname generieren
1063 		if ( !pImp->aTitle.Len() )
1064 			pImp->aTitle = aURL.GetBase();
1065 
1066 		// workaround for the case when the name can not be retrieved from URL by INetURLObject
1067 		if ( !pImp->aTitle.Len() )
1068 			pImp->aTitle = aURL.GetMainURL( INetURLObject::DECODE_WITH_CHARSET );
1069 	}
1070 
1071 	// ganzer Titel
1072 	return X(pImp->aTitle);
1073 }
1074 
1075 //--------------------------------------------------------------------
1076 
1077 void SfxObjectShell::InvalidateName()
1078 
1079 /*	[Beschreibung]
1080 
1081 	Ermittelt den Titel des Dokuments neu aus 'unbenannt', DocInfo-Titel
1082 	bzw. Dateinamen. Wird nach Laden aus Template oder SaveAs benötigt.
1083 */
1084 
1085 {
1086 	// Title neu erzeugen
1087 	pImp->aTitle.Erase();
1088 //	pImp->nVisualDocumentNumber = USHRT_MAX;
1089 	//GetTitle( SFX_TITLE_DETECT );
1090 	SetName( GetTitle( SFX_TITLE_APINAME ) );
1091 
1092 	// Benachrichtigungen
1093 	Broadcast( SfxSimpleHint(SFX_HINT_TITLECHANGED) );
1094 }
1095 
1096 //--------------------------------------------------------------------
1097 
1098 void SfxObjectShell::SetNamedVisibility_Impl()
1099 {
1100 	if ( !pImp->bIsNamedVisible )
1101 	{
1102 		// Nummer verpassen
1103 		pImp->bIsNamedVisible = sal_True;
1104 		// ggf. neue Nummer verpassen
1105 		if ( !HasName() && USHRT_MAX == pImp->nVisualDocumentNumber && !pImp->aTitle.Len() )
1106 		{
1107 			pImp->nVisualDocumentNumber = SFX_APP()->GetFreeIndex();
1108 			Broadcast( SfxSimpleHint(SFX_HINT_TITLECHANGED) );
1109 		}
1110 	}
1111 
1112 	SetName( GetTitle(SFX_TITLE_APINAME) );
1113 }
1114 
1115 void SfxObjectShell::SetNoName()
1116 {
1117     bHasName = 0;
1118     bIsTmp = sal_True;
1119     GetModel()->attachResource( ::rtl::OUString(), GetModel()->getArgs() );
1120 }
1121 
1122 //--------------------------------------------------------------------
1123 
1124 void SfxObjectShell::MemoryError()
1125 {
1126 }
1127 
1128 //--------------------------------------------------------------------
1129 
1130 SfxProgress* SfxObjectShell::GetProgress() const
1131 {
1132 	return pImp->pProgress;
1133 }
1134 
1135 //--------------------------------------------------------------------
1136 
1137 void SfxObjectShell::SetProgress_Impl
1138 (
1139 	SfxProgress *pProgress	/*	zu startender <SfxProgress> oder 0, falls
1140 								der Progress zur"uckgesetzt werden soll */
1141 )
1142 
1143 /*	[Beschreibung]
1144 
1145 	Interne Methode zum setzen oder zur"ucksetzen des Progress-Modes
1146 	f"ur diese SfxObjectShell.
1147 */
1148 
1149 {
1150 	DBG_ASSERT( ( !pImp->pProgress && pProgress ) ||
1151 				( pImp->pProgress && !pProgress ),
1152 				"Progress activation/deacitivation mismatch" );
1153 	pImp->pProgress = pProgress;
1154 }
1155 
1156 //--------------------------------------------------------------------
1157 
1158 void SfxObjectShell::PostActivateEvent_Impl( SfxViewFrame* pFrame )
1159 {
1160 	SfxApplication* pSfxApp = SFX_APP();
1161     if ( !pSfxApp->IsDowning() && !IsLoading() && pFrame && !pFrame->GetFrame().IsClosing_Impl() )
1162 	{
1163         SFX_ITEMSET_ARG( pMedium->GetItemSet(), pHiddenItem, SfxBoolItem, SID_HIDDEN, sal_False );
1164         if ( !pHiddenItem || !pHiddenItem->GetValue() )
1165         {
1166             sal_uInt16 nId = pImp->nEventId;
1167             pImp->nEventId = 0;
1168             if ( nId == SFX_EVENT_OPENDOC )
1169                 pSfxApp->NotifyEvent(SfxViewEventHint( nId, GlobalEventConfig::GetEventName(STR_EVENT_OPENDOC), this, pFrame->GetFrame().GetController() ), sal_False);
1170 			else if (nId == SFX_EVENT_CREATEDOC )
1171                 pSfxApp->NotifyEvent(SfxViewEventHint( nId, GlobalEventConfig::GetEventName(STR_EVENT_CREATEDOC), this, pFrame->GetFrame().GetController() ), sal_False);
1172         }
1173 	}
1174 }
1175 
1176 //--------------------------------------------------------------------
1177 
1178 void SfxObjectShell::SetActivateEvent_Impl(sal_uInt16 nId )
1179 {
1180 	if ( GetFactory().GetFlags() & SFXOBJECTSHELL_HASOPENDOC )
1181 		pImp->nEventId = nId;
1182 }
1183 
1184 //--------------------------------------------------------------------
1185 
1186 void SfxObjectShell::RegisterTransfer( SfxMedium& rMedium )
1187 /*  [Beschreibung ]
1188 	Alle Medien, die aufgesetzt werden, um Teile eines Dokumentes zu
1189 	laden, muessen an der zugehoerigen SfxObjectShell angemeldet
1190 	werden. So kann dokumentweise abgebrochen werden.  */
1191 {
1192 	rMedium.SetReferer( GetMedium()->GetName() );
1193 }
1194 
1195 //-------------------------------------------------------------------------
1196 
1197 void SfxObjectShell::PrepareReload( )
1198 /*  [Beschreibung ]
1199 	Wird vor dem Reload gerufen und gibt die Moeglichkeit,
1200 	etwaige Caches zu leeren. */
1201 {
1202 }
1203 
1204 //-------------------------------------------------------------------------
1205 
1206 void SfxObjectShell::LockAutoLoad( sal_Bool bLock )
1207 
1208 /* 	Verhindert ein evtl. eintreffendes AutoLoad. Wird auch vor AutoLoad
1209 	eines umgebenden FrameSet beruecksichtigt.
1210 */
1211 
1212 {
1213 	if ( bLock )
1214 		++pImp->nAutoLoadLocks;
1215 	else
1216 		--pImp->nAutoLoadLocks;
1217 }
1218 
1219 //-------------------------------------------------------------------------
1220 
1221 // kann nach frame.cxx gemoved werden, wenn 358+36x-Stand gemerged sind
1222 
1223 sal_Bool SfxFrame::IsAutoLoadLocked_Impl() const
1224 {
1225 	// sein einges Doc gelockt?
1226 	const SfxObjectShell* pObjSh = GetCurrentDocument();
1227 	if ( !pObjSh || !pObjSh->IsAutoLoadLocked() )
1228 		return sal_False;
1229 
1230 	// seine Childs gelockt?
1231 	for ( sal_uInt16 n = GetChildFrameCount(); n--; )
1232 		if ( !GetChildFrame(n)->IsAutoLoadLocked_Impl() )
1233 			return sal_False;
1234 
1235 	// sonst ist AutoLoad erlaubt
1236 	return sal_True;
1237 }
1238 
1239 //-------------------------------------------------------------------------
1240 
1241 sal_Bool SfxObjectShell::IsAutoLoadLocked() const
1242 
1243 /* 	Liefert, ob ein eintreffendes AutoLoad ausgefuehrt werden darf. Wird auch
1244 	vor AutoLoad eines umgebenden FrameSet beruecksichtigt.
1245 */
1246 
1247 {
1248 	return !IsReadOnly() || pImp->nAutoLoadLocks > 0;
1249 }
1250 
1251 //-------------------------------------------------------------------------
1252 void SfxObjectShell::BreakMacroSign_Impl( sal_Bool bBreakMacroSign )
1253 {
1254 	pImp->m_bMacroSignBroken = bBreakMacroSign;
1255 }
1256 
1257 //-------------------------------------------------------------------------
1258 void SfxObjectShell::CheckSecurityOnLoading_Impl()
1259 {
1260     uno::Reference< task::XInteractionHandler > xInteraction;
1261     if ( GetMedium() )
1262         xInteraction = GetMedium()->GetInteractionHandler();
1263 
1264 	// check if there is a broken signature...
1265     CheckForBrokenDocSignatures_Impl( xInteraction );
1266 
1267     CheckEncryption_Impl( xInteraction );
1268 
1269     // check macro security
1270     pImp->aMacroMode.checkMacrosOnLoading( xInteraction );
1271 }
1272 
1273 //-------------------------------------------------------------------------
1274 void SfxObjectShell::CheckEncryption_Impl( const uno::Reference< task::XInteractionHandler >& xHandler )
1275 {
1276     ::rtl::OUString aVersion;
1277     sal_Bool bIsEncrypted = sal_False;
1278     sal_Bool bHasNonEncrypted = sal_False;
1279 
1280     try
1281     {
1282         uno::Reference < beans::XPropertySet > xPropSet( GetStorage(), uno::UNO_QUERY_THROW );
1283         xPropSet->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Version" ) ) ) >>= aVersion;
1284         xPropSet->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "HasEncryptedEntries" ) ) ) >>= bIsEncrypted;
1285         xPropSet->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "HasNonEncryptedEntries" ) ) ) >>= bHasNonEncrypted;
1286     }
1287     catch( uno::Exception& )
1288     {
1289     }
1290 
1291     if ( aVersion.compareTo( ODFVER_012_TEXT ) >= 0 )
1292     {
1293         // this is ODF1.2 or later
1294         if ( bIsEncrypted && bHasNonEncrypted )
1295         {
1296             if ( !pImp->m_bIncomplEncrWarnShown )
1297             {
1298                 // this is an encrypted document with nonencrypted streams inside, show the warning
1299                 ::com::sun::star::task::ErrorCodeRequest aErrorCode;
1300                 aErrorCode.ErrCode = ERRCODE_SFX_INCOMPLETE_ENCRYPTION;
1301 
1302                 SfxMedium::CallApproveHandler( xHandler, uno::makeAny( aErrorCode ), sal_False );
1303                 pImp->m_bIncomplEncrWarnShown = sal_True;
1304             }
1305 
1306             // broken signatures imply no macro execution at all
1307             pImp->aMacroMode.disallowMacroExecution();
1308         }
1309     }
1310 }
1311 
1312 //-------------------------------------------------------------------------
1313 void SfxObjectShell::CheckForBrokenDocSignatures_Impl( const uno::Reference< task::XInteractionHandler >& xHandler )
1314 {
1315     sal_Int16 nSignatureState = GetDocumentSignatureState();
1316     bool bSignatureBroken = ( nSignatureState == SIGNATURESTATE_SIGNATURES_BROKEN );
1317     if ( !bSignatureBroken )
1318         return;
1319 
1320     pImp->showBrokenSignatureWarning( xHandler );
1321 
1322     // broken signatures imply no macro execution at all
1323     pImp->aMacroMode.disallowMacroExecution();
1324 }
1325 
1326 //-------------------------------------------------------------------------
1327 void SfxObjectShell::SetAutoLoad(
1328 	const INetURLObject& rUrl, sal_uInt32 nTime, sal_Bool bReload )
1329 {
1330 	if ( pImp->pReloadTimer )
1331 		DELETEZ(pImp->pReloadTimer);
1332 	if ( bReload )
1333 	{
1334 		pImp->pReloadTimer = new AutoReloadTimer_Impl(
1335 								rUrl.GetMainURL( INetURLObject::DECODE_TO_IURI ),
1336 								nTime, bReload, this );
1337 		pImp->pReloadTimer->Start();
1338 	}
1339 }
1340 
1341 sal_Bool SfxObjectShell::IsLoadingFinished() const
1342 {
1343 	return ( pImp->nLoadedFlags == SFX_LOADED_ALL );
1344 }
1345 
1346 void impl_addToModelCollection(const com::sun::star::uno::Reference< com::sun::star::frame::XModel >& xModel);
1347 void SfxObjectShell::InitOwnModel_Impl()
1348 {
1349 	if ( !pImp->bModelInitialized )
1350 	{
1351 		SFX_ITEMSET_ARG( pMedium->GetItemSet(), pSalvageItem, SfxStringItem, SID_DOC_SALVAGE, sal_False);
1352 		if ( pSalvageItem )
1353 		{
1354             pImp->aTempName = pMedium->GetPhysicalName();
1355 			pMedium->GetItemSet()->ClearItem( SID_DOC_SALVAGE );
1356 			pMedium->GetItemSet()->ClearItem( SID_FILE_NAME );
1357 			pMedium->GetItemSet()->Put( SfxStringItem( SID_FILE_NAME, pMedium->GetOrigURL() ) );
1358 		}
1359 		else
1360 		{
1361 			pMedium->GetItemSet()->ClearItem( SID_PROGRESS_STATUSBAR_CONTROL );
1362 			pMedium->GetItemSet()->ClearItem( SID_DOCUMENT );
1363 		}
1364 
1365 		pMedium->GetItemSet()->ClearItem( SID_REFERER );
1366 		uno::Reference< frame::XModel > xModel ( GetModel(), uno::UNO_QUERY );
1367 		if ( xModel.is() )
1368 		{
1369 			::rtl::OUString aURL = GetMedium()->GetOrigURL();
1370 			SfxItemSet *pSet = GetMedium()->GetItemSet();
1371             if ( !GetMedium()->IsReadOnly() )
1372                 pSet->ClearItem( SID_INPUTSTREAM );
1373 			uno::Sequence< beans::PropertyValue > aArgs;
1374 			TransformItems( SID_OPENDOC, *pSet, aArgs );
1375 			xModel->attachResource( aURL, aArgs );
1376             impl_addToModelCollection(xModel);
1377 		}
1378 
1379 		pImp->bModelInitialized = sal_True;
1380 	}
1381 }
1382 
1383 void SfxObjectShell::FinishedLoading( sal_uInt16 nFlags )
1384 {
1385 	sal_Bool bSetModifiedTRUE = sal_False;
1386 	SFX_ITEMSET_ARG( pMedium->GetItemSet(), pSalvageItem, SfxStringItem, SID_DOC_SALVAGE, sal_False );
1387     if( ( nFlags & SFX_LOADED_MAINDOCUMENT ) && !(pImp->nLoadedFlags & SFX_LOADED_MAINDOCUMENT )
1388 	    && !(pImp->nFlagsInProgress & SFX_LOADED_MAINDOCUMENT ))
1389 	{
1390 		pImp->nFlagsInProgress |= SFX_LOADED_MAINDOCUMENT;
1391 		((SfxHeaderAttributes_Impl*)GetHeaderAttributes())->SetAttributes();
1392 		pImp->bImportDone = sal_True;
1393 		if( !IsAbortingImport() )
1394 			PositionView_Impl();
1395 
1396         if ( ( GetModifyPasswordHash() || GetModifyPasswordInfo().getLength() ) && !IsModifyPasswordEntered() )
1397             SetReadOnly();
1398 
1399 		// Salvage
1400 		if ( pSalvageItem )
1401 			bSetModifiedTRUE = sal_True;
1402 
1403 		if ( !IsEnableSetModified() )
1404 			EnableSetModified( sal_True );
1405 
1406 		if( !bSetModifiedTRUE && IsEnableSetModified() )
1407 			SetModified( sal_False );
1408 
1409         CheckSecurityOnLoading_Impl();
1410 
1411 		bHasName = sal_True; // the document is loaded, so the name should already available
1412 		GetTitle( SFX_TITLE_DETECT );
1413 		InitOwnModel_Impl();
1414 		pImp->nFlagsInProgress &= ~SFX_LOADED_MAINDOCUMENT;
1415 	}
1416 
1417     if( ( nFlags & SFX_LOADED_IMAGES ) && !(pImp->nLoadedFlags & SFX_LOADED_IMAGES )
1418 	    && !(pImp->nFlagsInProgress & SFX_LOADED_IMAGES ))
1419 	{
1420 		pImp->nFlagsInProgress |= SFX_LOADED_IMAGES;
1421         uno::Reference<document::XDocumentProperties> xDocProps(
1422             getDocProperties());
1423         ::rtl::OUString url(xDocProps->getAutoloadURL());
1424         sal_Int32 delay(xDocProps->getAutoloadSecs());
1425         SetAutoLoad( INetURLObject(url), delay * 1000,
1426                      (delay > 0) || url.getLength() );
1427 		if( !bSetModifiedTRUE && IsEnableSetModified() )
1428 			SetModified( sal_False );
1429 		Invalidate( SID_SAVEASDOC );
1430 		pImp->nFlagsInProgress &= ~SFX_LOADED_IMAGES;
1431 	}
1432 
1433 	pImp->nLoadedFlags |= nFlags;
1434 
1435 	if ( !pImp->nFlagsInProgress )
1436 	{
1437 		// in case of reentrance calls the first called FinishedLoading() call on the stack
1438 		// should do the notification, in result the notification is done when all the FinishedLoading() calls are finished
1439 
1440 		if ( bSetModifiedTRUE )
1441 			SetModified( sal_True );
1442 		else
1443 			SetModified( sal_False );
1444 
1445 		if ( (pImp->nLoadedFlags & SFX_LOADED_MAINDOCUMENT ) && (pImp->nLoadedFlags & SFX_LOADED_IMAGES ) )
1446 		{
1447             SFX_ITEMSET_ARG( pMedium->GetItemSet(), pTemplateItem, SfxBoolItem, SID_TEMPLATE, sal_False);
1448             sal_Bool bTemplate = pTemplateItem && pTemplateItem->GetValue();
1449 
1450 			// closing the streams on loading should be under control of SFX!
1451 			DBG_ASSERT( pMedium->IsOpen(), "Don't close the medium when loading documents!" );
1452 
1453             if ( bTemplate )
1454             {
1455                 TemplateDisconnectionAfterLoad();
1456             }
1457             else
1458             {
1459                 // if a readonly medium has storage then it's stream is already based on temporary file
1460                 if( !(pMedium->GetOpenMode() & STREAM_WRITE) && !pMedium->HasStorage_Impl() )
1461                     // don't lock file opened read only
1462                     pMedium->CloseInStream();
1463             }
1464 		}
1465 
1466         SetInitialized_Impl( false );
1467 
1468 		// Title is not available until loading has finished
1469 		Broadcast( SfxSimpleHint( SFX_HINT_TITLECHANGED ) );
1470 		if ( pImp->nEventId )
1471 			PostActivateEvent_Impl(SfxViewFrame::GetFirst(this));
1472 	}
1473 }
1474 
1475 //-------------------------------------------------------------------------
1476 extern void SetTemplate_Impl( const String&, const String&, SfxObjectShell* );
1477 
1478 void SfxObjectShell::TemplateDisconnectionAfterLoad()
1479 {
1480     // document is created from a template
1481     //TODO/LATER: should the templates always be XML docs!
1482 
1483     SfxMedium* pTmpMedium = pMedium;
1484     if ( pTmpMedium )
1485     {
1486         String aName( pTmpMedium->GetName() );
1487         SFX_ITEMSET_ARG( pTmpMedium->GetItemSet(), pTemplNamItem, SfxStringItem, SID_TEMPLATE_NAME, sal_False);
1488         String aTemplateName;
1489         if ( pTemplNamItem )
1490             aTemplateName = pTemplNamItem->GetValue();
1491         else
1492         {
1493             // !TODO/LATER: what's this?!
1494             // Interaktiv ( DClick, Contextmenu ) kommt kein Langname mit
1495             aTemplateName = getDocProperties()->getTitle();
1496             if ( !aTemplateName.Len() )
1497             {
1498                 INetURLObject aURL( aName );
1499                 aURL.CutExtension();
1500                 aTemplateName = aURL.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DECODE_WITH_CHARSET );
1501             }
1502         }
1503 
1504         // set medium to noname
1505         pTmpMedium->SetName( String(), sal_True );
1506         pTmpMedium->Init_Impl();
1507 
1508         // drop resource
1509         SetNoName();
1510         InvalidateName();
1511 
1512         if( IsPackageStorageFormat_Impl( *pTmpMedium ) )
1513         {
1514             // untitled document must be based on temporary storage
1515             // the medium should not dispose the storage in this case
1516             uno::Reference < embed::XStorage > xTmpStor = ::comphelper::OStorageHelper::GetTemporaryStorage();
1517             GetStorage()->copyToStorage( xTmpStor );
1518 
1519             // the medium should disconnect from the original location
1520             // the storage should not be disposed since the document is still
1521             // based on it, but in DoSaveCompleted it will be disposed
1522             pTmpMedium->CanDisposeStorage_Impl( sal_False );
1523             pTmpMedium->Close();
1524 
1525             // setting the new storage the medium will be based on
1526             pTmpMedium->SetStorage_Impl( xTmpStor );
1527 
1528             ForgetMedium();
1529             if( !DoSaveCompleted( pTmpMedium ) )
1530                 SetError( ERRCODE_IO_GENERAL, ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ) );
1531             else
1532             {
1533                 SFX_ITEMSET_ARG( pMedium->GetItemSet(), pSalvageItem, SfxStringItem, SID_DOC_SALVAGE, sal_False );
1534                 sal_Bool bSalvage = pSalvageItem ? sal_True : sal_False;
1535 
1536                 if ( !bSalvage )
1537                 {
1538                     // some further initializations for templates
1539                     SetTemplate_Impl( aName, aTemplateName, this );
1540                 }
1541 
1542                 // the medium should not dispose the storage, DoSaveCompleted() has let it to do so
1543                 pTmpMedium->CanDisposeStorage_Impl( sal_False );
1544             }
1545         }
1546         else
1547         {
1548             // some further initializations for templates
1549             SetTemplate_Impl( aName, aTemplateName, this );
1550             pTmpMedium->CreateTempFile( sal_True );
1551         }
1552 
1553         // templates are never readonly
1554         pTmpMedium->GetItemSet()->ClearItem( SID_DOC_READONLY );
1555         pTmpMedium->SetOpenMode( SFX_STREAM_READWRITE, sal_True, sal_True );
1556 
1557         // notifications about possible changes in readonly state and document info
1558         Broadcast( SfxSimpleHint(SFX_HINT_MODECHANGED) );
1559 
1560         // created untitled document can't be modified
1561         SetModified( sal_False );
1562     }
1563 }
1564 
1565 //-------------------------------------------------------------------------
1566 
1567 void SfxObjectShell::PositionView_Impl()
1568 {
1569 	MarkData_Impl *pMark = Get_Impl()->pMarkData;
1570 	if( pMark )
1571 	{
1572 		SfxViewShell* pSh = pMark->pFrame->GetViewShell();
1573 		if( pMark->aUserData.Len() )
1574 			pSh->ReadUserData( pMark->aUserData, sal_True );
1575 		else if( pMark->aMark.Len() )
1576 			pSh->JumpToMark( pMark->aMark );
1577 		DELETEZ( Get_Impl()->pMarkData );
1578 	}
1579 }
1580 
1581 //-------------------------------------------------------------------------
1582 
1583 sal_Bool SfxObjectShell::IsLoading() const
1584 /*  [Beschreibung ]
1585 	Has FinishedLoading been called? */
1586 {
1587 	return !( pImp->nLoadedFlags & SFX_LOADED_MAINDOCUMENT );
1588 }
1589 
1590 //-------------------------------------------------------------------------
1591 
1592 void SfxObjectShell::CancelTransfers()
1593 /*  [Beschreibung ]
1594 	Hier koennen Transfers gecanceled werden, die nicht mit
1595 	RegisterTransfer registiert wurden */
1596 {
1597 	if( ( pImp->nLoadedFlags & SFX_LOADED_ALL ) != SFX_LOADED_ALL )
1598 	{
1599 		AbortImport();
1600 		if( IsLoading() )
1601 			FinishedLoading( SFX_LOADED_ALL );
1602 
1603 /*
1604 		SfxViewFrame* pFrame = SfxViewFrame::GetFirst( this );
1605 		while( pFrame )
1606 		{
1607 			pFrame->CancelTransfers();
1608 			pFrame = SfxViewFrame::GetNext( *pFrame, this );
1609 		}*/
1610 	}
1611 }
1612 
1613 //-------------------------------------------------------------------------
1614 
1615 AutoReloadTimer_Impl::AutoReloadTimer_Impl(
1616 	const String& rURL, sal_uInt32 nTime, sal_Bool bReloadP, SfxObjectShell* pSh )
1617 	: aUrl( rURL ), bReload( bReloadP ), pObjSh( pSh )
1618 {
1619 	SetTimeout( nTime );
1620 }
1621 
1622 //-------------------------------------------------------------------------
1623 
1624 void AutoReloadTimer_Impl::Timeout()
1625 {
1626 	SfxViewFrame *pFrame = SfxViewFrame::GetFirst( pObjSh );
1627 
1628 	if ( pFrame )
1629 	{
1630 		// momentan nicht m"oglich/sinnvoll?
1631         if ( !pObjSh->CanReload_Impl() || pObjSh->IsAutoLoadLocked() || Application::IsUICaptured() )
1632 		{
1633 			// erneuten Versuch erlauben
1634 			Start();
1635 			return;
1636 		}
1637 
1638 		SfxAllItemSet aSet( SFX_APP()->GetPool() );
1639 		aSet.Put( SfxBoolItem( SID_AUTOLOAD, sal_True ) );
1640 		if ( aUrl.Len() )
1641 			aSet.Put(  SfxStringItem( SID_FILE_NAME, aUrl ) );
1642 		SfxRequest aReq( SID_RELOAD, 0, aSet );
1643 		pObjSh->Get_Impl()->pReloadTimer = 0;
1644 		delete this;
1645 		pFrame->ExecReload_Impl( aReq );
1646 		return;
1647 	}
1648 
1649 	pObjSh->Get_Impl()->pReloadTimer = 0;
1650 	delete this;
1651 }
1652 
1653 SfxModule* SfxObjectShell::GetModule() const
1654 {
1655 	return GetFactory().GetModule();
1656 }
1657 
1658 ErrCode SfxObjectShell::CallBasic( const String& rMacro,
1659 	const String& rBasic, SbxArray* pArgs,
1660 	SbxValue* pRet )
1661 {
1662     SfxApplication* pApp = SFX_APP();
1663     if( pApp->GetName() != rBasic )
1664     {
1665         if ( !AdjustMacroMode( String() ) )
1666             return ERRCODE_IO_ACCESSDENIED;
1667     }
1668 
1669     BasicManager *pMgr = GetBasicManager();
1670     if( pApp->GetName() == rBasic )
1671         pMgr = pApp->GetBasicManager();
1672     ErrCode nRet = SfxApplication::CallBasic( rMacro, pMgr, pArgs, pRet );
1673     return nRet;
1674 }
1675 
1676 namespace
1677 {
1678     static bool lcl_isScriptAccessAllowed_nothrow( const Reference< XInterface >& _rxScriptContext )
1679     {
1680         try
1681         {
1682             Reference< XEmbeddedScripts > xScripts( _rxScriptContext, UNO_QUERY );
1683             if ( !xScripts.is() )
1684             {
1685                 Reference< XScriptInvocationContext > xContext( _rxScriptContext, UNO_QUERY_THROW );
1686                 xScripts.set( xContext->getScriptContainer(), UNO_SET_THROW );
1687             }
1688 
1689             return xScripts->getAllowMacroExecution();
1690         }
1691         catch( const Exception& )
1692         {
1693         	DBG_UNHANDLED_EXCEPTION();
1694         }
1695         return false;
1696     }
1697 }
1698 
1699 ErrCode SfxObjectShell::CallXScript( const Reference< XInterface >& _rxScriptContext, const ::rtl::OUString& _rScriptURL,
1700     const Sequence< Any >& aParams, Any& aRet, Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam, bool bRaiseError )
1701 {
1702     OSL_TRACE( "in CallXScript" );
1703 	ErrCode nErr = ERRCODE_NONE;
1704 
1705 	bool bCaughtException = false;
1706     Any aException;
1707     try
1708     {
1709         uno::Reference< lang::XMultiServiceFactory > xServiceManager( ::comphelper::getProcessServiceFactory(), uno::UNO_SET_THROW );
1710         Reference< uri::XUriReferenceFactory > xFac (
1711             xServiceManager->createInstance( rtl::OUString::createFromAscii(
1712                 "com.sun.star.uri.UriReferenceFactory") ) , UNO_QUERY_THROW );
1713         Reference< uri::XVndSunStarScriptUrlReference > xScriptUri( xFac->parse( _rScriptURL ), UNO_QUERY_THROW );
1714         if ( !lcl_isScriptAccessAllowed_nothrow( _rxScriptContext ) )
1715             return ERRCODE_IO_ACCESSDENIED;
1716 
1717         // obtain/create a script provider
1718         Reference< provider::XScriptProvider > xScriptProvider;
1719         Reference< provider::XScriptProviderSupplier > xSPS( _rxScriptContext, UNO_QUERY );
1720         if ( xSPS.is() )
1721             xScriptProvider.set( xSPS->getScriptProvider() );
1722 
1723         if ( !xScriptProvider.is() )
1724         {
1725             ::comphelper::ComponentContext aContext( ::comphelper::getProcessServiceFactory() );
1726             Reference< provider::XScriptProviderFactory > xScriptProviderFactory(
1727                 aContext.getSingleton( "com.sun.star.script.provider.theMasterScriptProviderFactory" ), UNO_QUERY_THROW );
1728             xScriptProvider.set( xScriptProviderFactory->createScriptProvider( makeAny( _rxScriptContext ) ), UNO_SET_THROW );
1729         }
1730 
1731         // ry to protect the invocation context's undo manager (if present), just in case the script tampers with it
1732         ::framework::DocumentUndoGuard aUndoGuard( _rxScriptContext.get() );
1733 
1734         // obtain the script, and execute it
1735         Reference< provider::XScript > xScript( xScriptProvider->getScript( _rScriptURL ), UNO_QUERY_THROW );
1736         aRet = xScript->invoke( aParams, aOutParamIndex, aOutParam );
1737     }
1738     catch ( const uno::Exception& )
1739     {
1740         aException = ::cppu::getCaughtException();
1741 		bCaughtException = sal_True;
1742         nErr = ERRCODE_BASIC_INTERNAL_ERROR;
1743     }
1744 
1745 	if ( bCaughtException && bRaiseError )
1746 	{
1747         ::std::auto_ptr< VclAbstractDialog > pScriptErrDlg;
1748 		SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
1749         if ( pFact )
1750             pScriptErrDlg.reset( pFact->CreateScriptErrorDialog( NULL, aException ) );
1751         OSL_ENSURE( pScriptErrDlg.get(), "SfxObjectShell::CallXScript: no script error dialog!" );
1752 
1753         if ( pScriptErrDlg.get() )
1754 			pScriptErrDlg->Execute();
1755 	}
1756 
1757     OSL_TRACE( "leaving CallXScript" );
1758     return nErr;
1759 }
1760 
1761 // perhaps rename to CallScript once we get rid of the existing CallScript
1762 // and Call, CallBasic, CallStarBasic methods
1763 ErrCode SfxObjectShell::CallXScript( const String& rScriptURL,
1764         const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >&
1765             aParams,
1766         ::com::sun::star::uno::Any& aRet,
1767         ::com::sun::star::uno::Sequence< sal_Int16 >& aOutParamIndex,
1768         ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aOutParam
1769         , bool bRaiseError )
1770 {
1771     return CallXScript( GetModel(), rScriptURL, aParams, aRet, aOutParamIndex, aOutParam, bRaiseError );
1772 }
1773 
1774 //-------------------------------------------------------------------------
1775 SfxFrame* SfxObjectShell::GetSmartSelf( SfxFrame* pSelf, SfxMedium& /*rMedium*/ )
1776 {
1777 	return pSelf;
1778 }
1779 
1780 SfxObjectShellFlags SfxObjectShell::GetFlags() const
1781 {
1782 	if( pImp->eFlags == SFXOBJECTSHELL_UNDEFINED )
1783 		pImp->eFlags = GetFactory().GetFlags();
1784 	return pImp->eFlags;
1785 }
1786 
1787 void SfxObjectShell::SetFlags( SfxObjectShellFlags eFlags )
1788 {
1789 	pImp->eFlags = eFlags;
1790 }
1791 
1792 void SfxHeaderAttributes_Impl::SetAttributes()
1793 {
1794 	bAlert = sal_True;
1795 	SvKeyValue aPair;
1796 	for( sal_Bool bCont = xIter->GetFirst( aPair ); bCont;
1797 		 bCont = xIter->GetNext( aPair ) )
1798 		SetAttribute( aPair );
1799 }
1800 
1801 void SfxHeaderAttributes_Impl::SetAttribute( const SvKeyValue& rKV )
1802 {
1803 	String aValue = rKV.GetValue();
1804 	if( rKV.GetKey().CompareIgnoreCaseToAscii( "refresh" ) == COMPARE_EQUAL && rKV.GetValue().Len() )
1805 	{
1806 		sal_uInt32 nTime = aValue.GetToken( 0, ';' ).ToInt32() ;
1807 		String aURL = aValue.GetToken( 1, ';' );
1808 		aURL.EraseTrailingChars().EraseLeadingChars();
1809         uno::Reference<document::XDocumentProperties> xDocProps(
1810             pDoc->getDocProperties());
1811 		if( aURL.Copy(0, 4).CompareIgnoreCaseToAscii( "url=" ) == COMPARE_EQUAL )
1812 		{
1813 			INetURLObject aObj;
1814 			INetURLObject( pDoc->GetMedium()->GetName() ).GetNewAbsURL( aURL.Copy( 4 ), &aObj );
1815             xDocProps->setAutoloadURL(
1816                 aObj.GetMainURL( INetURLObject::NO_DECODE ) );
1817 		}
1818         try
1819         {
1820             xDocProps->setAutoloadSecs( nTime );
1821         }
1822         catch (lang::IllegalArgumentException &)
1823         {
1824             // ignore
1825         }
1826 	}
1827 	else if( rKV.GetKey().CompareIgnoreCaseToAscii( "expires" ) == COMPARE_EQUAL )
1828 	{
1829 		DateTime aDateTime;
1830 		if( INetRFC822Message::ParseDateField( rKV.GetValue(), aDateTime ) )
1831 		{
1832 			aDateTime.ConvertToLocalTime();
1833 			pDoc->GetMedium()->SetExpired_Impl( aDateTime );
1834 		}
1835 		else
1836 		{
1837 //			DBG_ERROR( "Schlechtes ::com::sun::star::util::DateTime fuer Expired" );
1838 			pDoc->GetMedium()->SetExpired_Impl( Date( 1, 1, 1970 ) );
1839 		}
1840 	}
1841 	else if( rKV.GetKey().CompareIgnoreCaseToAscii( "content-type" ) == COMPARE_EQUAL )
1842 	{
1843 		::rtl::OString sContent = ::rtl::OUStringToOString( aValue, RTL_TEXTENCODING_ASCII_US );
1844 		ByteString sType, sSubType;
1845 		INetContentTypeParameterList aParameters;
1846 
1847 		if( INetContentTypes::parse( sContent, sType, sSubType, &aParameters ) )
1848 		{
1849 			const INetContentTypeParameter * pCharset = aParameters.find("charset");
1850 			if (pCharset != 0)
1851 				pDoc->GetMedium()->SetCharset( pCharset->m_sValue );
1852 		}
1853 	}
1854 }
1855 
1856 void SfxHeaderAttributes_Impl::Append( const SvKeyValue& rKV )
1857 {
1858 	xIter->Append( rKV );
1859 	if( bAlert ) SetAttribute( rKV );
1860 }
1861 
1862 SvKeyValueIterator* SfxObjectShell::GetHeaderAttributes()
1863 {
1864 	if( !pImp->xHeaderAttributes.Is() )
1865 	{
1866 		DBG_ASSERT( pMedium, "Kein Medium" );
1867 		pImp->xHeaderAttributes = new SfxHeaderAttributes_Impl( this );
1868 	}
1869 	return ( SvKeyValueIterator*) &pImp->xHeaderAttributes;
1870 }
1871 
1872 void SfxObjectShell::ClearHeaderAttributesForSourceViewHack()
1873 {
1874 	((SfxHeaderAttributes_Impl*)GetHeaderAttributes())
1875 		->ClearForSourceView();
1876 }
1877 
1878 
1879 void SfxObjectShell::SetHeaderAttributesForSourceViewHack()
1880 {
1881 	((SfxHeaderAttributes_Impl*)GetHeaderAttributes())
1882 		->SetAttributes();
1883 }
1884 
1885 sal_Bool SfxObjectShell::IsPreview() const
1886 {
1887 	if ( !pMedium )
1888 		return sal_False;
1889 
1890 	sal_Bool bPreview = sal_False;
1891 	SFX_ITEMSET_ARG( pMedium->GetItemSet(), pFlags, SfxStringItem, SID_OPTIONS, sal_False);
1892 	if ( pFlags )
1893 	{
1894 		// Werte auf einzelne Items verteilen
1895 		String aFileFlags = pFlags->GetValue();
1896 		aFileFlags.ToUpperAscii();
1897 		if ( STRING_NOTFOUND != aFileFlags.Search( 'B' ) )
1898 			bPreview = sal_True;
1899 	}
1900 
1901 	if ( !bPreview )
1902 	{
1903 		SFX_ITEMSET_ARG( pMedium->GetItemSet(), pItem, SfxBoolItem, SID_PREVIEW, sal_False);
1904 		if ( pItem )
1905 			bPreview = pItem->GetValue();
1906 	}
1907 
1908 	return bPreview;
1909 }
1910 
1911 sal_Bool SfxObjectShell::IsSecure()
1912 {
1913 	// Wenn globale Warnung an ist, nach Secure-Referer-Liste gehen
1914 	String aReferer = GetMedium()->GetName();
1915 	if ( !aReferer.Len() )
1916 	{
1917 		// bei neuen Dokumenten das Template als Referer nehmen
1918 		::rtl::OUString aTempl( getDocProperties()->getTemplateURL() );
1919 		if ( aTempl.getLength() )
1920             aReferer = INetURLObject( aTempl ).GetMainURL( INetURLObject::NO_DECODE );
1921 	}
1922 
1923 	INetURLObject aURL( "macro:" );
1924     if ( !aReferer.Len() )
1925         // empty new or embedded document
1926         return sal_True;
1927 
1928 		SvtSecurityOptions aOpt;
1929 
1930 	if( aOpt.GetBasicMode() == eALWAYS_EXECUTE )
1931     	return sal_True;
1932 
1933 	if( aOpt.GetBasicMode() == eNEVER_EXECUTE )
1934     	return sal_False;
1935 
1936 	if ( aOpt.IsSecureURL( aURL.GetMainURL( INetURLObject::NO_DECODE ), aReferer ) )
1937     //if ( SvtSecurityOptions().IsSecureURL( aURL.GetMainURL( INetURLObject::NO_DECODE ), aReferer ) )
1938 	{
1939         if ( GetMedium()->GetContent().is() )
1940         {
1941             Any aAny( ::utl::UCBContentHelper::GetProperty( aURL.GetMainURL( INetURLObject::NO_DECODE ), String( RTL_CONSTASCII_USTRINGPARAM("IsProtected")) ) );
1942             sal_Bool bIsProtected = sal_False;
1943             if ( ( aAny >>= bIsProtected ) && bIsProtected )
1944                 return sal_False;
1945             else
1946                 return sal_True;
1947 		}
1948 		else
1949 			return sal_True;
1950 	}
1951 	else
1952 		return sal_False;
1953 }
1954 
1955 void SfxObjectShell::SetWaitCursor( sal_Bool bSet ) const
1956 {
1957     for( SfxViewFrame* pFrame = SfxViewFrame::GetFirst( this ); pFrame; pFrame = SfxViewFrame::GetNext( *pFrame, this ) )
1958     {
1959         if ( bSet )
1960             pFrame->GetFrame().GetWindow().EnterWait();
1961         else
1962             pFrame->GetFrame().GetWindow().LeaveWait();
1963     }
1964 }
1965 
1966 String SfxObjectShell::GetAPIName() const
1967 {
1968 	INetURLObject aURL( IsDocShared() ? GetSharedFileURL() : ::rtl::OUString( GetMedium()->GetName() ) );
1969     String aName( aURL.GetBase() );
1970     if( !aName.Len() )
1971         aName = aURL.GetURLNoPass();
1972     if ( !aName.Len() )
1973         aName = GetTitle( SFX_TITLE_DETECT );
1974     return aName;
1975 }
1976 
1977 void SfxObjectShell::Invalidate( sal_uInt16 nId )
1978 {
1979     for( SfxViewFrame* pFrame = SfxViewFrame::GetFirst( this ); pFrame; pFrame = SfxViewFrame::GetNext( *pFrame, this ) )
1980         Invalidate_Impl( pFrame->GetBindings(), nId );
1981 }
1982 
1983 bool SfxObjectShell::AdjustMacroMode( const String& /*rScriptType*/, bool bSuppressUI )
1984 {
1985     uno::Reference< task::XInteractionHandler > xInteraction;
1986     if ( pMedium && !bSuppressUI )
1987         xInteraction = pMedium->GetInteractionHandler();
1988 
1989     CheckForBrokenDocSignatures_Impl( xInteraction );
1990 
1991     CheckEncryption_Impl( xInteraction );
1992 
1993     return pImp->aMacroMode.adjustMacroMode( xInteraction );
1994 }
1995 
1996 Window* SfxObjectShell::GetDialogParent( SfxMedium* pLoadingMedium )
1997 {
1998     Window* pWindow = 0;
1999     SfxItemSet* pSet = pLoadingMedium ? pLoadingMedium->GetItemSet() : GetMedium()->GetItemSet();
2000     SFX_ITEMSET_ARG( pSet, pUnoItem, SfxUnoFrameItem, SID_FILLFRAME, sal_False );
2001     if ( pUnoItem )
2002     {
2003         uno::Reference < frame::XFrame > xFrame( pUnoItem->GetFrame() );
2004         pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
2005     }
2006 
2007     if ( !pWindow )
2008     {
2009         SfxFrame* pFrame = 0;
2010         SFX_ITEMSET_ARG( pSet, pFrameItem, SfxFrameItem, SID_DOCFRAME, sal_False );
2011         if( pFrameItem && pFrameItem->GetFrame() )
2012             // get target frame from ItemSet
2013             pFrame = pFrameItem->GetFrame();
2014         else
2015         {
2016             // try the current frame
2017             SfxViewFrame* pView = SfxViewFrame::Current();
2018             if ( !pView || pView->GetObjectShell() != this )
2019                 // get any visible frame
2020                 pView = SfxViewFrame::GetFirst(this);
2021             if ( pView )
2022                 pFrame = &pView->GetFrame();
2023         }
2024 
2025         if ( pFrame )
2026             // get topmost window
2027             pWindow = VCLUnoHelper::GetWindow( pFrame->GetFrameInterface()->getContainerWindow() );
2028     }
2029 
2030     if ( pWindow )
2031     {
2032         // this frame may be invisible, show it if it is allowed
2033         SFX_ITEMSET_ARG( pSet, pHiddenItem, SfxBoolItem, SID_HIDDEN, sal_False );
2034         if ( !pHiddenItem || !pHiddenItem->GetValue() )
2035         {
2036             pWindow->Show();
2037             pWindow->ToTop();
2038         }
2039     }
2040 
2041     return pWindow;
2042 }
2043 
2044 String SfxObjectShell::UpdateTitle( SfxMedium* pMed, sal_uInt16 nDocViewNumber )
2045 {
2046     // Titel des Fensters
2047     String aTitle;
2048     if ( pMed )
2049 	{
2050 		INetURLObject aTmp( pMed->GetName() );
2051         aTitle = aTmp.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DECODE_WITH_CHARSET );
2052 	}
2053     else
2054     {
2055 		pMed = GetMedium();
2056         aTitle = GetTitle(SFX_TITLE_CAPTION);
2057         String aName(aTitle);
2058         if ( nDocViewNumber )
2059         {
2060             aName += ':';
2061             aName += String::CreateFromInt32( nDocViewNumber );
2062         }
2063     }
2064 
2065 	if ( pMed )
2066 	{
2067 		SFX_ITEMSET_ARG( pMed->GetItemSet(), pRepairedDocItem, SfxBoolItem, SID_REPAIRPACKAGE, sal_False );
2068 		if ( pRepairedDocItem && pRepairedDocItem->GetValue() )
2069         	aTitle += String( SfxResId(STR_REPAIREDDOCUMENT) );
2070 	}
2071 
2072 	if ( IsReadOnlyUI() || (pMed && pMed->IsReadOnly()) )
2073         aTitle += String( SfxResId(STR_READONLY) );
2074     else if ( IsDocShared() )
2075         aTitle += String( SfxResId(STR_SHARED) );
2076 
2077     return aTitle;
2078 }
2079 
2080 void SfxObjectShell::SetCreateMode_Impl( SfxObjectCreateMode nMode )
2081 {
2082 	eCreateMode = nMode;
2083 }
2084 
2085 sal_Bool SfxObjectShell::IsInPlaceActive()
2086 {
2087 	if ( eCreateMode != SFX_CREATE_MODE_EMBEDDED )
2088 		return sal_False;
2089 
2090     SfxViewFrame* pFrame = SfxViewFrame::GetFirst( this );
2091     return pFrame && pFrame->GetFrame().IsInPlace();
2092 }
2093 
2094 sal_Bool SfxObjectShell::IsUIActive()
2095 {
2096 	if ( eCreateMode != SFX_CREATE_MODE_EMBEDDED )
2097 		return sal_False;
2098 
2099     SfxViewFrame* pFrame = SfxViewFrame::GetFirst( this );
2100     return pFrame && pFrame->GetFrame().IsInPlace() && pFrame->GetFrame().GetWorkWindow_Impl()->IsVisible_Impl();
2101 }
2102 
2103 void SfxObjectShell::UIActivate( sal_Bool )
2104 {
2105 }
2106 
2107 void SfxObjectShell::InPlaceActivate( sal_Bool )
2108 {
2109 }
2110 
2111 sal_Bool SfxObjectShell::UseInteractionToHandleError(
2112                     const uno::Reference< task::XInteractionHandler >& xHandler,
2113                     sal_uInt32 nError )
2114 {
2115     sal_Bool bResult = sal_False;
2116 
2117     if ( xHandler.is() )
2118     {
2119         try
2120         {
2121             uno::Any aInteraction;
2122             uno::Sequence< uno::Reference< task::XInteractionContinuation > > lContinuations(2);
2123             ::comphelper::OInteractionAbort* pAbort = new ::comphelper::OInteractionAbort();
2124             ::comphelper::OInteractionApprove* pApprove = new ::comphelper::OInteractionApprove();
2125             lContinuations[0] = uno::Reference< task::XInteractionContinuation >(
2126                                  static_cast< task::XInteractionContinuation* >( pAbort ), uno::UNO_QUERY );
2127             lContinuations[1] = uno::Reference< task::XInteractionContinuation >(
2128                                  static_cast< task::XInteractionContinuation* >( pApprove ), uno::UNO_QUERY );
2129 
2130             task::ErrorCodeRequest aErrorCode;
2131             aErrorCode.ErrCode = nError;
2132             aInteraction <<= aErrorCode;
2133             xHandler->handle(::framework::InteractionRequest::CreateRequest (aInteraction,lContinuations));
2134             bResult = pAbort->wasSelected();
2135         }
2136         catch( uno::Exception& )
2137         {}
2138     }
2139 
2140     return bResult;
2141 }
2142 
2143 sal_Bool SfxObjectShell_Impl::NeedsOfficeUpdateDialog()
2144 {
2145     // if the configuration is not available for any reason, the default behavior is to show the message
2146     sal_Bool bResult = sal_True;
2147 
2148     try
2149     {
2150     	uno::Reference< lang::XMultiServiceFactory > xServiceManager( ::comphelper::getProcessServiceFactory(), uno::UNO_SET_THROW );
2151 		uno::Reference< uno::XInterface > xCommonConfig(
2152                         ::comphelper::ConfigurationHelper::openConfig(
2153 							xServiceManager,
2154 							::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/org.openoffice.Office.Common" ) ),
2155 							::comphelper::ConfigurationHelper::E_STANDARD ),
2156                         uno::UNO_SET_THROW );
2157 
2158         ::comphelper::ConfigurationHelper::readRelativeKey(
2159                         xCommonConfig,
2160                         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Load/" ) ),
2161                         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ShowOfficeUpdateDialog" ) ) ) >>= bResult;
2162     }
2163     catch( uno::Exception& )
2164     {
2165     }
2166 
2167 	return bResult;
2168 }
2169 
2170 sal_Int16 SfxObjectShell_Impl::getCurrentMacroExecMode() const
2171 {
2172     sal_Int16 nImposedExecMode( MacroExecMode::NEVER_EXECUTE );
2173 
2174     const SfxMedium* pMedium( rDocShell.GetMedium() );
2175     OSL_PRECOND( pMedium, "SfxObjectShell_Impl::getCurrentMacroExecMode: no medium!" );
2176     if ( pMedium )
2177     {
2178         SFX_ITEMSET_ARG( pMedium->GetItemSet(), pMacroModeItem, SfxUInt16Item, SID_MACROEXECMODE, sal_False);
2179         if ( pMacroModeItem )
2180             nImposedExecMode = pMacroModeItem->GetValue();
2181     }
2182     return nImposedExecMode;
2183 }
2184 
2185 sal_Bool SfxObjectShell_Impl::setCurrentMacroExecMode( sal_uInt16 nMacroMode )
2186 {
2187     const SfxMedium* pMedium( rDocShell.GetMedium() );
2188     OSL_PRECOND( pMedium, "SfxObjectShell_Impl::getCurrentMacroExecMode: no medium!" );
2189     if ( pMedium )
2190     {
2191 		pMedium->GetItemSet()->Put( SfxUInt16Item( SID_MACROEXECMODE, nMacroMode ) );
2192         return sal_True;
2193     }
2194 
2195     return sal_False;
2196 }
2197 
2198 ::rtl::OUString SfxObjectShell_Impl::getDocumentLocation() const
2199 {
2200     ::rtl::OUString sLocation;
2201 
2202     const SfxMedium* pMedium( rDocShell.GetMedium() );
2203     OSL_PRECOND( pMedium, "SfxObjectShell_Impl::getDocumentLocation: no medium!" );
2204     if ( pMedium )
2205     {
2206         sLocation = pMedium->GetName();
2207         if ( !sLocation.getLength() )
2208         {
2209             // for documents made from a template: get the name of the template
2210             sLocation = rDocShell.getDocProperties()->getTemplateURL();
2211         }
2212     }
2213     return sLocation;
2214 }
2215 
2216 uno::Reference< embed::XStorage > SfxObjectShell_Impl::getZipStorageToSign()
2217 {
2218     Reference < embed::XStorage > xStore;
2219 
2220     SfxMedium* pMedium( rDocShell.GetMedium() );
2221     OSL_PRECOND( pMedium, "SfxObjectShell_Impl::getLastCommitDocumentStorage: no medium!" );
2222     if ( pMedium )
2223         xStore = pMedium->GetZipStorageToSign_Impl();
2224 
2225     return xStore;
2226 }
2227 
2228 sal_Bool SfxObjectShell_Impl::documentStorageHasMacros() const
2229 {
2230     return ::sfx2::DocumentMacroMode::storageHasMacros( m_xDocStorage );
2231 }
2232 
2233 Reference< XEmbeddedScripts > SfxObjectShell_Impl::getEmbeddedDocumentScripts() const
2234 {
2235     return Reference< XEmbeddedScripts >( rDocShell.GetModel(), UNO_QUERY );
2236 }
2237 
2238 sal_Int16 SfxObjectShell_Impl::getScriptingSignatureState()
2239 {
2240     sal_Int16 nSignatureState( rDocShell.GetScriptingSignatureState() );
2241 
2242     if ( nSignatureState != SIGNATURESTATE_NOSIGNATURES && m_bMacroSignBroken )
2243     {
2244         // if there is a macro signature it must be handled as broken
2245         nSignatureState = SIGNATURESTATE_SIGNATURES_BROKEN;
2246     }
2247 
2248     return nSignatureState;
2249 }
2250 
2251 sal_Bool SfxObjectShell_Impl::hasTrustedScriptingSignature( sal_Bool bAllowUIToAddAuthor )
2252 {
2253     sal_Bool bResult = sal_False;
2254 
2255     try
2256     {
2257         ::rtl::OUString aVersion;
2258         try
2259         {
2260             uno::Reference < beans::XPropertySet > xPropSet( rDocShell.GetStorage(), uno::UNO_QUERY_THROW );
2261             xPropSet->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Version" ) ) ) >>= aVersion;
2262         }
2263         catch( uno::Exception& )
2264         {
2265         }
2266         uno::Sequence< uno::Any > aArgs( 1 );
2267         aArgs[0] <<= aVersion;
2268 
2269         uno::Reference< security::XDocumentDigitalSignatures > xSigner( comphelper::getProcessServiceFactory()->createInstanceWithArguments( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.security.DocumentDigitalSignatures" ) ), aArgs ), uno::UNO_QUERY_THROW );
2270 
2271         if ( nScriptingSignatureState == SIGNATURESTATE_UNKNOWN
2272           || nScriptingSignatureState == SIGNATURESTATE_SIGNATURES_OK
2273           || nScriptingSignatureState == SIGNATURESTATE_SIGNATURES_NOTVALIDATED )
2274         {
2275             uno::Sequence< security::DocumentSignatureInformation > aInfo = rDocShell.ImplAnalyzeSignature( sal_True, xSigner );
2276 
2277             if ( aInfo.getLength() )
2278             {
2279                 if ( nScriptingSignatureState == SIGNATURESTATE_UNKNOWN )
2280                     nScriptingSignatureState = rDocShell.ImplCheckSignaturesInformation( aInfo );
2281 
2282                 if ( nScriptingSignatureState == SIGNATURESTATE_SIGNATURES_OK
2283                   || nScriptingSignatureState == SIGNATURESTATE_SIGNATURES_NOTVALIDATED )
2284                 {
2285                     for ( sal_Int32 nInd = 0; !bResult && nInd < aInfo.getLength(); nInd++ )
2286                     {
2287                         bResult = xSigner->isAuthorTrusted( aInfo[nInd].Signer );
2288                     }
2289 
2290                     if ( !bResult && bAllowUIToAddAuthor )
2291                     {
2292                         uno::Reference< task::XInteractionHandler > xInteraction;
2293                         if ( rDocShell.GetMedium() )
2294                             xInteraction = rDocShell.GetMedium()->GetInteractionHandler();
2295 
2296                         if ( xInteraction.is() )
2297                         {
2298                             task::DocumentMacroConfirmationRequest aRequest;
2299                             aRequest.DocumentURL = getDocumentLocation();
2300                             aRequest.DocumentStorage = rDocShell.GetMedium()->GetZipStorageToSign_Impl();
2301                             aRequest.DocumentSignatureInformation = aInfo;
2302                             aRequest.DocumentVersion = aVersion;
2303                             aRequest.Classification = task::InteractionClassification_QUERY;
2304                             bResult = SfxMedium::CallApproveHandler( xInteraction, uno::makeAny( aRequest ), sal_True );
2305                         }
2306                     }
2307                 }
2308             }
2309         }
2310     }
2311     catch( uno::Exception& )
2312     {}
2313 
2314     return bResult;
2315 }
2316 
2317 void SfxObjectShell_Impl::showBrokenSignatureWarning( const uno::Reference< task::XInteractionHandler >& _rxInteraction ) const
2318 {
2319     if  ( !bSignatureErrorIsShown )
2320     {
2321         SfxObjectShell::UseInteractionToHandleError( _rxInteraction, ERRCODE_SFX_BROKENSIGNATURE );
2322 	    const_cast< SfxObjectShell_Impl* >( this )->bSignatureErrorIsShown = sal_True;
2323     }
2324 }
2325 
2326 void SfxObjectShell::AddLog( const ::rtl::OUString& aMessage )
2327 {
2328     if ( !pImp->m_xLogRing.is() )
2329     {
2330         try
2331         {
2332             ::comphelper::ComponentContext aContext( ::comphelper::getProcessServiceFactory() );
2333             if ( aContext.is() )
2334                 pImp->m_xLogRing.set( aContext.getSingleton( "com.sun.star.logging.DocumentIOLogRing" ), UNO_QUERY_THROW );
2335         }
2336         catch( uno::Exception& )
2337         {}
2338     }
2339 
2340     if ( pImp->m_xLogRing.is() )
2341         pImp->m_xLogRing->logString( aMessage );
2342 }
2343 
2344 namespace {
2345 
2346 void WriteStringInStream( const uno::Reference< io::XOutputStream >& xOutStream, const ::rtl::OUString& aString )
2347 {
2348     if ( xOutStream.is() )
2349     {
2350         ::rtl::OString aStrLog = ::rtl::OUStringToOString( aString, RTL_TEXTENCODING_UTF8 );
2351         uno::Sequence< sal_Int8 > aLogData( (const sal_Int8*)aStrLog.getStr(), aStrLog.getLength() );
2352         xOutStream->writeBytes( aLogData );
2353 
2354         aLogData.realloc( 1 );
2355         aLogData[0] = '\n';
2356         xOutStream->writeBytes( aLogData );
2357     }
2358 }
2359 
2360 }
2361 
2362 void SfxObjectShell::StoreLog()
2363 {
2364     if ( !pImp->m_xLogRing.is() )
2365     {
2366         try
2367         {
2368             ::comphelper::ComponentContext aContext( ::comphelper::getProcessServiceFactory() );
2369             if ( aContext.is() )
2370                 pImp->m_xLogRing.set( aContext.getSingleton( "com.sun.star.logging.DocumentIOLogRing" ), UNO_QUERY_THROW );
2371         }
2372         catch( uno::Exception& )
2373         {}
2374     }
2375 
2376     if ( pImp->m_xLogRing.is() )
2377     {
2378         ::rtl::OUString aFileURL = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "${$OOO_BASE_DIR/program/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}" ) );
2379 //#ifdef WNT
2380 //        ::rtl::OUString aFileURL = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "${$OOO_BASE_DIR/program/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}" ) );
2381 //#else
2382 //        ::rtl::OUString aFileURL = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "${$OOO_BASE_DIR/program/bootstraprc:UserInstallation}" ) );
2383 //#endif
2384         ::rtl::Bootstrap::expandMacros( aFileURL );
2385 
2386 //#ifdef WNT
2387 //        ::rtl::OUString aBuildID = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "${$OOO_BASE_DIR/program/setup.ini:buildid}" ) );
2388 //#else
2389 //        ::rtl::OUString aBuildID = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "${$OOO_BASE_DIR/program/setuprc:buildid}" ) );
2390 //#endif
2391         ::rtl::OUString aBuildID = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "${$OOO_BASE_DIR/program/" SAL_CONFIGFILE("setup") ":buildid}" ) );
2392         ::rtl::Bootstrap::expandMacros( aBuildID );
2393 
2394         if ( aFileURL.getLength() )
2395         {
2396             aFileURL += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/temp/document_io_logring.txt" ) );
2397             try
2398             {
2399                 uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory(), uno::UNO_SET_THROW );
2400                 uno::Reference< ucb::XSimpleFileAccess > xSimpleFileAccess( xFactory->createInstance( DEFINE_CONST_UNICODE( "com.sun.star.ucb.SimpleFileAccess" ) ), uno::UNO_QUERY_THROW );
2401                 uno::Reference< io::XStream > xStream( xSimpleFileAccess->openFileReadWrite( aFileURL ), uno::UNO_SET_THROW );
2402                 uno::Reference< io::XOutputStream > xOutStream( xStream->getOutputStream(), uno::UNO_SET_THROW );
2403                 uno::Reference< io::XTruncate > xTruncate( xOutStream, uno::UNO_QUERY_THROW );
2404                 xTruncate->truncate();
2405 
2406                 if ( aBuildID.getLength() )
2407                     WriteStringInStream( xOutStream, aBuildID );
2408 
2409                 uno::Sequence< ::rtl::OUString > aLogSeq = pImp->m_xLogRing->getCollectedLog();
2410                 for ( sal_Int32 nInd = 0; nInd < aLogSeq.getLength(); nInd++ )
2411                     WriteStringInStream( xOutStream, aLogSeq[nInd] );
2412             }
2413             catch( uno::Exception& )
2414             {}
2415         }
2416     }
2417 }
2418