nss: upgrade to release 3.73
[LibreOffice.git] / scripting / source / protocolhandler / scripthandler.cxx
blobb163a2000ccedec0c408c4156b4853ac9b135739
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include "scripthandler.hxx"
22 #include <com/sun/star/frame/DispatchResultEvent.hpp>
23 #include <com/sun/star/frame/DispatchResultState.hpp>
24 #include <com/sun/star/frame/XController.hpp>
25 #include <com/sun/star/frame/XModel.hpp>
27 #include <com/sun/star/document/XEmbeddedScripts.hpp>
28 #include <com/sun/star/document/XScriptInvocationContext.hpp>
30 #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
31 #include <com/sun/star/lang/XSingleServiceFactory.hpp>
32 #include <com/sun/star/script/provider/ScriptFrameworkErrorException.hpp>
33 #include <com/sun/star/script/provider/XScriptProviderSupplier.hpp>
34 #include <com/sun/star/script/provider/theMasterScriptProviderFactory.hpp>
35 #include <com/sun/star/script/provider/ScriptFrameworkErrorType.hpp>
37 #include <sfx2/objsh.hxx>
38 #include <sfx2/frame.hxx>
39 #include <sfx2/sfxdlg.hxx>
40 #include <vcl/abstdlg.hxx>
41 #include <tools/diagnose_ex.h>
43 #include <comphelper/processfactory.hxx>
44 #include <cppuhelper/factory.hxx>
45 #include <cppuhelper/exc_hlp.hxx>
46 #include <cppuhelper/supportsservice.hxx>
47 #include <framework/documentundoguard.hxx>
48 #include <officecfg/Office/Common.hxx>
50 #include <com/sun/star/uri/XUriReference.hpp>
51 #include <com/sun/star/uri/XVndSunStarScriptUrlReference.hpp>
52 #include <com/sun/star/uri/UriReferenceFactory.hpp>
54 #include <memory>
56 using namespace ::com::sun::star;
57 using namespace ::com::sun::star::uno;
58 using namespace ::com::sun::star::frame;
59 using namespace ::com::sun::star::util;
60 using namespace ::com::sun::star::beans;
61 using namespace ::com::sun::star::lang;
62 using namespace ::com::sun::star::script;
63 using namespace ::com::sun::star::script::provider;
64 using namespace ::com::sun::star::document;
66 namespace scripting_protocolhandler
69 void SAL_CALL ScriptProtocolHandler::initialize(
70 const css::uno::Sequence < css::uno::Any >& aArguments )
72 if ( m_bInitialised )
74 return ;
77 // first argument contains a reference to the frame (may be empty or the desktop,
78 // but usually it's a "real" frame)
79 if ( aArguments.hasElements() && !( aArguments[ 0 ] >>= m_xFrame ) )
81 throw RuntimeException( "ScriptProtocolHandler::initialize: could not extract reference to the frame" );
84 ENSURE_OR_THROW( m_xContext.is(), "ScriptProtocolHandler::initialize: No Service Manager available" );
85 m_bInitialised = true;
88 Reference< XDispatch > SAL_CALL ScriptProtocolHandler::queryDispatch(
89 const URL& aURL, const OUString&, sal_Int32 )
91 Reference< XDispatch > xDispatcher;
92 // get scheme of url
94 Reference< uri::XUriReferenceFactory > xFac = uri::UriReferenceFactory::create( m_xContext );
95 Reference< uri::XUriReference > uriRef = xFac->parse( aURL.Complete );
96 if ( uriRef.is() )
98 if ( uriRef->getScheme() == "vnd.sun.star.script" )
100 xDispatcher = this;
104 return xDispatcher;
107 Sequence< Reference< XDispatch > > SAL_CALL
108 ScriptProtocolHandler::queryDispatches(
109 const Sequence < DispatchDescriptor >& seqDescriptor )
111 sal_Int32 nCount = seqDescriptor.getLength();
112 Sequence< Reference< XDispatch > > lDispatcher( nCount );
113 std::transform(seqDescriptor.begin(), seqDescriptor.end(), lDispatcher.begin(),
114 [this](const DispatchDescriptor& rDescr) -> Reference<XDispatch> {
115 return queryDispatch(rDescr.FeatureURL, rDescr.FrameName, rDescr.SearchFlags); });
116 return lDispatcher;
119 void SAL_CALL ScriptProtocolHandler::dispatchWithNotification(
120 const URL& aURL, const Sequence < PropertyValue >& lArgs,
121 const Reference< XDispatchResultListener >& xListener )
123 if (officecfg::Office::Common::Security::Scripting::DisableMacrosExecution::get())
124 return;
126 bool bSuccess = false;
127 Any invokeResult;
128 bool bCaughtException = false;
129 Any aException;
131 if ( m_bInitialised )
135 css::uno::Reference<css::uri::XUriReferenceFactory> urifac(
136 css::uri::UriReferenceFactory::create(m_xContext));
137 css::uno::Reference<css::uri::XVndSunStarScriptUrlReference> uri(
138 urifac->parse(aURL.Complete), css::uno::UNO_QUERY_THROW);
139 auto const loc = uri->getParameter("location");
140 bool bIsDocumentScript = loc == "document";
142 if ( bIsDocumentScript )
144 // obtain the component for our security check
145 Reference< XEmbeddedScripts > xDocumentScripts;
146 if ( getScriptInvocation() )
147 xDocumentScripts.set( m_xScriptInvocation->getScriptContainer(), UNO_SET_THROW );
149 OSL_ENSURE( xDocumentScripts.is(), "ScriptProtocolHandler::dispatchWithNotification: can't do the security check!" );
150 if ( !xDocumentScripts.is() || !xDocumentScripts->getAllowMacroExecution() )
152 if ( xListener.is() )
154 css::frame::DispatchResultEvent aEvent(
155 static_cast< ::cppu::OWeakObject* >( this ),
156 css::frame::DispatchResultState::FAILURE,
157 invokeResult );
160 xListener->dispatchFinished( aEvent ) ;
162 catch(const RuntimeException &)
164 TOOLS_WARN_EXCEPTION("scripting",
165 "ScriptProtocolHandler::dispatchWithNotification: caught RuntimeException"
166 "while dispatchFinished with failure of the execution");
169 return;
173 // Creates a ScriptProvider ( if one is not created already )
174 createScriptProvider();
176 Reference< provider::XScript > xFunc =
177 m_xScriptProvider->getScript( aURL.Complete );
178 ENSURE_OR_THROW( xFunc.is(),
179 "ScriptProtocolHandler::dispatchWithNotification: validate xFunc - unable to obtain XScript interface" );
182 Sequence< Any > inArgs( 0 );
183 Sequence< Any > outArgs( 0 );
184 Sequence< sal_Int16 > outIndex;
186 if ( lArgs.hasElements() )
188 int argCount = 0;
189 for ( const auto& rArg : lArgs )
191 // Sometimes we get a propertyval with name = "Referer" or "SynchronMode". These
192 // are not actual arguments to be passed to script, but flags describing the
193 // call, so ignore. Who thought that passing such "meta-arguments" mixed in with
194 // real arguments was a good idea?
195 if ( (rArg.Name != "Referer" &&
196 rArg.Name != "SynchronMode") ||
197 rArg.Name.isEmpty() ) //TODO:???
199 inArgs.realloc( ++argCount );
200 inArgs[ argCount - 1 ] = rArg.Value;
205 // attempt to protect the document against the script tampering with its Undo Context
206 std::unique_ptr< ::framework::DocumentUndoGuard > pUndoGuard;
207 if ( bIsDocumentScript )
208 pUndoGuard.reset( new ::framework::DocumentUndoGuard( m_xScriptInvocation ) );
210 bSuccess = false;
211 while ( !bSuccess )
213 std::exception_ptr aFirstCaughtException;
216 invokeResult = xFunc->invoke( inArgs, outIndex, outArgs );
217 bSuccess = true;
219 catch( const provider::ScriptFrameworkErrorException& se )
221 if (!aFirstCaughtException)
222 aFirstCaughtException = std::current_exception();
224 if ( se.errorType != provider::ScriptFrameworkErrorType::NO_SUCH_SCRIPT )
225 // the only condition which allows us to retry is if there is no method with the
226 // given name/signature
227 std::rethrow_exception(aFirstCaughtException);
229 if ( !inArgs.hasElements() )
230 // no chance to retry if we can't strip more in-args
231 std::rethrow_exception(aFirstCaughtException);
233 // strip one argument, then retry
234 inArgs.realloc( inArgs.getLength() - 1 );
238 // Office doesn't handle exceptions rethrown here very well, it cores,
239 // all we can is log them and then set fail for the dispatch event!
240 // (if there is a listener of course)
241 catch ( const Exception & e )
243 aException = ::cppu::getCaughtException();
245 invokeResult <<= "ScriptProtocolHandler::dispatch: caught "
246 + aException.getValueTypeName() + ": " + e.Message;
248 bCaughtException = true;
251 else
253 invokeResult <<= OUString(
254 "ScriptProtocolHandler::dispatchWithNotification failed, ScriptProtocolHandler not initialised"
258 if ( bCaughtException )
260 SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
261 pFact->ShowAsyncScriptErrorDialog( nullptr, aException );
264 if ( !xListener.is() )
265 return;
267 // always call dispatchFinished(), because we didn't load a document but
268 // executed a macro instead!
269 css::frame::DispatchResultEvent aEvent;
271 aEvent.Source = static_cast< ::cppu::OWeakObject* >( this );
272 aEvent.Result = invokeResult;
273 if ( bSuccess )
275 aEvent.State = css::frame::DispatchResultState::SUCCESS;
277 else
279 aEvent.State = css::frame::DispatchResultState::FAILURE;
284 xListener->dispatchFinished( aEvent ) ;
286 catch(const RuntimeException &)
288 TOOLS_WARN_EXCEPTION("scripting",
289 "ScriptProtocolHandler::dispatchWithNotification: caught RuntimeException"
290 "while dispatchFinished" );
294 void SAL_CALL ScriptProtocolHandler::dispatch(
295 const URL& aURL, const Sequence< PropertyValue >& lArgs )
297 dispatchWithNotification( aURL, lArgs, Reference< XDispatchResultListener >() );
300 void SAL_CALL ScriptProtocolHandler::addStatusListener(
301 const Reference< XStatusListener >&, const URL& )
303 // implement if status is supported
306 void SAL_CALL ScriptProtocolHandler::removeStatusListener(
307 const Reference< XStatusListener >&, const URL& )
310 bool
311 ScriptProtocolHandler::getScriptInvocation()
313 if ( !m_xScriptInvocation.is() && m_xFrame.is() )
315 Reference< XController > xController = m_xFrame->getController();
316 if ( xController .is() )
318 // try to obtain an XScriptInvocationContext interface, preferred from the
319 // mode, then from the controller
320 if ( !m_xScriptInvocation.set( xController->getModel(), UNO_QUERY ) )
321 m_xScriptInvocation.set( xController, UNO_QUERY );
323 else
325 if ( m_xFrame.is() )
327 SfxFrame* pFrame = nullptr;
328 for ( pFrame = SfxFrame::GetFirst(); pFrame; pFrame = SfxFrame::GetNext( *pFrame ) )
330 if ( pFrame->GetFrameInterface() == m_xFrame )
331 break;
333 SfxObjectShell* pDocShell = pFrame ? pFrame->GetCurrentDocument() : SfxObjectShell::Current();
334 if ( pDocShell )
336 Reference< XModel > xModel( pDocShell->GetModel() );
337 m_xScriptInvocation.set( xModel, UNO_QUERY );
342 return m_xScriptInvocation.is();
345 void ScriptProtocolHandler::createScriptProvider()
347 if ( m_xScriptProvider.is() )
348 return;
352 // first, ask the component supporting the XScriptInvocationContext interface
353 // (if there is one) for a script provider
354 if ( getScriptInvocation() )
356 Reference< XScriptProviderSupplier > xSPS( m_xScriptInvocation, UNO_QUERY );
357 if ( xSPS.is() )
358 m_xScriptProvider = xSPS->getScriptProvider();
361 // second, ask the model in our frame
362 if ( !m_xScriptProvider.is() && m_xFrame.is() )
364 Reference< XController > xController = m_xFrame->getController();
365 if ( xController .is() )
367 Reference< XScriptProviderSupplier > xSPS( xController->getModel(), UNO_QUERY );
368 if ( xSPS.is() )
369 m_xScriptProvider = xSPS->getScriptProvider();
374 // as a fallback, ask the controller
375 if ( !m_xScriptProvider.is() && m_xFrame.is() )
377 Reference< XScriptProviderSupplier > xSPS( m_xFrame->getController(), UNO_QUERY );
378 if ( xSPS.is() )
379 m_xScriptProvider = xSPS->getScriptProvider();
382 // if nothing of this is successful, use the master script provider
383 if ( !m_xScriptProvider.is() )
385 Reference< provider::XScriptProviderFactory > xFac =
386 provider::theMasterScriptProviderFactory::get( m_xContext );
388 Any aContext;
389 if ( getScriptInvocation() )
390 aContext <<= m_xScriptInvocation;
391 m_xScriptProvider.set( xFac->createScriptProvider( aContext ), UNO_SET_THROW );
394 catch ( const Exception & e )
396 css::uno::Any anyEx = cppu::getCaughtException();
397 throw css::lang::WrappedTargetRuntimeException(
398 "ScriptProtocolHandler::createScriptProvider: " + e.Message,
399 nullptr, anyEx );
403 ScriptProtocolHandler::ScriptProtocolHandler( const Reference< css::uno::XComponentContext > & xContext )
404 : m_bInitialised( false ), m_xContext( xContext )
408 ScriptProtocolHandler::~ScriptProtocolHandler()
412 /* XServiceInfo */
413 OUString SAL_CALL ScriptProtocolHandler::getImplementationName( )
415 return "com.sun.star.comp.ScriptProtocolHandler";
418 /* XServiceInfo */
419 sal_Bool SAL_CALL ScriptProtocolHandler::supportsService(const OUString& sServiceName )
421 return cppu::supportsService(this, sServiceName);
424 /* XServiceInfo */
425 Sequence< OUString > SAL_CALL ScriptProtocolHandler::getSupportedServiceNames()
427 return {"com.sun.star.frame.ProtocolHandler"};
430 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
431 scripting_ScriptProtocolHandler_get_implementation(
432 css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const&)
434 return cppu::acquire(new ScriptProtocolHandler(context));
437 } // namespace scripting_protocolhandler
440 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */