Coverage Report

Created: 2026-10-14 09:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libreoffice/sfx2/source/appl/macroloader.cxx
Line
Count
Source
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 <config_features.h>
21
22
#include <macroloader.hxx>
23
24
#include <com/sun/star/frame/DispatchResultState.hpp>
25
#include <com/sun/star/frame/XModel3.hpp>
26
#include <basic/basmgr.hxx>
27
#include <basic/sbuno.hxx>
28
#include <basic/sberrors.hxx>
29
#include <cppuhelper/supportsservice.hxx>
30
#include <cppuhelper/weak.hxx>
31
#include <cppuhelper/weakref.hxx>
32
#include <framework/documentundoguard.hxx>
33
#include <sfx2/app.hxx>
34
#include <sfx2/frame.hxx>
35
#include <sfx2/objsh.hxx>
36
#include <tools/urlobj.hxx>
37
#include <unotools/securityoptions.hxx>
38
#include <vcl/svapp.hxx>
39
40
#include <memory>
41
42
using namespace ::com::sun::star;
43
using namespace ::com::sun::star::frame;
44
using namespace ::com::sun::star::lang;
45
using namespace ::com::sun::star::uno;
46
using namespace ::com::sun::star::util;
47
48
SfxMacroLoader::SfxMacroLoader(const css::uno::Sequence< css::uno::Any >& aArguments)
49
0
{
50
0
    Reference < XFrame > xFrame;
51
0
    if ( aArguments.hasElements() )
52
0
    {
53
0
        aArguments[0] >>= xFrame;
54
0
        m_xFrame = xFrame;
55
0
    }
56
0
}
57
58
OUString SAL_CALL SfxMacroLoader::getImplementationName()
59
0
{
60
0
    return u"com.sun.star.comp.sfx2.SfxMacroLoader"_ustr;
61
0
}
62
63
sal_Bool SAL_CALL SfxMacroLoader::supportsService(OUString const & ServiceName)
64
0
{
65
0
    return cppu::supportsService(this, ServiceName);
66
0
}
67
68
css::uno::Sequence<OUString> SAL_CALL SfxMacroLoader::getSupportedServiceNames()
69
0
{
70
0
    return { u"com.sun.star.frame.ProtocolHandler"_ustr };
71
0
}
72
73
SfxObjectShell* SfxMacroLoader::GetObjectShell(const Reference <XFrame>& xFrame)
74
0
{
75
0
    SfxObjectShell* pDocShell = nullptr;
76
77
0
    if ( xFrame.is() )
78
0
    {
79
0
        SfxFrame* pFrame=nullptr;
80
0
        for ( pFrame = SfxFrame::GetFirst(); pFrame; pFrame = SfxFrame::GetNext( *pFrame ) )
81
0
        {
82
0
            if ( pFrame->GetFrameInterface() == xFrame )
83
0
                break;
84
0
        }
85
86
0
        if ( pFrame )
87
0
            pDocShell = pFrame->GetCurrentDocument();
88
0
    }
89
90
0
    return pDocShell;
91
0
}
92
93
SfxObjectShell* SfxMacroLoader::GetObjectShell_Impl()
94
0
{
95
0
    Reference < XFrame > xFrame( m_xFrame.get(), UNO_QUERY );
96
0
    return SfxMacroLoader::GetObjectShell(xFrame);
97
0
}
98
99
uno::Reference<frame::XDispatch> SAL_CALL SfxMacroLoader::queryDispatch(
100
    const util::URL&   aURL            ,
101
    const OUString&               /*sTargetFrameName*/,
102
    sal_Int32                            /*nSearchFlags*/    )
103
0
{
104
0
    uno::Reference<frame::XDispatch> xDispatcher;
105
0
    if(aURL.Complete.startsWith("macro:"))
106
0
        xDispatcher = this;
107
0
    return xDispatcher;
108
0
}
109
110
111
uno::Sequence< uno::Reference<frame::XDispatch> > SAL_CALL
112
                SfxMacroLoader::queryDispatches( const uno::Sequence < frame::DispatchDescriptor >& seqDescriptor )
113
0
{
114
0
    sal_Int32 nCount = seqDescriptor.getLength();
115
0
    uno::Sequence< uno::Reference<frame::XDispatch> > lDispatcher(nCount);
116
0
    std::transform(seqDescriptor.begin(), seqDescriptor.end(), lDispatcher.getArray(),
117
0
        [this](const frame::DispatchDescriptor& rDescr) -> uno::Reference<frame::XDispatch> {
118
0
            return queryDispatch(rDescr.FeatureURL, rDescr.FrameName, rDescr.SearchFlags); });
119
0
    return lDispatcher;
120
0
}
121
122
123
void SAL_CALL SfxMacroLoader::dispatchWithNotification(
124
    const util::URL& aURL, const uno::Sequence<beans::PropertyValue>& /*lArgs*/,
125
    const uno::Reference<frame::XDispatchResultListener>& xListener )
126
0
{
127
0
    SolarMutexGuard aGuard;
128
129
0
    uno::Any aAny;
130
0
    ErrCode nErr = loadMacro( aURL.Complete, aAny, GetObjectShell_Impl() );
131
0
    if( !xListener.is() )
132
0
        return;
133
134
    // always call dispatchFinished(), because we didn't load a document but
135
    // executed a macro instead!
136
0
    frame::DispatchResultEvent aEvent;
137
138
0
    aEvent.Source = getXWeak();
139
0
    if( nErr == ERRCODE_NONE )
140
0
        aEvent.State = frame::DispatchResultState::SUCCESS;
141
0
    else
142
0
        aEvent.State = frame::DispatchResultState::FAILURE;
143
144
0
    xListener->dispatchFinished( aEvent ) ;
145
0
}
146
147
uno::Any SAL_CALL SfxMacroLoader::dispatchWithReturnValue(
148
    const util::URL& aURL, const uno::Sequence<beans::PropertyValue>& )
149
0
{
150
0
    uno::Any aRet;
151
0
    ErrCode nErr = loadMacro( aURL.Complete, aRet, GetObjectShell_Impl() );
152
153
    // aRet gets set to a different value only if nErr == ERRCODE_NONE
154
    // Return it in such case to preserve the original behaviour
155
156
    // In all other cases (nErr != ERRCODE_NONE), the calling code gets
157
    // the actual error code back
158
0
    if ( nErr != ERRCODE_NONE )
159
0
    {
160
0
        beans::PropertyValue aErrorCode;
161
162
0
        aErrorCode.Name = "ErrorCode";
163
0
        aErrorCode.Value <<= sal_uInt32(nErr);
164
165
0
        aRet <<= aErrorCode;
166
0
    }
167
168
0
    return aRet;
169
0
}
170
171
void SAL_CALL SfxMacroLoader::dispatch(
172
    const util::URL& aURL, const uno::Sequence<beans::PropertyValue>& /*lArgs*/ )
173
0
{
174
0
    SolarMutexGuard aGuard;
175
176
0
    uno::Any aAny;
177
0
    loadMacro( aURL.Complete, aAny, GetObjectShell_Impl() );
178
0
}
179
180
void SAL_CALL SfxMacroLoader::addStatusListener(
181
    const uno::Reference< frame::XStatusListener >& ,
182
    const util::URL&                                                    )
183
0
{
184
    /* TODO
185
            How we can handle different listener for further coming or currently running dispatch() jobs
186
            without any inconsistency!
187
     */
188
0
}
189
190
191
void SAL_CALL SfxMacroLoader::removeStatusListener(
192
    const uno::Reference< frame::XStatusListener >&,
193
    const util::URL&                                                  )
194
0
{
195
0
}
196
197
ErrCode SfxMacroLoader::loadMacro( const OUString& rURL, css::uno::Any& rRetval, SfxObjectShell* pSh )
198
0
{
199
0
#if !HAVE_FEATURE_SCRIPTING
200
0
    (void) rURL;
201
0
    (void) rRetval;
202
0
    (void) pSh;
203
0
    return ERRCODE_BASIC_PROC_UNDEFINED;
204
#else
205
    if ( SvtSecurityOptions::IsMacroDisabled() )
206
        return ERRCODE_IO_ACCESSDENIED;
207
208
    SfxObjectShell* pCurrent = pSh;
209
    if ( !pCurrent )
210
        // all not full qualified names use the BASIC of the given or current document
211
        pCurrent = SfxObjectShell::Current();
212
213
    // 'macro:///lib.mod.proc(args)' => macro of App-BASIC
214
    // 'macro://[docname|.]/lib.mod.proc(args)' => macro of current or qualified document
215
    // 'macro://obj.method(args)' => direct API call, execute it via App-BASIC
216
    const OUString& aMacro( rURL );
217
    sal_Int32 nThirdSlashPos = aMacro.indexOf( '/', 8 );
218
    sal_Int32 nArgsPos = aMacro.indexOf( '(' );
219
    BasicManager *pAppMgr = SfxApplication::GetBasicManager();
220
    BasicManager *pBasMgr = nullptr;
221
    ErrCode nErr = ERRCODE_NONE;
222
223
    // should a macro function be executed ( no direct API call)?
224
    if ( -1 != nThirdSlashPos && ( -1 == nArgsPos || nThirdSlashPos < nArgsPos ) )
225
    {
226
        // find BasicManager
227
        SfxObjectShell* pDoc = nullptr;
228
        OUString aBasMgrName( INetURLObject::decode(aMacro.subView( 8, nThirdSlashPos-8 ), INetURLObject::DecodeMechanism::WithCharset) );
229
        if ( aBasMgrName.isEmpty() )
230
            pBasMgr = pAppMgr;
231
        else if ( aBasMgrName == "." )
232
        {
233
            // current/actual document
234
            pDoc = pCurrent;
235
            if (pDoc)
236
                pBasMgr = pDoc->GetBasicManager();
237
        }
238
        else
239
        {
240
            // full qualified name, find document by name
241
            for ( SfxObjectShell *pObjSh = SfxObjectShell::GetFirst();
242
                    pObjSh && !pBasMgr;
243
                    pObjSh = SfxObjectShell::GetNext(*pObjSh) )
244
                if ( aBasMgrName == pObjSh->GetTitle(SFX_TITLE_APINAME) )
245
                {
246
                    pDoc = pObjSh;
247
                    pBasMgr = pDoc->GetBasicManager();
248
                }
249
        }
250
251
        if ( pBasMgr )
252
        {
253
            const bool bIsAppBasic = ( pBasMgr == pAppMgr );
254
            const bool bIsDocBasic = ( pBasMgr != pAppMgr );
255
256
            if ( pDoc )
257
            {
258
                // security check for macros from document basic if an SFX doc is given
259
                if ( !pDoc->AdjustMacroMode() )
260
                    // check forbids execution
261
                    return ERRCODE_IO_ACCESSDENIED;
262
            }
263
264
            // find BASIC method
265
            OUString aQualifiedMethod( INetURLObject::decode(aMacro.subView( nThirdSlashPos+1 ), INetURLObject::DecodeMechanism::WithCharset) );
266
            OUString aArgs;
267
            if ( -1 != nArgsPos )
268
            {
269
                // remove arguments from macro name
270
                aArgs = aQualifiedMethod.copy( nArgsPos - nThirdSlashPos - 1 );
271
                aQualifiedMethod = aQualifiedMethod.copy( 0, nArgsPos - nThirdSlashPos - 1 );
272
            }
273
274
            if ( pBasMgr->HasMacro( aQualifiedMethod ) )
275
            {
276
                Any aOldThisComponent;
277
                const bool bSetDocMacroMode = ( pDoc != nullptr ) && bIsDocBasic;
278
                const bool bSetGlobalThisComponent = ( pDoc != nullptr ) && bIsAppBasic;
279
                if ( bSetDocMacroMode )
280
                {
281
                    // mark document: it executes an own macro, so it's in a modal mode
282
                    pDoc->SetMacroMode_Impl();
283
                }
284
285
                if ( bSetGlobalThisComponent )
286
                {
287
                    // document is executed via AppBASIC, adjust ThisComponent variable
288
                    pAppMgr->SetGlobalUNOConstant( u"ThisComponent"_ustr, Any( pDoc->GetModel() ), &aOldThisComponent );
289
                }
290
291
                // just to let the shell be alive
292
                SfxObjectShellRef xKeepDocAlive = pDoc;
293
294
                {
295
                    // attempt to protect the document against the script tampering with its Undo Context
296
                    std::optional< ::framework::DocumentUndoGuard > pUndoGuard;
297
                    if ( bIsDocBasic )
298
                        pUndoGuard.emplace( pDoc->GetModel() );
299
300
                    // execute the method
301
                    SbxVariableRef retValRef = new SbxVariable;
302
                    nErr = pBasMgr->ExecuteMacro( aQualifiedMethod, aArgs, retValRef.get() );
303
                    if ( nErr == ERRCODE_NONE )
304
                        rRetval = sbxToUnoValue( retValRef.get() );
305
                }
306
307
                if ( bSetGlobalThisComponent )
308
                {
309
                    pAppMgr->SetGlobalUNOConstant( u"ThisComponent"_ustr, aOldThisComponent );
310
                }
311
312
                if ( bSetDocMacroMode )
313
                {
314
                    // remove flag for modal mode
315
                    pDoc->SetMacroMode_Impl( false );
316
                }
317
            }
318
            else
319
                nErr = ERRCODE_BASIC_PROC_UNDEFINED;
320
        }
321
        else
322
            nErr = ERRCODE_IO_NOTEXISTS;
323
    }
324
    else
325
    {
326
        // direct API call on a specified object
327
        OUString aCall =
328
            "[" +
329
            INetURLObject::decode(aMacro.subView(6),
330
                    INetURLObject::DecodeMechanism::WithCharset) +
331
            "]";
332
        pAppMgr->GetLib(0)->Execute(aCall);
333
        nErr = SbxBase::GetError();
334
    }
335
336
    SbxBase::ResetError();
337
    return nErr;
338
#endif
339
0
}
340
341
extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface *
342
com_sun_star_comp_sfx2_SfxMacroLoader_get_implementation(
343
    css::uno::XComponentContext *,
344
    css::uno::Sequence<css::uno::Any> const &arguments)
345
0
{
346
0
    return cppu::acquire(new SfxMacroLoader(arguments));
347
0
}
348
349
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */