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