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