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