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