xref: /AOO41X/main/scripting/source/protocolhandler/scripthandler.cxx (revision 1ecadb572e7010ff3b3382ad9bf179dbc6efadbb)
1 /*************************************************************************
2 *
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * Copyright 2000, 2010 Oracle and/or its affiliates.
6  *
7  * OpenOffice.org - a multi-platform office productivity suite
8  *
9  * This file is part of OpenOffice.org.
10  *
11  * OpenOffice.org is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU Lesser General Public License version 3
13  * only, as published by the Free Software Foundation.
14  *
15  * OpenOffice.org is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Lesser General Public License version 3 for more details
19  * (a copy is included in the LICENSE file that accompanied this code).
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * version 3 along with OpenOffice.org.  If not, see
23  * <http://www.openoffice.org/license.html>
24  * for a copy of the LGPLv3 License.
25  *
26 ************************************************************************/
27 
28 // MARKER(update_precomp.py): autogen include statement, do not remove
29 #include "precompiled_scripting.hxx"
30 #include "scripthandler.hxx"
31 
32 #include <osl/mutex.hxx>
33 
34 #include <com/sun/star/frame/DispatchResultEvent.hpp>
35 #include <com/sun/star/frame/DispatchResultState.hpp>
36 #include <com/sun/star/frame/XController.hpp>
37 #include <com/sun/star/frame/XModel.hpp>
38 
39 #include <com/sun/star/document/XEmbeddedScripts.hpp>
40 #include <com/sun/star/document/XScriptInvocationContext.hpp>
41 
42 #include <com/sun/star/lang/XSingleServiceFactory.hpp>
43 
44 #include <com/sun/star/script/provider/XScriptProviderSupplier.hpp>
45 #include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
46 #include <com/sun/star/script/provider/ScriptFrameworkErrorType.hpp>
47 
48 #include <sfx2/objsh.hxx>
49 #include <sfx2/frame.hxx>
50 #include <sfx2/sfxdlg.hxx>
51 #include <vcl/abstdlg.hxx>
52 #include <tools/diagnose_ex.h>
53 
54 #include <cppuhelper/factory.hxx>
55 #include <cppuhelper/exc_hlp.hxx>
56 #include <util/util.hxx>
57 #include <framework/documentundoguard.hxx>
58 
59 #include "com/sun/star/uno/XComponentContext.hpp"
60 #include "com/sun/star/uri/XUriReference.hpp"
61 #include "com/sun/star/uri/XUriReferenceFactory.hpp"
62 #include "com/sun/star/uri/XVndSunStarScriptUrl.hpp"
63 #include "com/sun/star/beans/XPropertySet.hpp"
64 
65 using namespace ::com::sun::star;
66 using namespace ::com::sun::star::uno;
67 using namespace ::com::sun::star::frame;
68 using namespace ::com::sun::star::util;
69 using namespace ::com::sun::star::beans;
70 using namespace ::com::sun::star::lang;
71 using namespace ::com::sun::star::script;
72 using namespace ::com::sun::star::script::provider;
73 using namespace ::com::sun::star::document;
74 
75 namespace scripting_protocolhandler
76 {
77 
78 const sal_Char * const MYSERVICENAME = "com.sun.star.frame.ProtocolHandler";
79 const sal_Char * const MYIMPLNAME = "com.sun.star.comp.ScriptProtocolHandler";
80 const sal_Char * MYSCHEME = "vnd.sun.star.script";
81 const sal_Int32 MYSCHEME_LEN = 20;
82 
83 void SAL_CALL ScriptProtocolHandler::initialize(
84     const css::uno::Sequence < css::uno::Any >& aArguments )
85     throw ( css::uno::Exception )
86 {
87     if ( m_bInitialised )
88     {
89         return ;
90     }
91 
92     // first argument contains a reference to the frame (may be empty or the desktop,
93     // but usually it's a "real" frame)
94     if ( aArguments.getLength() &&
95          sal_False == ( aArguments[ 0 ] >>= m_xFrame ) )
96     {
97         ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::initialize: could not extract reference to the frame" );
98         throw RuntimeException( temp, Reference< XInterface >() );
99     }
100 
101     ENSURE_OR_THROW( m_xFactory.is(), "ScriptProtocolHandler::initialize: No Service Manager available" );
102     m_bInitialised = true;
103 }
104 
105 Reference< XDispatch > SAL_CALL ScriptProtocolHandler::queryDispatch(
106     const URL& aURL, const ::rtl::OUString& sTargetFrameName, sal_Int32 nSearchFlags )
107     throw( ::com::sun::star::uno::RuntimeException )
108 {
109 	(void)sTargetFrameName;
110 	(void)nSearchFlags;
111 
112     Reference< XDispatch > xDispatcher;
113     // get scheme of url
114 
115     Reference< uri::XUriReferenceFactory > xFac (
116          m_xFactory->createInstance( rtl::OUString::createFromAscii(
117             "com.sun.star.uri.UriReferenceFactory") ) , UNO_QUERY );
118     if ( xFac.is() )
119     {
120         Reference<  uri::XUriReference > uriRef(
121             xFac->parse( aURL.Complete ), UNO_QUERY );
122         if ( uriRef.is() )
123         {
124             if ( uriRef->getScheme().equals( ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYSCHEME ) ) )
125             {
126                 xDispatcher = this;
127             }
128         }
129     }
130 
131     return xDispatcher;
132 }
133 
134 Sequence< Reference< XDispatch > > SAL_CALL
135 ScriptProtocolHandler::queryDispatches(
136 const Sequence < DispatchDescriptor >& seqDescriptor )
137 throw( RuntimeException )
138 {
139     sal_Int32 nCount = seqDescriptor.getLength();
140     Sequence< Reference< XDispatch > > lDispatcher( nCount );
141     for ( sal_Int32 i = 0; i < nCount; ++i )
142     {
143         lDispatcher[ i ] = this->queryDispatch( seqDescriptor[ i ].FeatureURL,
144                                                 seqDescriptor[ i ].FrameName,
145                                                 seqDescriptor[ i ].SearchFlags );
146     }
147     return lDispatcher;
148 }
149 
150 void SAL_CALL ScriptProtocolHandler::dispatchWithNotification(
151     const URL& aURL, const Sequence < PropertyValue >& lArgs,
152     const Reference< XDispatchResultListener >& xListener )
153     throw ( RuntimeException )
154 {
155 
156     sal_Bool bSuccess = sal_False;
157     Any invokeResult;
158 	bool bCaughtException = sal_False;
159 	Any aException;
160 
161     if ( m_bInitialised )
162     {
163         try
164         {
165             bool bIsDocumentScript = ( aURL.Complete.indexOfAsciiL( RTL_CONSTASCII_STRINGPARAM( "document" ) ) !=-1 );
166                 // TODO: isn't this somewhat strange? This should be a test for a location=document parameter, shouldn't it?
167 
168             if ( bIsDocumentScript )
169             {
170                 // obtain the component for our security check
171                 Reference< XEmbeddedScripts > xDocumentScripts;
172                 if ( getScriptInvocation() )
173                     xDocumentScripts.set( m_xScriptInvocation->getScriptContainer(), UNO_SET_THROW );
174 
175                 OSL_ENSURE( xDocumentScripts.is(), "ScriptProtocolHandler::dispatchWithNotification: can't do the security check!" );
176                 if ( !xDocumentScripts.is() || !xDocumentScripts->getAllowMacroExecution() )
177                     return;
178             }
179 
180             // Creates a ScriptProvider ( if one is not created allready )
181             createScriptProvider();
182 
183             Reference< provider::XScript > xFunc =
184                 m_xScriptProvider->getScript( aURL.Complete );
185             ENSURE_OR_THROW( xFunc.is(),
186                 "ScriptProtocolHandler::dispatchWithNotification: validate xFunc - unable to obtain XScript interface" );
187 
188 
189             Sequence< Any > inArgs( 0 );
190             Sequence< Any > outArgs( 0 );
191             Sequence< sal_Int16 > outIndex;
192 
193             if ( lArgs.getLength() > 0 )
194             {
195                int argCount = 0;
196                for ( int index = 0; index < lArgs.getLength(); index++ )
197                {
198                    // Sometimes we get a propertyval with name = "Referer"
199                    // this is not an argument to be passed to script, so
200                    // ignore.
201                    if ( lArgs[ index ].Name.compareToAscii("Referer") != 0  ||
202                         lArgs[ index ].Name.getLength() == 0 )
203                    {
204                        inArgs.realloc( ++argCount );
205                        inArgs[ argCount - 1 ] = lArgs[ index ].Value;
206                    }
207                }
208             }
209 
210             // attempt to protect the document against the script tampering with its Undo Context
211             ::std::auto_ptr< ::framework::DocumentUndoGuard > pUndoGuard;
212             if ( bIsDocumentScript )
213                 pUndoGuard.reset( new ::framework::DocumentUndoGuard( m_xScriptInvocation ) );
214 
215             bSuccess = sal_False;
216             while ( !bSuccess )
217             {
218                 Any aFirstCaughtException;
219                 try
220                 {
221                     invokeResult = xFunc->invoke( inArgs, outIndex, outArgs );
222                     bSuccess = sal_True;
223                 }
224                 catch( const provider::ScriptFrameworkErrorException& se )
225                 {
226                     if  ( !aFirstCaughtException.hasValue() )
227                         aFirstCaughtException = ::cppu::getCaughtException();
228 
229                     if ( se.errorType != provider::ScriptFrameworkErrorType::NO_SUCH_SCRIPT )
230                         // the only condition which allows us to retry is if there is no method with the
231                         // given name/signature
232                         ::cppu::throwException( aFirstCaughtException );
233 
234                     if ( inArgs.getLength() == 0 )
235                         // no chance to retry if we can't strip more in-args
236                         ::cppu::throwException( aFirstCaughtException );
237 
238                     // strip one argument, then retry
239                     inArgs.realloc( inArgs.getLength() - 1 );
240                 }
241             }
242         }
243         // Office doesn't handle exceptions rethrown here very well, it cores,
244         // all we can is log them and then set fail for the dispatch event!
245         // (if there is a listener of course)
246         catch ( const Exception & e )
247         {
248             aException = ::cppu::getCaughtException();
249 
250             ::rtl::OUString reason = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ScriptProtocolHandler::dispatch: caught " ) );
251 
252             invokeResult <<= reason.concat( aException.getValueTypeName() ).concat( e.Message );
253 
254 			bCaughtException = sal_True;
255         }
256     }
257     else
258     {
259         ::rtl::OUString reason = ::rtl::OUString::createFromAscii(
260         "ScriptProtocolHandler::dispatchWithNotification failed, ScriptProtocolHandler not initialised"
261         );
262         invokeResult <<= reason;
263     }
264 
265 	if ( bCaughtException )
266 	{
267 		SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
268 
269 		if ( pFact != NULL )
270 		{
271 			VclAbstractDialog* pDlg =
272 				pFact->CreateScriptErrorDialog( NULL, aException );
273 
274 			if ( pDlg != NULL )
275 			{
276 				pDlg->Execute();
277 				delete pDlg;
278 			}
279 		}
280    	}
281 
282     if ( xListener.is() )
283     {
284         // always call dispatchFinished(), because we didn't load a document but
285         // executed a macro instead!
286         ::com::sun::star::frame::DispatchResultEvent aEvent;
287 
288         aEvent.Source = static_cast< ::cppu::OWeakObject* >( this );
289         aEvent.Result = invokeResult;
290         if ( bSuccess )
291         {
292             aEvent.State = ::com::sun::star::frame::DispatchResultState::SUCCESS;
293         }
294         else
295         {
296             aEvent.State = ::com::sun::star::frame::DispatchResultState::FAILURE;
297         }
298 
299         try
300         {
301             xListener->dispatchFinished( aEvent ) ;
302         }
303         catch(RuntimeException & e)
304         {
305             OSL_TRACE(
306             "ScriptProtocolHandler::dispatchWithNotification: caught RuntimeException"
307             "while dispatchFinished %s",
308             ::rtl::OUStringToOString( e.Message,
309             RTL_TEXTENCODING_ASCII_US ).pData->buffer );
310         }
311     }
312 }
313 
314 void SAL_CALL ScriptProtocolHandler::dispatch(
315 const URL& aURL, const Sequence< PropertyValue >& lArgs )
316 throw ( RuntimeException )
317 {
318     dispatchWithNotification( aURL, lArgs, Reference< XDispatchResultListener >() );
319 }
320 
321 void SAL_CALL ScriptProtocolHandler::addStatusListener(
322 const Reference< XStatusListener >& xControl, const URL& aURL )
323 throw ( RuntimeException )
324 {
325 	(void)xControl;
326 	(void)aURL;
327 
328     // implement if status is supported
329 }
330 
331 void SAL_CALL ScriptProtocolHandler::removeStatusListener(
332 const Reference< XStatusListener >& xControl, const URL& aURL )
333 throw ( RuntimeException )
334 {
335 	(void)xControl;
336 	(void)aURL;
337 }
338 
339 bool
340 ScriptProtocolHandler::getScriptInvocation()
341 {
342     if ( !m_xScriptInvocation.is() && m_xFrame.is() )
343     {
344         Reference< XController > xController = m_xFrame->getController();
345         if ( xController .is() )
346         {
347             // try to obtain an XScriptInvocationContext interface, preferred from the
348             // mode, then from the controller
349             if ( !m_xScriptInvocation.set( xController->getModel(), UNO_QUERY ) )
350                 m_xScriptInvocation.set( xController, UNO_QUERY );
351         }
352     }
353     return m_xScriptInvocation.is();
354 }
355 
356 void ScriptProtocolHandler::createScriptProvider()
357 {
358     if ( m_xScriptProvider.is() )
359         return;
360 
361     try
362     {
363         // first, ask the component supporting the XScriptInvocationContext interface
364         // (if there is one) for a script provider
365         if ( getScriptInvocation() )
366         {
367             Reference< XScriptProviderSupplier > xSPS( m_xScriptInvocation, UNO_QUERY );
368             if ( xSPS.is() )
369                 m_xScriptProvider = xSPS->getScriptProvider();
370         }
371 
372         // second, ask the model in our frame
373         if ( !m_xScriptProvider.is() && m_xFrame.is() )
374         {
375             Reference< XController > xController = m_xFrame->getController();
376             if ( xController .is() )
377             {
378                 Reference< XScriptProviderSupplier > xSPS( xController->getModel(), UNO_QUERY );
379                 if ( xSPS.is() )
380                     m_xScriptProvider = xSPS->getScriptProvider();
381             }
382         }
383 
384 
385         // as a fallback, ask the controller
386         if ( !m_xScriptProvider.is() && m_xFrame.is() )
387         {
388             Reference< XScriptProviderSupplier > xSPS( m_xFrame->getController(), UNO_QUERY );
389             if ( xSPS.is() )
390                 m_xScriptProvider = xSPS->getScriptProvider();
391         }
392 
393         // if nothing of this is successful, use the master script provider
394         if ( !m_xScriptProvider.is() )
395         {
396             Reference< XPropertySet > xProps( m_xFactory, UNO_QUERY_THROW );
397 
398             ::rtl::OUString dc(
399                 RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ) );
400 
401             Reference< XComponentContext > xCtx(
402                 xProps->getPropertyValue( dc ), UNO_QUERY_THROW );
403 
404             ::rtl::OUString tmspf = ::rtl::OUString::createFromAscii(
405                 "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory");
406 
407             Reference< provider::XScriptProviderFactory > xFac(
408                 xCtx->getValueByName( tmspf ), UNO_QUERY_THROW );
409 
410             Any aContext;
411             if ( getScriptInvocation() )
412                 aContext = makeAny( m_xScriptInvocation );
413             m_xScriptProvider = Reference< provider::XScriptProvider > (
414                 xFac->createScriptProvider( aContext ), UNO_QUERY_THROW );
415         }
416     }
417     catch ( RuntimeException & e )
418     {
419         ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::createScriptProvider(),  " );
420         throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
421     }
422     catch ( Exception & e )
423     {
424         ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::createScriptProvider: " );
425         throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
426     }
427 }
428 
429 ScriptProtocolHandler::ScriptProtocolHandler(
430 Reference< css::lang::XMultiServiceFactory > const& rFact ) :
431 m_bInitialised( false ), m_xFactory( rFact )
432 {
433 }
434 
435 ScriptProtocolHandler::~ScriptProtocolHandler()
436 {
437 }
438 
439 /* XServiceInfo */
440 ::rtl::OUString SAL_CALL ScriptProtocolHandler::getImplementationName( )
441 throw( RuntimeException )
442 {
443     return impl_getStaticImplementationName();
444 }
445 
446 /* XServiceInfo */
447 sal_Bool SAL_CALL ScriptProtocolHandler::supportsService(
448 const ::rtl::OUString& sServiceName )
449 throw( RuntimeException )
450 {
451     Sequence< ::rtl::OUString > seqServiceNames = getSupportedServiceNames();
452     const ::rtl::OUString* pArray = seqServiceNames.getConstArray();
453     for ( sal_Int32 nCounter = 0; nCounter < seqServiceNames.getLength(); nCounter++ )
454     {
455         if ( pArray[ nCounter ] == sServiceName )
456         {
457             return sal_True ;
458         }
459     }
460 
461     return sal_False ;
462 }
463 
464 /* XServiceInfo */
465 Sequence< ::rtl::OUString > SAL_CALL ScriptProtocolHandler::getSupportedServiceNames()
466 throw( RuntimeException )
467 {
468     return impl_getStaticSupportedServiceNames();
469 }
470 
471 /* Helper for XServiceInfo */
472 Sequence< ::rtl::OUString > ScriptProtocolHandler::impl_getStaticSupportedServiceNames()
473 {
474     ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
475     Sequence< ::rtl::OUString > seqServiceNames( 1 );
476     seqServiceNames.getArray() [ 0 ] =
477         ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYSERVICENAME );
478     return seqServiceNames ;
479 }
480 
481 /* Helper for XServiceInfo */
482 ::rtl::OUString ScriptProtocolHandler::impl_getStaticImplementationName()
483 {
484     return ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYIMPLNAME );
485 }
486 
487 /* Helper for registry */
488 Reference< XInterface > SAL_CALL ScriptProtocolHandler::impl_createInstance(
489 const Reference< css::lang::XMultiServiceFactory >& xServiceManager )
490 throw( RuntimeException )
491 {
492     return Reference< XInterface > ( *new ScriptProtocolHandler( xServiceManager ) );
493 }
494 
495 /* Factory for registration */
496 Reference< XSingleServiceFactory > ScriptProtocolHandler::impl_createFactory(
497 const Reference< XMultiServiceFactory >& xServiceManager )
498 {
499     Reference< XSingleServiceFactory > xReturn (
500         cppu::createSingleFactory( xServiceManager,
501             ScriptProtocolHandler::impl_getStaticImplementationName(),
502             ScriptProtocolHandler::impl_createInstance,
503             ScriptProtocolHandler::impl_getStaticSupportedServiceNames() )
504     );
505     return xReturn;
506 }
507 
508 } // namespace scripting_protocolhandler
509 
510 /* exported functions for registration */
511 extern "C"
512 {
513 
514 #undef css
515 #define css ::com::sun::star
516 
517     void SAL_CALL component_getImplementationEnvironment(
518         const sal_Char** ppEnvironmentTypeName, uno_Environment** ppEnvironment )
519     {
520 		(void)ppEnvironment;
521 
522         *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
523     }
524 
525     void* SAL_CALL component_getFactory( const sal_Char * pImplementationName ,
526                                          void * pServiceManager ,
527                                          void * pRegistryKey )
528     {
529 		(void)pRegistryKey;
530 
531         // Set default return value for this operation - if it failed.
532         void * pReturn = NULL ;
533 
534         if (
535             ( pImplementationName != NULL ) &&
536             ( pServiceManager != NULL )
537         )
538         {
539             // Define variables which are used in following macros.
540             ::com::sun::star::uno::Reference<
541             ::com::sun::star::lang::XSingleServiceFactory > xFactory ;
542             ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
543             xServiceManager( reinterpret_cast<
544             ::com::sun::star::lang::XMultiServiceFactory* >( pServiceManager ) ) ;
545 
546             if ( ::scripting_protocolhandler::ScriptProtocolHandler::impl_getStaticImplementationName().equals(
547                 ::rtl::OUString::createFromAscii( pImplementationName ) ) )
548             {
549                 xFactory = ::scripting_protocolhandler::ScriptProtocolHandler::impl_createFactory( xServiceManager );
550             }
551 
552             // Factory is valid - service was found.
553             if ( xFactory.is() )
554             {
555                 xFactory->acquire();
556                 pReturn = xFactory.get();
557             }
558         }
559 
560         // Return with result of this operation.
561         return pReturn ;
562     }
563 } // extern "C"
564 
565 
566