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