LibreOffice Module scripting (master) 1
scripthandler.cxx
Go to the documentation of this file.
1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
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/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
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 .
18 */
19
20#include "scripthandler.hxx"
21
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>
26
27#include <com/sun/star/document/XEmbeddedScripts.hpp>
28#include <com/sun/star/document/XScriptInvocationContext.hpp>
29
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>
36
37#include <sfx2/objsh.hxx>
38#include <sfx2/frame.hxx>
39#include <sfx2/sfxdlg.hxx>
41
45#include <officecfg/Office/Common.hxx>
46
47#include <com/sun/star/uri/XUriReference.hpp>
48#include <com/sun/star/uri/XVndSunStarScriptUrlReference.hpp>
49#include <com/sun/star/uri/UriReferenceFactory.hpp>
50
51#include <memory>
52
53using namespace ::com::sun::star;
54using namespace ::com::sun::star::uno;
55using namespace ::com::sun::star::frame;
56using namespace ::com::sun::star::util;
57using namespace ::com::sun::star::beans;
58using namespace ::com::sun::star::lang;
59using namespace ::com::sun::star::script;
60using namespace ::com::sun::star::script::provider;
61using namespace ::com::sun::star::document;
62
64{
65
67 const css::uno::Sequence < css::uno::Any >& aArguments )
68{
69 if ( m_bInitialised )
70 {
71 return ;
72 }
73
74 // first argument contains a reference to the frame (may be empty or the desktop,
75 // but usually it's a "real" frame)
76 if ( aArguments.hasElements() && !( aArguments[ 0 ] >>= m_xFrame ) )
77 {
78 throw RuntimeException( "ScriptProtocolHandler::initialize: could not extract reference to the frame" );
79 }
80
81 ENSURE_OR_THROW( m_xContext.is(), "ScriptProtocolHandler::initialize: No Service Manager available" );
82 m_bInitialised = true;
83}
84
85Reference< XDispatch > SAL_CALL ScriptProtocolHandler::queryDispatch(
86 const URL& aURL, const OUString&, sal_Int32 )
87{
88 Reference< XDispatch > xDispatcher;
89 // get scheme of url
90
91 Reference< uri::XUriReferenceFactory > xFac = uri::UriReferenceFactory::create( m_xContext );
92 Reference< uri::XUriReference > uriRef = xFac->parse( aURL.Complete );
93 if ( uriRef.is() )
94 {
95 if ( uriRef->getScheme() == "vnd.sun.star.script" )
96 {
97 xDispatcher = this;
98 }
99 }
100
101 return xDispatcher;
102}
103
104Sequence< Reference< XDispatch > > SAL_CALL
106const Sequence < DispatchDescriptor >& seqDescriptor )
107{
108 sal_Int32 nCount = seqDescriptor.getLength();
109 Sequence< Reference< XDispatch > > lDispatcher( nCount );
110 std::transform(seqDescriptor.begin(), seqDescriptor.end(), lDispatcher.getArray(),
111 [this](const DispatchDescriptor& rDescr) -> Reference<XDispatch> {
112 return queryDispatch(rDescr.FeatureURL, rDescr.FrameName, rDescr.SearchFlags); });
113 return lDispatcher;
114}
115
117 const URL& aURL, const Sequence < PropertyValue >& lArgs,
118 const Reference< XDispatchResultListener >& xListener )
119{
120 if (officecfg::Office::Common::Security::Scripting::DisableMacrosExecution::get())
121 return;
122
123 bool bSuccess = false;
124 Any invokeResult;
125 bool bCaughtException = false;
126 Any aException;
127
128 if ( m_bInitialised )
129 {
130 try
131 {
132 css::uno::Reference<css::uri::XUriReferenceFactory> urifac(
133 css::uri::UriReferenceFactory::create(m_xContext));
134 css::uno::Reference<css::uri::XVndSunStarScriptUrlReference> uri(
135 urifac->parse(aURL.Complete), css::uno::UNO_QUERY_THROW);
136 auto const loc = uri->getParameter("location");
137 bool bIsDocumentScript = loc == "document";
138
139 if ( bIsDocumentScript )
140 {
141 // obtain the component for our security check
142 Reference< XEmbeddedScripts > xDocumentScripts;
143 if ( getScriptInvocation() )
144 xDocumentScripts.set( m_xScriptInvocation->getScriptContainer(), UNO_SET_THROW );
145
146 OSL_ENSURE( xDocumentScripts.is(), "ScriptProtocolHandler::dispatchWithNotification: can't do the security check!" );
147 if ( !xDocumentScripts.is() || !xDocumentScripts->getAllowMacroExecution() )
148 {
149 if ( xListener.is() )
150 {
151 css::frame::DispatchResultEvent aEvent(
152 getXWeak(),
153 css::frame::DispatchResultState::FAILURE,
154 invokeResult );
155 try
156 {
157 xListener->dispatchFinished( aEvent ) ;
158 }
159 catch(const RuntimeException &)
160 {
161 TOOLS_WARN_EXCEPTION("scripting",
162 "ScriptProtocolHandler::dispatchWithNotification: caught RuntimeException"
163 "while dispatchFinished with failure of the execution");
164 }
165 }
166 return;
167 }
168 }
169
170 // Creates a ScriptProvider ( if one is not created already )
172
173 Reference< provider::XScript > xFunc =
174 m_xScriptProvider->getScript( aURL.Complete );
175 ENSURE_OR_THROW( xFunc.is(),
176 "ScriptProtocolHandler::dispatchWithNotification: validate xFunc - unable to obtain XScript interface" );
177
178
179 Sequence< Any > inArgs;
180 Sequence< Any > outArgs;
181 Sequence< sal_Int16 > outIndex;
182
183 if ( lArgs.hasElements() )
184 {
185 int argCount = 0;
186 for ( const auto& rArg : lArgs )
187 {
188 // Sometimes we get a propertyval with name = "Referer" or "SynchronMode". These
189 // are not actual arguments to be passed to script, but flags describing the
190 // call, so ignore. Who thought that passing such "meta-arguments" mixed in with
191 // real arguments was a good idea?
192 if ( (rArg.Name != "Referer" &&
193 rArg.Name != "SynchronMode") ||
194 rArg.Name.isEmpty() ) //TODO:???
195 {
196 inArgs.realloc( ++argCount );
197 inArgs.getArray()[ argCount - 1 ] = rArg.Value;
198 }
199 }
200 }
201
202 // attempt to protect the document against the script tampering with its Undo Context
203 std::unique_ptr< ::framework::DocumentUndoGuard > pUndoGuard;
204 if ( bIsDocumentScript )
205 pUndoGuard.reset( new ::framework::DocumentUndoGuard( m_xScriptInvocation ) );
206
207 bSuccess = false;
208 while ( !bSuccess )
209 {
210 std::exception_ptr aFirstCaughtException;
211 try
212 {
213 invokeResult = xFunc->invoke( inArgs, outIndex, outArgs );
214 bSuccess = true;
215 }
216 catch( const provider::ScriptFrameworkErrorException& se )
217 {
218 if (!aFirstCaughtException)
219 aFirstCaughtException = std::current_exception();
220
221 if ( se.errorType != provider::ScriptFrameworkErrorType::NO_SUCH_SCRIPT )
222 // the only condition which allows us to retry is if there is no method with the
223 // given name/signature
224 std::rethrow_exception(aFirstCaughtException);
225
226 if ( !inArgs.hasElements() )
227 // no chance to retry if we can't strip more in-args
228 std::rethrow_exception(aFirstCaughtException);
229
230 // strip one argument, then retry
231 inArgs.realloc( inArgs.getLength() - 1 );
232 }
233 }
234 }
235 // Office doesn't handle exceptions rethrown here very well, it cores,
236 // all we can is log them and then set fail for the dispatch event!
237 // (if there is a listener of course)
238 catch ( const Exception & e )
239 {
240 aException = ::cppu::getCaughtException();
241
242 invokeResult <<= "ScriptProtocolHandler::dispatch: caught "
243 + aException.getValueTypeName() + ": " + e.Message;
244
245 bCaughtException = true;
246 }
247 }
248 else
249 {
250 invokeResult <<= OUString(
251 "ScriptProtocolHandler::dispatchWithNotification failed, ScriptProtocolHandler not initialised"
252 );
253 }
254
255 if ( bCaughtException )
256 {
258 pFact->ShowAsyncScriptErrorDialog( nullptr, aException );
259 }
260
261 if ( !xListener.is() )
262 return;
263
264 // always call dispatchFinished(), because we didn't load a document but
265 // executed a macro instead!
266 css::frame::DispatchResultEvent aEvent;
267
268 aEvent.Source = getXWeak();
269 aEvent.Result = invokeResult;
270 if ( bSuccess )
271 {
272 aEvent.State = css::frame::DispatchResultState::SUCCESS;
273 }
274 else
275 {
276 aEvent.State = css::frame::DispatchResultState::FAILURE;
277 }
278
279 try
280 {
281 xListener->dispatchFinished( aEvent ) ;
282 }
283 catch(const RuntimeException &)
284 {
285 TOOLS_WARN_EXCEPTION("scripting",
286 "ScriptProtocolHandler::dispatchWithNotification: caught RuntimeException"
287 "while dispatchFinished" );
288 }
289}
290
292const URL& aURL, const Sequence< PropertyValue >& lArgs )
293{
294 dispatchWithNotification( aURL, lArgs, Reference< XDispatchResultListener >() );
295}
296
298const Reference< XStatusListener >&, const URL& )
299{
300 // implement if status is supported
301}
302
304const Reference< XStatusListener >&, const URL& )
305{}
306
307bool
309{
310 if ( !m_xScriptInvocation.is() && m_xFrame.is() )
311 {
312 Reference< XController > xController = m_xFrame->getController();
313 if ( xController .is() )
314 {
315 // try to obtain an XScriptInvocationContext interface, preferred from the
316 // mode, then from the controller
317 if ( !m_xScriptInvocation.set( xController->getModel(), UNO_QUERY ) )
318 m_xScriptInvocation.set( xController, UNO_QUERY );
319 }
320 else
321 {
322 if ( m_xFrame.is() )
323 {
324 SfxFrame* pFrame = nullptr;
325 for ( pFrame = SfxFrame::GetFirst(); pFrame; pFrame = SfxFrame::GetNext( *pFrame ) )
326 {
327 if ( pFrame->GetFrameInterface() == m_xFrame )
328 break;
329 }
330 if (SfxObjectShell* pDocShell = pFrame ? pFrame->GetCurrentDocument() : SfxObjectShell::Current())
331 {
332 Reference< XModel > xModel( pDocShell->GetModel() );
333 m_xScriptInvocation.set( xModel, UNO_QUERY );
334 }
335 }
336 }
337 }
338 return m_xScriptInvocation.is();
339}
340
342{
343 if ( m_xScriptProvider.is() )
344 return;
345
346 try
347 {
348 // first, ask the component supporting the XScriptInvocationContext interface
349 // (if there is one) for a script provider
350 if ( getScriptInvocation() )
351 {
352 Reference< XScriptProviderSupplier > xSPS( m_xScriptInvocation, UNO_QUERY );
353 if ( xSPS.is() )
354 m_xScriptProvider = xSPS->getScriptProvider();
355 }
356
357 // second, ask the model in our frame
358 if ( !m_xScriptProvider.is() && m_xFrame.is() )
359 {
360 Reference< XController > xController = m_xFrame->getController();
361 if ( xController .is() )
362 {
363 Reference< XScriptProviderSupplier > xSPS( xController->getModel(), UNO_QUERY );
364 if ( xSPS.is() )
365 m_xScriptProvider = xSPS->getScriptProvider();
366 }
367 }
368
369
370 // as a fallback, ask the controller
371 if ( !m_xScriptProvider.is() && m_xFrame.is() )
372 {
373 Reference< XScriptProviderSupplier > xSPS( m_xFrame->getController(), UNO_QUERY );
374 if ( xSPS.is() )
375 m_xScriptProvider = xSPS->getScriptProvider();
376 }
377
378 // if nothing of this is successful, use the master script provider
379 if ( !m_xScriptProvider.is() )
380 {
381 Reference< provider::XScriptProviderFactory > xFac =
382 provider::theMasterScriptProviderFactory::get( m_xContext );
383
384 Any aContext;
385 if ( getScriptInvocation() )
386 aContext <<= m_xScriptInvocation;
387 m_xScriptProvider.set( xFac->createScriptProvider( aContext ), UNO_SET_THROW );
388 }
389 }
390 catch ( const Exception & e )
391 {
392 css::uno::Any anyEx = cppu::getCaughtException();
393 throw css::lang::WrappedTargetRuntimeException(
394 "ScriptProtocolHandler::createScriptProvider: " + e.Message,
395 nullptr, anyEx );
396 }
397}
398
399ScriptProtocolHandler::ScriptProtocolHandler( const Reference< css::uno::XComponentContext > & xContext )
400 : m_bInitialised( false ), m_xContext( xContext )
401{
402}
403
405{
406}
407
408/* XServiceInfo */
410{
411 return "com.sun.star.comp.ScriptProtocolHandler";
412}
413
414/* XServiceInfo */
415sal_Bool SAL_CALL ScriptProtocolHandler::supportsService(const OUString& sServiceName )
416{
418}
419
420/* XServiceInfo */
422{
423 return {"com.sun.star.frame.ProtocolHandler"};
424}
425
426extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
428 css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const&)
429{
430 return cppu::acquire(new ScriptProtocolHandler(context));
431}
432
433} // namespace scripting_protocolhandler
434
435
436/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Reference< XComponentContext > m_xContext
constexpr OUStringLiteral sServiceName
AnyEventRef aEvent
virtual void ShowAsyncScriptErrorDialog(weld::Window *pParent, const css::uno::Any &rException)=0
static SfxAbstractDialogFactory * Create()
const css::uno::Reference< css::frame::XFrame > & GetFrameInterface() const
SAL_WARN_UNUSED_RESULT SfxObjectShell * GetCurrentDocument() const
static SAL_WARN_UNUSED_RESULT SfxFrame * GetNext(SfxFrame &)
static SAL_WARN_UNUSED_RESULT SfxFrame * GetFirst()
static SAL_WARN_UNUSED_RESULT SfxObjectShell * Current()
ScriptProtocolHandler(const css::uno::Reference< css::uno::XComponentContext > &xContext)
virtual void SAL_CALL removeStatusListener(const css::uno::Reference< css::frame::XStatusListener > &xControl, const css::util::URL &aURL) override
virtual sal_Bool SAL_CALL supportsService(const OUString &sServiceName) override
virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL queryDispatch(const css::util::URL &aURL, const OUString &sTargetFrameName, sal_Int32 eSearchFlags) override
virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches(const css::uno::Sequence< css::frame::DispatchDescriptor > &seqDescriptor) override
virtual void SAL_CALL addStatusListener(const css::uno::Reference< css::frame::XStatusListener > &xControl, const css::util::URL &aURL) override
virtual OUString SAL_CALL getImplementationName() override
virtual void SAL_CALL dispatch(const css::util::URL &aURL, const css::uno::Sequence< css::beans::PropertyValue > &lArgs) override
virtual void SAL_CALL initialize(const css::uno::Sequence< css::uno::Any > &aArguments) override
css::uno::Reference< css::frame::XFrame > m_xFrame
css::uno::Reference< css::script::provider::XScriptProvider > m_xScriptProvider
css::uno::Reference< css::document::XScriptInvocationContext > m_xScriptInvocation
virtual void SAL_CALL dispatchWithNotification(const css::util::URL &aURL, const css::uno::Sequence< css::beans::PropertyValue > &lArgs, const css::uno::Reference< css::frame::XDispatchResultListener > &Listener) override
css::uno::Reference< css::uno::XComponentContext > m_xContext
virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override
int nCount
#define TOOLS_WARN_EXCEPTION(area, stream)
#define ENSURE_OR_THROW(c, m)
URL aURL
Sequence< PropertyValue > aArguments
@ Exception
bool CPPUHELPER_DLLPUBLIC supportsService(css::lang::XServiceInfo *implementation, rtl::OUString const &name)
Any SAL_CALL getCaughtException()
SAL_DLLPUBLIC_EXPORT css::uno::XInterface * scripting_ScriptProtocolHandler_get_implementation(css::uno::XComponentContext *context, css::uno::Sequence< css::uno::Any > const &)
Reference< XController > xController
Reference< XModel > xModel
unsigned char sal_Bool